NetworkPrinterOutputDevice.py 62 KB

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