NetworkPrinterOutputDevice.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.i18n import i18nCatalog
  4. from UM.Application import Application
  5. from UM.Logger import Logger
  6. from UM.Signal import signalemitter
  7. from UM.Message import Message
  8. import UM.Settings.ContainerRegistry
  9. import UM.Version #To compare firmware version numbers.
  10. from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
  11. import cura.Settings.ExtruderManager
  12. from PyQt5.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager, QNetworkReply
  13. from PyQt5.QtCore import QUrl, QTimer, pyqtSignal, pyqtProperty, pyqtSlot, QCoreApplication
  14. from PyQt5.QtGui import QImage
  15. from PyQt5.QtWidgets import QMessageBox
  16. import json
  17. import os
  18. import gzip
  19. import zlib
  20. from time import time
  21. from time import sleep
  22. i18n_catalog = i18nCatalog("cura")
  23. from enum import IntEnum
  24. class AuthState(IntEnum):
  25. NotAuthenticated = 1
  26. AuthenticationRequested = 2
  27. Authenticated = 3
  28. AuthenticationDenied = 4
  29. ## Network connected (wifi / lan) printer that uses the Ultimaker API
  30. @signalemitter
  31. class NetworkPrinterOutputDevice(PrinterOutputDevice):
  32. def __init__(self, key, address, properties, api_prefix):
  33. super().__init__(key)
  34. self._address = address
  35. self._key = key
  36. self._properties = properties # Properties dict as provided by zero conf
  37. self._api_prefix = api_prefix
  38. self._gcode = None
  39. self._print_finished = True # _print_finsihed == False means we're halfway in a print
  40. self._use_gzip = True # Should we use g-zip compression before sending the data?
  41. # This holds the full JSON file that was received from the last request.
  42. # The JSON looks like:
  43. #{
  44. # "led": {"saturation": 0.0, "brightness": 100.0, "hue": 0.0},
  45. # "beep": {},
  46. # "network": {
  47. # "wifi_networks": [],
  48. # "ethernet": {"connected": true, "enabled": true},
  49. # "wifi": {"ssid": "xxxx", "connected": False, "enabled": False}
  50. # },
  51. # "diagnostics": {},
  52. # "bed": {"temperature": {"target": 60.0, "current": 44.4}},
  53. # "heads": [{
  54. # "max_speed": {"z": 40.0, "y": 300.0, "x": 300.0},
  55. # "position": {"z": 20.0, "y": 6.0, "x": 180.0},
  56. # "fan": 0.0,
  57. # "jerk": {"z": 0.4, "y": 20.0, "x": 20.0},
  58. # "extruders": [
  59. # {
  60. # "feeder": {"max_speed": 45.0, "jerk": 5.0, "acceleration": 3000.0},
  61. # "active_material": {"guid": "xxxxxxx", "length_remaining": -1.0},
  62. # "hotend": {"temperature": {"target": 0.0, "current": 22.8}, "id": "AA 0.4"}
  63. # },
  64. # {
  65. # "feeder": {"max_speed": 45.0, "jerk": 5.0, "acceleration": 3000.0},
  66. # "active_material": {"guid": "xxxx", "length_remaining": -1.0},
  67. # "hotend": {"temperature": {"target": 0.0, "current": 22.8}, "id": "BB 0.4"}
  68. # }
  69. # ],
  70. # "acceleration": 3000.0
  71. # }],
  72. # "status": "printing"
  73. #}
  74. self._json_printer_state = {}
  75. ## Todo: Hardcoded value now; we should probably read this from the machine file.
  76. ## It's okay to leave this for now, as this plugin is um3 only (and has 2 extruders by definition)
  77. self._num_extruders = 2
  78. # These are reinitialised here (from PrinterOutputDevice) to match the new _num_extruders
  79. self._hotend_temperatures = [0] * self._num_extruders
  80. self._target_hotend_temperatures = [0] * self._num_extruders
  81. self._material_ids = [""] * self._num_extruders
  82. self._hotend_ids = [""] * self._num_extruders
  83. self._target_bed_temperature = 0
  84. self._processing_preheat_requests = True
  85. self.setPriority(2) # Make sure the output device gets selected above local file output
  86. self.setName(key)
  87. self.setShortDescription(i18n_catalog.i18nc("@action:button Preceded by 'Ready to'.", "Print over network"))
  88. self.setDescription(i18n_catalog.i18nc("@properties:tooltip", "Print over network"))
  89. self.setIconName("print")
  90. self._manager = None
  91. self._post_request = None
  92. self._post_reply = None
  93. self._post_multi_part = None
  94. self._post_part = None
  95. self._material_multi_part = None
  96. self._material_part = None
  97. self._progress_message = None
  98. self._error_message = None
  99. self._connection_message = None
  100. self._update_timer = QTimer()
  101. self._update_timer.setInterval(2000) # TODO; Add preference for update interval
  102. self._update_timer.setSingleShot(False)
  103. self._update_timer.timeout.connect(self._update)
  104. self._camera_timer = QTimer()
  105. self._camera_timer.setInterval(500) # Todo: Add preference for camera update interval
  106. self._camera_timer.setSingleShot(False)
  107. self._camera_timer.timeout.connect(self._updateCamera)
  108. self._image_request = None
  109. self._image_reply = None
  110. self._use_stream = True
  111. self._stream_buffer = b""
  112. self._stream_buffer_start_index = -1
  113. self._camera_image_id = 0
  114. self._authentication_counter = 0
  115. self._max_authentication_counter = 5 * 60 # Number of attempts before authentication timed out (5 min)
  116. self._authentication_timer = QTimer()
  117. self._authentication_timer.setInterval(1000) # TODO; Add preference for update interval
  118. self._authentication_timer.setSingleShot(False)
  119. self._authentication_timer.timeout.connect(self._onAuthenticationTimer)
  120. self._authentication_request_active = False
  121. self._authentication_state = AuthState.NotAuthenticated
  122. self._authentication_id = None
  123. self._authentication_key = None
  124. self._authentication_requested_message = Message(i18n_catalog.i18nc("@info:status", "Access to the printer requested. Please approve the request on the printer"), lifetime = 0, dismissable = False, progress = 0)
  125. self._authentication_failed_message = Message(i18n_catalog.i18nc("@info:status", ""))
  126. self._authentication_failed_message.addAction("Retry", i18n_catalog.i18nc("@action:button", "Retry"), None, i18n_catalog.i18nc("@info:tooltip", "Re-send the access request"))
  127. self._authentication_failed_message.actionTriggered.connect(self.requestAuthentication)
  128. self._authentication_succeeded_message = Message(i18n_catalog.i18nc("@info:status", "Access to the printer accepted"))
  129. self._not_authenticated_message = Message(i18n_catalog.i18nc("@info:status", "No access to print with this printer. Unable to send print job."))
  130. self._not_authenticated_message.addAction("Request", i18n_catalog.i18nc("@action:button", "Request Access"), None, i18n_catalog.i18nc("@info:tooltip", "Send access request to the printer"))
  131. self._not_authenticated_message.actionTriggered.connect(self.requestAuthentication)
  132. self._camera_image = QImage()
  133. self._material_post_objects = {}
  134. self._connection_state_before_timeout = None
  135. self._last_response_time = time()
  136. self._last_request_time = None
  137. self._response_timeout_time = 10
  138. self._recreate_network_manager_time = 30 # If we have no connection, re-create network manager every 30 sec.
  139. self._recreate_network_manager_count = 1
  140. self._send_gcode_start = time() # Time when the sending of the g-code started.
  141. self._last_command = ""
  142. self._compressing_print = False
  143. printer_type = self._properties.get(b"machine", b"").decode("utf-8")
  144. if printer_type.startswith("9511"):
  145. self._updatePrinterType("ultimaker3_extended")
  146. elif printer_type.startswith("9066"):
  147. self._updatePrinterType("ultimaker3")
  148. else:
  149. self._updatePrinterType("unknown")
  150. def _onNetworkAccesibleChanged(self, accessible):
  151. Logger.log("d", "Network accessible state changed to: %s", accessible)
  152. def _onAuthenticationTimer(self):
  153. self._authentication_counter += 1
  154. self._authentication_requested_message.setProgress(self._authentication_counter / self._max_authentication_counter * 100)
  155. if self._authentication_counter > self._max_authentication_counter:
  156. self._authentication_timer.stop()
  157. Logger.log("i", "Authentication timer ended. Setting authentication to denied")
  158. self.setAuthenticationState(AuthState.AuthenticationDenied)
  159. def _onAuthenticationRequired(self, reply, authenticator):
  160. if self._authentication_id is not None and self._authentication_key is not None:
  161. Logger.log("d", "Authentication was required. Setting up authenticator with ID %s",self._authentication_id )
  162. authenticator.setUser(self._authentication_id)
  163. authenticator.setPassword(self._authentication_key)
  164. else:
  165. Logger.log("d", "No authentication was required. The ID is: %s", self._authentication_id)
  166. def getProperties(self):
  167. return self._properties
  168. @pyqtSlot(str, result = str)
  169. def getProperty(self, key):
  170. key = key.encode("utf-8")
  171. if key in self._properties:
  172. return self._properties.get(key, b"").decode("utf-8")
  173. else:
  174. return ""
  175. ## Get the unique key of this machine
  176. # \return key String containing the key of the machine.
  177. @pyqtSlot(result = str)
  178. def getKey(self):
  179. return self._key
  180. ## The IP address of the printer.
  181. @pyqtProperty(str, constant = True)
  182. def address(self):
  183. return self._properties.get(b"address", b"").decode("utf-8")
  184. ## Name of the printer (as returned from the ZeroConf properties)
  185. @pyqtProperty(str, constant = True)
  186. def name(self):
  187. return self._properties.get(b"name", b"").decode("utf-8")
  188. ## Firmware version (as returned from the ZeroConf properties)
  189. @pyqtProperty(str, constant=True)
  190. def firmwareVersion(self):
  191. return self._properties.get(b"firmware_version", b"").decode("utf-8")
  192. ## IPadress of this printer
  193. @pyqtProperty(str, constant=True)
  194. def ipAddress(self):
  195. return self._address
  196. ## Pre-heats the heated bed of the printer.
  197. #
  198. # \param temperature The temperature to heat the bed to, in degrees
  199. # Celsius.
  200. # \param duration How long the bed should stay warm, in seconds.
  201. @pyqtSlot(float, float)
  202. def preheatBed(self, temperature, duration):
  203. temperature = round(temperature) #The API doesn't allow floating point.
  204. duration = round(duration)
  205. if UM.Version.Version(self.firmwareVersion) < UM.Version.Version("3.5.92"): #Real bed pre-heating support is implemented from 3.5.92 and up.
  206. self.setTargetBedTemperature(temperature = temperature) #No firmware-side duration support then.
  207. return
  208. url = QUrl("http://" + self._address + self._api_prefix + "printer/bed/pre_heat")
  209. if duration > 0:
  210. data = """{"temperature": "%i", "timeout": "%i"}""" % (temperature, duration)
  211. else:
  212. data = """{"temperature": "%i"}""" % temperature
  213. Logger.log("i", "Pre-heating bed to %i degrees.", temperature)
  214. put_request = QNetworkRequest(url)
  215. put_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
  216. self._processing_preheat_requests = False
  217. self._manager.put(put_request, data.encode())
  218. self._preheat_bed_timer.start(self._preheat_bed_timeout * 1000) #Times 1000 because it needs to be provided as milliseconds.
  219. self.preheatBedRemainingTimeChanged.emit()
  220. ## Cancels pre-heating the heated bed of the printer.
  221. #
  222. # If the bed is not pre-heated, nothing happens.
  223. @pyqtSlot()
  224. def cancelPreheatBed(self):
  225. Logger.log("i", "Cancelling pre-heating of the bed.")
  226. self.preheatBed(temperature = 0, duration = 0)
  227. self._preheat_bed_timer.stop()
  228. self._preheat_bed_timer.setInterval(0)
  229. self.preheatBedRemainingTimeChanged.emit()
  230. ## Changes the target bed temperature on the printer.
  231. #
  232. # /param temperature The new target temperature of the bed.
  233. def _setTargetBedTemperature(self, temperature):
  234. if self._target_bed_temperature == temperature:
  235. return
  236. self._target_bed_temperature = temperature
  237. self.targetBedTemperatureChanged.emit()
  238. url = QUrl("http://" + self._address + self._api_prefix + "printer/bed/temperature/target")
  239. data = str(temperature)
  240. put_request = QNetworkRequest(url)
  241. put_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
  242. self._manager.put(put_request, data.encode())
  243. def _stopCamera(self):
  244. self._camera_timer.stop()
  245. if self._image_reply:
  246. self._image_reply.abort()
  247. self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
  248. self._image_reply = None
  249. self._image_request = None
  250. def _startCamera(self):
  251. if self._use_stream:
  252. self._startCameraStream()
  253. else:
  254. self._camera_timer.start()
  255. def _startCameraStream(self):
  256. ## Request new image
  257. url = QUrl("http://" + self._address + ":8080/?action=stream")
  258. self._image_request = QNetworkRequest(url)
  259. self._image_reply = self._manager.get(self._image_request)
  260. self._image_reply.downloadProgress.connect(self._onStreamDownloadProgress)
  261. def _updateCamera(self):
  262. if not self._manager.networkAccessible():
  263. return
  264. ## Request new image
  265. url = QUrl("http://" + self._address + ":8080/?action=snapshot")
  266. image_request = QNetworkRequest(url)
  267. self._manager.get(image_request)
  268. self._last_request_time = time()
  269. ## Set the authentication state.
  270. # \param auth_state \type{AuthState} Enum value representing the new auth state
  271. def setAuthenticationState(self, auth_state):
  272. if auth_state == self._authentication_state:
  273. return # Nothing to do here.
  274. if auth_state == AuthState.AuthenticationRequested:
  275. Logger.log("d", "Authentication state changed to authentication requested.")
  276. self.setAcceptsCommands(False)
  277. self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network. Please approve the access request on the printer."))
  278. self._authentication_requested_message.show()
  279. self._authentication_request_active = True
  280. self._authentication_timer.start() # Start timer so auth will fail after a while.
  281. elif auth_state == AuthState.Authenticated:
  282. Logger.log("d", "Authentication state changed to authenticated")
  283. self.setAcceptsCommands(True)
  284. self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network."))
  285. self._authentication_requested_message.hide()
  286. if self._authentication_request_active:
  287. self._authentication_succeeded_message.show()
  288. # Stop waiting for a response
  289. self._authentication_timer.stop()
  290. self._authentication_counter = 0
  291. # Once we are authenticated we need to send all material profiles.
  292. self.sendMaterialProfiles()
  293. elif auth_state == AuthState.AuthenticationDenied:
  294. self.setAcceptsCommands(False)
  295. self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network. No access to control the printer."))
  296. self._authentication_requested_message.hide()
  297. if self._authentication_request_active:
  298. if self._authentication_timer.remainingTime() > 0:
  299. Logger.log("d", "Authentication state changed to authentication denied before the request timeout.")
  300. self._authentication_failed_message.setText(i18n_catalog.i18nc("@info:status", "Access request was denied on the printer."))
  301. else:
  302. Logger.log("d", "Authentication state changed to authentication denied due to a timeout")
  303. self._authentication_failed_message.setText(i18n_catalog.i18nc("@info:status", "Access request failed due to a timeout."))
  304. self._authentication_failed_message.show()
  305. self._authentication_request_active = False
  306. # Stop waiting for a response
  307. self._authentication_timer.stop()
  308. self._authentication_counter = 0
  309. self._authentication_state = auth_state
  310. self.authenticationStateChanged.emit()
  311. authenticationStateChanged = pyqtSignal()
  312. @pyqtProperty(int, notify = authenticationStateChanged)
  313. def authenticationState(self):
  314. return self._authentication_state
  315. @pyqtSlot()
  316. def requestAuthentication(self, message_id = None, action_id = "Retry"):
  317. if action_id == "Request" or action_id == "Retry":
  318. self._authentication_failed_message.hide()
  319. self._not_authenticated_message.hide()
  320. self._authentication_state = AuthState.NotAuthenticated
  321. self._authentication_counter = 0
  322. self._authentication_requested_message.setProgress(0)
  323. self._authentication_id = None
  324. self._authentication_key = None
  325. self._createNetworkManager() # Re-create network manager to force re-authentication.
  326. ## Request data from the connected device.
  327. def _update(self):
  328. if self._last_response_time:
  329. time_since_last_response = time() - self._last_response_time
  330. else:
  331. time_since_last_response = 0
  332. if self._last_request_time:
  333. time_since_last_request = time() - self._last_request_time
  334. else:
  335. time_since_last_request = float("inf") # An irrelevantly large number of seconds
  336. # Connection is in timeout, check if we need to re-start the connection.
  337. # Sometimes the qNetwork manager incorrectly reports the network status on Mac & Windows.
  338. # Re-creating the QNetworkManager seems to fix this issue.
  339. if self._last_response_time and self._connection_state_before_timeout:
  340. if time_since_last_response > self._recreate_network_manager_time * self._recreate_network_manager_count:
  341. self._recreate_network_manager_count += 1
  342. counter = 0 # Counter to prevent possible indefinite while loop.
  343. # It can happen that we had a very long timeout (multiple times the recreate time).
  344. # In that case we should jump through the point that the next update won't be right away.
  345. while time_since_last_response - self._recreate_network_manager_time * self._recreate_network_manager_count > self._recreate_network_manager_time and counter < 10:
  346. counter += 1
  347. self._recreate_network_manager_count += 1
  348. Logger.log("d", "Timeout lasted over %.0f seconds (%.1fs), re-checking connection.", self._recreate_network_manager_time, time_since_last_response)
  349. self._createNetworkManager()
  350. return
  351. # Check if we have an connection in the first place.
  352. if not self._manager.networkAccessible():
  353. if not self._connection_state_before_timeout:
  354. Logger.log("d", "The network connection seems to be disabled. Going into timeout mode")
  355. self._connection_state_before_timeout = self._connection_state
  356. self.setConnectionState(ConnectionState.error)
  357. self._connection_message = Message(i18n_catalog.i18nc("@info:status",
  358. "The connection with the network was lost."))
  359. self._connection_message.show()
  360. if self._progress_message:
  361. self._progress_message.hide()
  362. # Check if we were uploading something. Abort if this is the case.
  363. # Some operating systems handle this themselves, others give weird issues.
  364. try:
  365. if self._post_reply:
  366. Logger.log("d", "Stopping post upload because the connection was lost.")
  367. try:
  368. self._post_reply.uploadProgress.disconnect(self._onUploadProgress)
  369. except TypeError:
  370. pass # The disconnection can fail on mac in some cases. Ignore that.
  371. self._post_reply.abort()
  372. self._post_reply = None
  373. except RuntimeError:
  374. self._post_reply = None # It can happen that the wrapped c++ object is already deleted.
  375. return
  376. else:
  377. if not self._connection_state_before_timeout:
  378. self._recreate_network_manager_count = 1
  379. # Check that we aren't in a timeout state
  380. if self._last_response_time and self._last_request_time and not self._connection_state_before_timeout:
  381. if time_since_last_response > self._response_timeout_time and time_since_last_request <= self._response_timeout_time:
  382. # Go into timeout state.
  383. Logger.log("d", "We did not receive a response for %0.1f seconds, so it seems the printer is no longer accessible.", time_since_last_response)
  384. self._connection_state_before_timeout = self._connection_state
  385. self._connection_message = Message(i18n_catalog.i18nc("@info:status", "The connection with the printer was lost. Check your printer to see if it is connected."))
  386. self._connection_message.show()
  387. if self._progress_message:
  388. self._progress_message.hide()
  389. # Check if we were uploading something. Abort if this is the case.
  390. # Some operating systems handle this themselves, others give weird issues.
  391. try:
  392. if self._post_reply:
  393. Logger.log("d", "Stopping post upload because the connection was lost.")
  394. try:
  395. self._post_reply.uploadProgress.disconnect(self._onUploadProgress)
  396. except TypeError:
  397. pass # The disconnection can fail on mac in some cases. Ignore that.
  398. self._post_reply.abort()
  399. self._post_reply = None
  400. except RuntimeError:
  401. self._post_reply = None # It can happen that the wrapped c++ object is already deleted.
  402. self.setConnectionState(ConnectionState.error)
  403. return
  404. if self._authentication_state == AuthState.NotAuthenticated:
  405. self._verifyAuthentication() # We don't know if we are authenticated; check if we have correct auth.
  406. elif self._authentication_state == AuthState.AuthenticationRequested:
  407. self._checkAuthentication() # We requested authentication at some point. Check if we got permission.
  408. ## Request 'general' printer data
  409. url = QUrl("http://" + self._address + self._api_prefix + "printer")
  410. printer_request = QNetworkRequest(url)
  411. self._manager.get(printer_request)
  412. ## Request print_job data
  413. url = QUrl("http://" + self._address + self._api_prefix + "print_job")
  414. print_job_request = QNetworkRequest(url)
  415. self._manager.get(print_job_request)
  416. self._last_request_time = time()
  417. def _createNetworkManager(self):
  418. if self._manager:
  419. self._manager.finished.disconnect(self._onFinished)
  420. self._manager.networkAccessibleChanged.disconnect(self._onNetworkAccesibleChanged)
  421. self._manager.authenticationRequired.disconnect(self._onAuthenticationRequired)
  422. self._manager = QNetworkAccessManager()
  423. self._manager.finished.connect(self._onFinished)
  424. self._manager.authenticationRequired.connect(self._onAuthenticationRequired)
  425. self._manager.networkAccessibleChanged.connect(self._onNetworkAccesibleChanged) # for debug purposes
  426. ## Convenience function that gets information from the received json data and converts it to the right internal
  427. # values / variables
  428. def _spliceJSONData(self):
  429. # Check for hotend temperatures
  430. for index in range(0, self._num_extruders):
  431. temperature = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["temperature"]["current"]
  432. self._setHotendTemperature(index, temperature)
  433. try:
  434. material_id = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"]
  435. except KeyError:
  436. material_id = ""
  437. self._setMaterialId(index, material_id)
  438. try:
  439. hotend_id = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"]
  440. except KeyError:
  441. hotend_id = ""
  442. self._setHotendId(index, hotend_id)
  443. bed_temperature = self._json_printer_state["bed"]["temperature"]["current"]
  444. self._setBedTemperature(bed_temperature)
  445. target_bed_temperature = self._json_printer_state["bed"]["temperature"]["target"]
  446. self._setTargetBedTemperature(target_bed_temperature)
  447. head_x = self._json_printer_state["heads"][0]["position"]["x"]
  448. head_y = self._json_printer_state["heads"][0]["position"]["y"]
  449. head_z = self._json_printer_state["heads"][0]["position"]["z"]
  450. self._updateHeadPosition(head_x, head_y, head_z)
  451. self._updatePrinterState(self._json_printer_state["status"])
  452. if self._processing_preheat_requests:
  453. try:
  454. is_preheating = self._json_printer_state["bed"]["pre_heat"]["active"]
  455. except KeyError: #Old firmware doesn't support that.
  456. pass #Don't update the pre-heat remaining time.
  457. else:
  458. if is_preheating:
  459. try:
  460. remaining_preheat_time = self._json_printer_state["bed"]["pre_heat"]["remaining"]
  461. except KeyError: #Error in firmware. If "active" is supported, "remaining" should also be supported.
  462. pass #Anyway, don't update.
  463. else:
  464. #Only update if time estimate is significantly off (>5000ms).
  465. #Otherwise we get issues with latency causing the timer to count inconsistently.
  466. if abs(self._preheat_bed_timer.remainingTime() - remaining_preheat_time * 1000) > 5000:
  467. self._preheat_bed_timer.setInterval(remaining_preheat_time * 1000)
  468. self._preheat_bed_timer.start()
  469. self.preheatBedRemainingTimeChanged.emit()
  470. else: #Not pre-heating. Must've cancelled.
  471. if self._preheat_bed_timer.isActive():
  472. self._preheat_bed_timer.setInterval(0)
  473. self._preheat_bed_timer.stop()
  474. self.preheatBedRemainingTimeChanged.emit()
  475. def close(self):
  476. Logger.log("d", "Closing connection of printer %s with ip %s", self._key, self._address)
  477. self._updateJobState("")
  478. self.setConnectionState(ConnectionState.closed)
  479. if self._progress_message:
  480. self._progress_message.hide()
  481. # Reset authentication state
  482. self._authentication_requested_message.hide()
  483. self._authentication_state = AuthState.NotAuthenticated
  484. self._authentication_counter = 0
  485. self._authentication_timer.stop()
  486. self._authentication_requested_message.hide()
  487. self._authentication_failed_message.hide()
  488. self._authentication_succeeded_message.hide()
  489. # Reset stored material & hotend data.
  490. self._material_ids = [""] * self._num_extruders
  491. self._hotend_ids = [""] * self._num_extruders
  492. if self._error_message:
  493. self._error_message.hide()
  494. # Reset timeout state
  495. self._connection_state_before_timeout = None
  496. self._last_response_time = time()
  497. self._last_request_time = None
  498. # Stop update timers
  499. self._update_timer.stop()
  500. self.stopCamera()
  501. ## Request the current scene to be sent to a network-connected printer.
  502. #
  503. # \param nodes A collection of scene nodes to send. This is ignored.
  504. # \param file_name \type{string} A suggestion for a file name to write.
  505. # This is ignored.
  506. # \param filter_by_machine Whether to filter MIME types by machine. This
  507. # is ignored.
  508. # \param kwargs Keyword arguments.
  509. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  510. if self._printer_state != "idle":
  511. self._error_message = Message(
  512. i18n_catalog.i18nc("@info:status", "Unable to start a new print job, printer is busy. Current printer status is %s.") % self._printer_state)
  513. self._error_message.show()
  514. return
  515. elif self._authentication_state != AuthState.Authenticated:
  516. self._not_authenticated_message.show()
  517. Logger.log("d", "Attempting to perform an action without authentication. Auth state is %s", self._authentication_state)
  518. return
  519. Application.getInstance().showPrintMonitor.emit(True)
  520. self._print_finished = True
  521. self.writeStarted.emit(self)
  522. self._gcode = getattr(Application.getInstance().getController().getScene(), "gcode_list")
  523. print_information = Application.getInstance().getPrintInformation()
  524. # Check if print cores / materials are loaded at all. Any failure in these results in an Error.
  525. for index in range(0, self._num_extruders):
  526. if print_information.materialLengths[index] != 0:
  527. if self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"] == "":
  528. Logger.log("e", "No cartridge loaded in slot %s, unable to start print", index + 1)
  529. self._error_message = Message(
  530. i18n_catalog.i18nc("@info:status", "Unable to start a new print job. No PrinterCore loaded in slot {0}".format(index + 1)))
  531. self._error_message.show()
  532. return
  533. if self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"] == "":
  534. Logger.log("e", "No material loaded in slot %s, unable to start print", index + 1)
  535. self._error_message = Message(
  536. i18n_catalog.i18nc("@info:status",
  537. "Unable to start a new print job. No material loaded in slot {0}".format(index + 1)))
  538. self._error_message.show()
  539. return
  540. warnings = [] # There might be multiple things wrong. Keep a list of all the stuff we need to warn about.
  541. for index in range(0, self._num_extruders):
  542. # Check if there is enough material. Any failure in these results in a warning.
  543. material_length = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["length_remaining"]
  544. if material_length != -1 and print_information.materialLengths[index] > material_length:
  545. Logger.log("w", "Printer reports that there is not enough material left for extruder %s. We need %s and the printer has %s", index + 1, print_information.materialLengths[index], material_length)
  546. warnings.append(i18n_catalog.i18nc("@label", "Not enough material for spool {0}.").format(index+1))
  547. # Check if the right cartridges are loaded. Any failure in these results in a warning.
  548. extruder_manager = cura.Settings.ExtruderManager.ExtruderManager.getInstance()
  549. if print_information.materialLengths[index] != 0:
  550. variant = extruder_manager.getExtruderStack(index).findContainer({"type": "variant"})
  551. core_name = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"]
  552. if variant:
  553. if variant.getName() != core_name:
  554. Logger.log("w", "Extruder %s has a different Cartridge (%s) as Cura (%s)", index + 1, core_name, variant.getName())
  555. warnings.append(i18n_catalog.i18nc("@label", "Different print core (Cura: {0}, Printer: {1}) selected for extruder {2}".format(variant.getName(), core_name, index + 1)))
  556. material = extruder_manager.getExtruderStack(index).findContainer({"type": "material"})
  557. if material:
  558. remote_material_guid = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"]
  559. if material.getMetaDataEntry("GUID") != remote_material_guid:
  560. Logger.log("w", "Extruder %s has a different material (%s) as Cura (%s)", index + 1,
  561. remote_material_guid,
  562. material.getMetaDataEntry("GUID"))
  563. remote_materials = UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(type = "material", GUID = remote_material_guid, read_only = True)
  564. remote_material_name = "Unknown"
  565. if remote_materials:
  566. remote_material_name = remote_materials[0].getName()
  567. warnings.append(i18n_catalog.i18nc("@label", "Different material (Cura: {0}, Printer: {1}) selected for extruder {2}").format(material.getName(), remote_material_name, index + 1))
  568. try:
  569. is_offset_calibrated = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["offset"]["state"] == "valid"
  570. except KeyError: # Older versions of the API don't expose the offset property, so we must asume that all is well.
  571. is_offset_calibrated = True
  572. if not is_offset_calibrated:
  573. warnings.append(i18n_catalog.i18nc("@label", "Print core {0} is not properly calibrated. XY calibration needs to be performed on the printer.").format(index + 1))
  574. if warnings:
  575. text = i18n_catalog.i18nc("@label", "Are you sure you wish to print with the selected configuration?")
  576. informative_text = i18n_catalog.i18nc("@label", "There is a mismatch between the configuration or calibration of the printer and Cura. "
  577. "For the best result, always slice for the PrintCores and materials that are inserted in your printer.")
  578. detailed_text = ""
  579. for warning in warnings:
  580. detailed_text += warning + "\n"
  581. Application.getInstance().messageBox(i18n_catalog.i18nc("@window:title", "Mismatched configuration"),
  582. text,
  583. informative_text,
  584. detailed_text,
  585. buttons=QMessageBox.Yes + QMessageBox.No,
  586. icon=QMessageBox.Question,
  587. callback=self._configurationMismatchMessageCallback
  588. )
  589. return
  590. self.startPrint()
  591. def _configurationMismatchMessageCallback(self, button):
  592. def delayedCallback():
  593. if button == QMessageBox.Yes:
  594. self.startPrint()
  595. else:
  596. Application.getInstance().showPrintMonitor.emit(False)
  597. # For some unknown reason Cura on OSX will hang if we do the call back code
  598. # immediately without first returning and leaving QML's event system.
  599. QTimer.singleShot(100, delayedCallback)
  600. def isConnected(self):
  601. return self._connection_state != ConnectionState.closed and self._connection_state != ConnectionState.error
  602. ## Start requesting data from printer
  603. def connect(self):
  604. self.close() # Ensure that previous connection (if any) is killed.
  605. self._createNetworkManager()
  606. self.setConnectionState(ConnectionState.connecting)
  607. self._update() # Manually trigger the first update, as we don't want to wait a few secs before it starts.
  608. if not self._use_stream:
  609. self._updateCamera()
  610. Logger.log("d", "Connection with printer %s with ip %s started", self._key, self._address)
  611. ## Check if this machine was authenticated before.
  612. self._authentication_id = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("network_authentication_id", None)
  613. self._authentication_key = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("network_authentication_key", None)
  614. if self._authentication_id is None and self._authentication_key is None:
  615. Logger.log("d", "No authentication found in metadata.")
  616. else:
  617. Logger.log("d", "Loaded authentication id %s from the metadata entry", self._authentication_id)
  618. self._update_timer.start()
  619. ## Stop requesting data from printer
  620. def disconnect(self):
  621. Logger.log("d", "Connection with printer %s with ip %s stopped", self._key, self._address)
  622. self.close()
  623. newImage = pyqtSignal()
  624. @pyqtProperty(QUrl, notify = newImage)
  625. def cameraImage(self):
  626. self._camera_image_id += 1
  627. # There is an image provider that is called "camera". In order to ensure that the image qml object, that
  628. # requires a QUrl to function, updates correctly we add an increasing number. This causes to see the QUrl
  629. # as new (instead of relying on cached version and thus forces an update.
  630. temp = "image://camera/" + str(self._camera_image_id)
  631. return QUrl(temp, QUrl.TolerantMode)
  632. def getCameraImage(self):
  633. return self._camera_image
  634. def _setJobState(self, job_state):
  635. self._last_command = job_state
  636. url = QUrl("http://" + self._address + self._api_prefix + "print_job/state")
  637. put_request = QNetworkRequest(url)
  638. put_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
  639. data = "{\"target\": \"%s\"}" % job_state
  640. self._manager.put(put_request, data.encode())
  641. ## Convenience function to get the username from the OS.
  642. # The code was copied from the getpass module, as we try to use as little dependencies as possible.
  643. def _getUserName(self):
  644. for name in ("LOGNAME", "USER", "LNAME", "USERNAME"):
  645. user = os.environ.get(name)
  646. if user:
  647. return user
  648. return "Unknown User" # Couldn't find out username.
  649. def _progressMessageActionTrigger(self, message_id = None, action_id = None):
  650. if action_id == "Abort":
  651. Logger.log("d", "User aborted sending print to remote.")
  652. self._progress_message.hide()
  653. self._compressing_print = False
  654. if self._post_reply:
  655. self._post_reply.abort()
  656. self._post_reply = None
  657. Application.getInstance().showPrintMonitor.emit(False)
  658. ## Attempt to start a new print.
  659. # This function can fail to actually start a print due to not being authenticated or another print already
  660. # being in progress.
  661. def startPrint(self):
  662. try:
  663. self._send_gcode_start = time()
  664. self._progress_message = Message(i18n_catalog.i18nc("@info:status", "Sending data to printer"), 0, False, -1)
  665. self._progress_message.addAction("Abort", i18n_catalog.i18nc("@action:button", "Cancel"), None, "")
  666. self._progress_message.actionTriggered.connect(self._progressMessageActionTrigger)
  667. self._progress_message.show()
  668. Logger.log("d", "Started sending g-code to remote printer.")
  669. self._compressing_print = True
  670. ## Mash the data into single string
  671. byte_array_file_data = b""
  672. for line in self._gcode:
  673. if not self._compressing_print:
  674. self._progress_message.hide()
  675. return # Stop trying to zip, abort was called.
  676. if self._use_gzip:
  677. byte_array_file_data += gzip.compress(line.encode("utf-8"))
  678. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  679. # Pretend that this is a response, as zipping might take a bit of time.
  680. self._last_response_time = time()
  681. else:
  682. byte_array_file_data += line.encode("utf-8")
  683. if self._use_gzip:
  684. file_name = "%s.gcode.gz" % Application.getInstance().getPrintInformation().jobName
  685. else:
  686. file_name = "%s.gcode" % Application.getInstance().getPrintInformation().jobName
  687. self._compressing_print = False
  688. ## Create multi_part request
  689. self._post_multi_part = QHttpMultiPart(QHttpMultiPart.FormDataType)
  690. ## Create part (to be placed inside multipart)
  691. self._post_part = QHttpPart()
  692. self._post_part.setHeader(QNetworkRequest.ContentDispositionHeader,
  693. "form-data; name=\"file\"; filename=\"%s\"" % file_name)
  694. self._post_part.setBody(byte_array_file_data)
  695. self._post_multi_part.append(self._post_part)
  696. url = QUrl("http://" + self._address + self._api_prefix + "print_job")
  697. ## Create the QT request
  698. self._post_request = QNetworkRequest(url)
  699. ## Post request + data
  700. self._post_reply = self._manager.post(self._post_request, self._post_multi_part)
  701. self._post_reply.uploadProgress.connect(self._onUploadProgress)
  702. except IOError:
  703. self._progress_message.hide()
  704. self._error_message = Message(i18n_catalog.i18nc("@info:status", "Unable to send data to printer. Is another job still active?"))
  705. self._error_message.show()
  706. except Exception as e:
  707. self._progress_message.hide()
  708. Logger.log("e", "An exception occurred in network connection: %s" % str(e))
  709. ## Verify if we are authenticated to make requests.
  710. def _verifyAuthentication(self):
  711. url = QUrl("http://" + self._address + self._api_prefix + "auth/verify")
  712. request = QNetworkRequest(url)
  713. self._manager.get(request)
  714. ## Check if the authentication request was allowed by the printer.
  715. def _checkAuthentication(self):
  716. Logger.log("d", "Checking if authentication is correct for id %s", self._authentication_id)
  717. self._manager.get(QNetworkRequest(QUrl("http://" + self._address + self._api_prefix + "auth/check/" + str(self._authentication_id))))
  718. ## Request a authentication key from the printer so we can be authenticated
  719. def _requestAuthentication(self):
  720. url = QUrl("http://" + self._address + self._api_prefix + "auth/request")
  721. request = QNetworkRequest(url)
  722. request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
  723. self.setAuthenticationState(AuthState.AuthenticationRequested)
  724. self._manager.post(request, json.dumps({"application": "Cura-" + Application.getInstance().getVersion(), "user": self._getUserName()}).encode())
  725. ## Send all material profiles to the printer.
  726. def sendMaterialProfiles(self):
  727. for container in UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(type = "material"):
  728. try:
  729. xml_data = container.serialize()
  730. if xml_data == "" or xml_data is None:
  731. continue
  732. material_multi_part = QHttpMultiPart(QHttpMultiPart.FormDataType)
  733. material_part = QHttpPart()
  734. file_name = "none.xml"
  735. material_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"file\";filename=\"%s\"" % file_name)
  736. material_part.setBody(xml_data.encode())
  737. material_multi_part.append(material_part)
  738. url = QUrl("http://" + self._address + self._api_prefix + "materials")
  739. material_post_request = QNetworkRequest(url)
  740. reply = self._manager.post(material_post_request, material_multi_part)
  741. # Keep reference to material_part, material_multi_part and reply so the garbage collector won't touch them.
  742. self._material_post_objects[id(reply)] = (material_part, material_multi_part, reply)
  743. except NotImplementedError:
  744. # If the material container is not the most "generic" one it can't be serialized an will raise a
  745. # NotImplementedError. We can simply ignore these.
  746. pass
  747. ## Handler for all requests that have finished.
  748. def _onFinished(self, reply):
  749. if reply.error() == QNetworkReply.TimeoutError:
  750. Logger.log("w", "Received a timeout on a request to the printer")
  751. self._connection_state_before_timeout = self._connection_state
  752. # Check if we were uploading something. Abort if this is the case.
  753. # Some operating systems handle this themselves, others give weird issues.
  754. if self._post_reply:
  755. self._post_reply.abort()
  756. self._post_reply.uploadProgress.disconnect(self._onUploadProgress)
  757. Logger.log("d", "Uploading of print failed after %s", time() - self._send_gcode_start)
  758. self._post_reply = None
  759. self._progress_message.hide()
  760. self.setConnectionState(ConnectionState.error)
  761. return
  762. if self._connection_state_before_timeout and reply.error() == QNetworkReply.NoError: # There was a timeout, but we got a correct answer again.
  763. Logger.log("d", "We got a response (%s) from the server after %0.1f of silence. Going back to previous state %s", reply.url().toString(), time() - self._last_response_time, self._connection_state_before_timeout)
  764. # Camera was active before timeout. Start it again
  765. if self._camera_active:
  766. self._startCamera()
  767. self.setConnectionState(self._connection_state_before_timeout)
  768. self._connection_state_before_timeout = None
  769. if reply.error() == QNetworkReply.NoError:
  770. self._last_response_time = time()
  771. status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
  772. if not status_code:
  773. if self._connection_state != ConnectionState.error:
  774. Logger.log("d", "A reply from %s did not have status code.", reply.url().toString())
  775. # Received no or empty reply
  776. return
  777. reply_url = reply.url().toString()
  778. if reply.operation() == QNetworkAccessManager.GetOperation:
  779. if "printer" in reply_url: # Status update from printer.
  780. if status_code == 200:
  781. if self._connection_state == ConnectionState.connecting:
  782. self.setConnectionState(ConnectionState.connected)
  783. self._json_printer_state = json.loads(bytes(reply.readAll()).decode("utf-8"))
  784. self._spliceJSONData()
  785. # Hide connection error message if the connection was restored
  786. if self._connection_message:
  787. self._connection_message.hide()
  788. self._connection_message = None
  789. else:
  790. Logger.log("w", "We got an unexpected status (%s) while requesting printer state", status_code)
  791. pass # TODO: Handle errors
  792. elif "print_job" in reply_url: # Status update from print_job:
  793. if status_code == 200:
  794. json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
  795. progress = json_data["progress"]
  796. ## If progress is 0 add a bit so another print can't be sent.
  797. if progress == 0:
  798. progress += 0.001
  799. elif progress == 1:
  800. self._print_finished = True
  801. else:
  802. self._print_finished = False
  803. self.setProgress(progress * 100)
  804. state = json_data["state"]
  805. # There is a short period after aborting or finishing a print where the printer
  806. # reports a "none" state (but the printer is not ready to receive a print)
  807. # If this happens before the print has reached progress == 1, the print has
  808. # been aborted.
  809. if state == "none" or state == "":
  810. if self._last_command == "abort":
  811. self.setErrorText(i18n_catalog.i18nc("@label:MonitorStatus", "Aborting print..."))
  812. state = "error"
  813. else:
  814. state = "printing"
  815. if state == "wait_cleanup" and self._last_command == "abort":
  816. # Keep showing the "aborted" error state until after the buildplate has been cleaned
  817. self.setErrorText(i18n_catalog.i18nc("@label:MonitorStatus", "Print aborted. Please check the printer"))
  818. state = "error"
  819. # NB/TODO: the following two states are intentionally added for future proofing the i18n strings
  820. # but are currently non-functional
  821. if state == "!pausing":
  822. self.setErrorText(i18n_catalog.i18nc("@label:MonitorStatus", "Pausing print..."))
  823. if state == "!resuming":
  824. self.setErrorText(i18n_catalog.i18nc("@label:MonitorStatus", "Resuming print..."))
  825. self._updateJobState(state)
  826. self.setTimeElapsed(json_data["time_elapsed"])
  827. self.setTimeTotal(json_data["time_total"])
  828. self.setJobName(json_data["name"])
  829. elif status_code == 404:
  830. self.setProgress(0) # No print job found, so there can't be progress or other data.
  831. self._updateJobState("")
  832. self.setErrorText("")
  833. self.setTimeElapsed(0)
  834. self.setTimeTotal(0)
  835. self.setJobName("")
  836. else:
  837. Logger.log("w", "We got an unexpected status (%s) while requesting print job state", status_code)
  838. elif "snapshot" in reply_url: # Status update from image:
  839. if status_code == 200:
  840. self._camera_image.loadFromData(reply.readAll())
  841. self.newImage.emit()
  842. elif "auth/verify" in reply_url: # Answer when requesting authentication
  843. if status_code == 401:
  844. if self._authentication_state != AuthState.AuthenticationRequested:
  845. # Only request a new authentication when we have not already done so.
  846. Logger.log("i", "Not authenticated (Current auth state is %s). Attempting to request authentication", self._authentication_state )
  847. self._requestAuthentication()
  848. elif status_code == 403:
  849. # If we already had an auth (eg; didn't request one), we only need a single 403 to see it as denied.
  850. if self._authentication_state != AuthState.AuthenticationRequested:
  851. Logger.log("d", "While trying to verify the authentication state, we got a forbidden response. Our own auth state was %s", self._authentication_state)
  852. self.setAuthenticationState(AuthState.AuthenticationDenied)
  853. elif status_code == 200:
  854. self.setAuthenticationState(AuthState.Authenticated)
  855. global_container_stack = Application.getInstance().getGlobalContainerStack()
  856. ## Save authentication details.
  857. if global_container_stack:
  858. if "network_authentication_key" in global_container_stack.getMetaData():
  859. global_container_stack.setMetaDataEntry("network_authentication_key", self._authentication_key)
  860. else:
  861. global_container_stack.addMetaDataEntry("network_authentication_key", self._authentication_key)
  862. if "network_authentication_id" in global_container_stack.getMetaData():
  863. global_container_stack.setMetaDataEntry("network_authentication_id", self._authentication_id)
  864. else:
  865. global_container_stack.addMetaDataEntry("network_authentication_id", self._authentication_id)
  866. Application.getInstance().saveStack(global_container_stack) # Force save so we are sure the data is not lost.
  867. Logger.log("i", "Authentication succeeded for id %s", self._authentication_id)
  868. else: # Got a response that we didn't expect, so something went wrong.
  869. Logger.log("e", "While trying to authenticate, we got an unexpected response: %s", reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
  870. self.setAuthenticationState(AuthState.NotAuthenticated)
  871. elif "auth/check" in reply_url: # Check if we are authenticated (user can refuse this!)
  872. data = json.loads(bytes(reply.readAll()).decode("utf-8"))
  873. if data.get("message", "") == "authorized":
  874. Logger.log("i", "Authentication was approved")
  875. self._verifyAuthentication() # Ensure that the verification is really used and correct.
  876. elif data.get("message", "") == "unauthorized":
  877. Logger.log("i", "Authentication was denied.")
  878. self.setAuthenticationState(AuthState.AuthenticationDenied)
  879. else:
  880. pass
  881. elif reply.operation() == QNetworkAccessManager.PostOperation:
  882. if "/auth/request" in reply_url:
  883. # We got a response to requesting authentication.
  884. data = json.loads(bytes(reply.readAll()).decode("utf-8"))
  885. global_container_stack = Application.getInstance().getGlobalContainerStack()
  886. if global_container_stack: # Remove any old data.
  887. Logger.log("d", "Removing old network authentication data as a new one was requested.")
  888. global_container_stack.removeMetaDataEntry("network_authentication_key")
  889. global_container_stack.removeMetaDataEntry("network_authentication_id")
  890. Application.getInstance().saveStack(global_container_stack) # Force saving so we don't keep wrong auth data.
  891. self._authentication_key = data["key"]
  892. self._authentication_id = data["id"]
  893. Logger.log("i", "Got a new authentication ID. Waiting for authorization: %s", self._authentication_id )
  894. # Check if the authentication is accepted.
  895. self._checkAuthentication()
  896. elif "materials" in reply_url:
  897. # Remove cached post request items.
  898. del self._material_post_objects[id(reply)]
  899. elif "print_job" in reply_url:
  900. reply.uploadProgress.disconnect(self._onUploadProgress)
  901. Logger.log("d", "Uploading of print succeeded after %s", time() - self._send_gcode_start)
  902. # Only reset the _post_reply if it was the same one.
  903. if reply == self._post_reply:
  904. self._post_reply = None
  905. self._progress_message.hide()
  906. elif reply.operation() == QNetworkAccessManager.PutOperation:
  907. if "printer/bed/pre_heat" in reply_url: #Pre-heat command has completed. Re-enable syncing pre-heating.
  908. self._processing_preheat_requests = True
  909. if status_code in [200, 201, 202, 204]:
  910. pass # Request was successful!
  911. else:
  912. Logger.log("d", "Something went wrong when trying to update data of API (%s). Message: %s Statuscode: %s", reply_url, reply.readAll(), status_code)
  913. else:
  914. Logger.log("d", "NetworkPrinterOutputDevice got an unhandled operation %s", reply.operation())
  915. def _onStreamDownloadProgress(self, bytes_received, bytes_total):
  916. # An MJPG stream is (for our purpose) a stream of concatenated JPG images.
  917. # JPG images start with the marker 0xFFD8, and end with 0xFFD9
  918. if self._image_reply is None:
  919. return
  920. self._stream_buffer += self._image_reply.readAll()
  921. if self._stream_buffer_start_index == -1:
  922. self._stream_buffer_start_index = self._stream_buffer.indexOf(b'\xff\xd8')
  923. stream_buffer_end_index = self._stream_buffer.lastIndexOf(b'\xff\xd9')
  924. # If this happens to be more than a single frame, then so be it; the JPG decoder will
  925. # ignore the extra data. We do it like this in order not to get a buildup of frames
  926. if self._stream_buffer_start_index != -1 and stream_buffer_end_index != -1:
  927. jpg_data = self._stream_buffer[self._stream_buffer_start_index:stream_buffer_end_index + 2]
  928. self._stream_buffer = self._stream_buffer[stream_buffer_end_index + 2:]
  929. self._stream_buffer_start_index = -1
  930. self._camera_image.loadFromData(jpg_data)
  931. self.newImage.emit()
  932. def _onUploadProgress(self, bytes_sent, bytes_total):
  933. if bytes_total > 0:
  934. new_progress = bytes_sent / bytes_total * 100
  935. # Treat upload progress as response. Uploading can take more than 10 seconds, so if we don't, we can get
  936. # timeout responses if this happens.
  937. self._last_response_time = time()
  938. if new_progress > self._progress_message.getProgress():
  939. self._progress_message.show() # Ensure that the message is visible.
  940. self._progress_message.setProgress(bytes_sent / bytes_total * 100)
  941. else:
  942. self._progress_message.setProgress(0)
  943. self._progress_message.hide()
  944. ## Let the user decide if the hotends and/or material should be synced with the printer
  945. def materialHotendChangedMessage(self, callback):
  946. Application.getInstance().messageBox(i18n_catalog.i18nc("@window:title", "Sync with your printer"),
  947. i18n_catalog.i18nc("@label",
  948. "Would you like to use your current printer configuration in Cura?"),
  949. i18n_catalog.i18nc("@label",
  950. "The print cores and/or materials on your printer differ from those within your current project. For the best result, always slice for the print cores and materials that are inserted in your printer."),
  951. buttons=QMessageBox.Yes + QMessageBox.No,
  952. icon=QMessageBox.Question,
  953. callback=callback
  954. )