NetworkPrinterOutputDevice.py 56 KB

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