NetworkPrinterOutputDevice.py 63 KB

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