NetworkPrinterOutputDevice.py 57 KB

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