ClusterUM3OutputDevice.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import Any, cast, Set, Tuple, Union
  4. from UM.FileHandler.FileHandler import FileHandler
  5. from UM.FileHandler.FileWriter import FileWriter #To choose based on the output file mode (text vs. binary).
  6. from UM.FileHandler.WriteFileJob import WriteFileJob #To call the file writer asynchronously.
  7. from UM.Logger import Logger
  8. from UM.Settings.ContainerRegistry import ContainerRegistry
  9. from UM.i18n import i18nCatalog
  10. from UM.Message import Message
  11. from UM.Qt.Duration import Duration, DurationFormat
  12. from UM.OutputDevice import OutputDeviceError #To show that something went wrong when writing.
  13. from UM.Scene.SceneNode import SceneNode #For typing.
  14. from UM.Version import Version #To check against firmware versions for support.
  15. from cura.CuraApplication import CuraApplication
  16. from cura.PrinterOutput.NetworkedPrinterOutputDevice import NetworkedPrinterOutputDevice, AuthState
  17. from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
  18. from cura.PrinterOutput.PrintJobOutputModel import PrintJobOutputModel
  19. from cura.PrinterOutput.MaterialOutputModel import MaterialOutputModel
  20. from cura.PrinterOutput.NetworkCamera import NetworkCamera
  21. from .ClusterUM3PrinterOutputController import ClusterUM3PrinterOutputController
  22. from .SendMaterialJob import SendMaterialJob
  23. from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
  24. from PyQt5.QtGui import QDesktopServices
  25. from PyQt5.QtCore import pyqtSlot, QUrl, pyqtSignal, pyqtProperty, QObject
  26. from time import time
  27. from datetime import datetime
  28. from typing import Optional, Dict, List, Set
  29. import io #To create the correct buffers for sending data to the printer.
  30. import json
  31. import os
  32. i18n_catalog = i18nCatalog("cura")
  33. class ClusterUM3OutputDevice(NetworkedPrinterOutputDevice):
  34. printJobsChanged = pyqtSignal()
  35. activePrinterChanged = pyqtSignal()
  36. # This is a bit of a hack, as the notify can only use signals that are defined by the class that they are in.
  37. # Inheritance doesn't seem to work. Tying them together does work, but i'm open for better suggestions.
  38. clusterPrintersChanged = pyqtSignal()
  39. def __init__(self, device_id, address, properties, parent = None) -> None:
  40. super().__init__(device_id = device_id, address = address, properties=properties, parent = parent)
  41. self._api_prefix = "/cluster-api/v1/"
  42. self._number_of_extruders = 2
  43. self._dummy_lambdas = ("", {}, io.BytesIO()) #type: Tuple[str, Dict, Union[io.StringIO, io.BytesIO]]
  44. self._print_jobs = [] # type: List[PrintJobOutputModel]
  45. self._monitor_view_qml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ClusterMonitorItem.qml")
  46. self._control_view_qml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ClusterControlItem.qml")
  47. # See comments about this hack with the clusterPrintersChanged signal
  48. self.printersChanged.connect(self.clusterPrintersChanged)
  49. self._accepts_commands = True #type: bool
  50. # Cluster does not have authentication, so default to authenticated
  51. self._authentication_state = AuthState.Authenticated
  52. self._error_message = None #type: Optional[Message]
  53. self._write_job_progress_message = None #type: Optional[Message]
  54. self._progress_message = None #type: Optional[Message]
  55. self._active_printer = None # type: Optional[PrinterOutputModel]
  56. self._printer_selection_dialog = None #type: QObject
  57. self.setPriority(3) # Make sure the output device gets selected above local file output
  58. self.setName(self._id)
  59. self.setShortDescription(i18n_catalog.i18nc("@action:button Preceded by 'Ready to'.", "Print over network"))
  60. self.setDescription(i18n_catalog.i18nc("@properties:tooltip", "Print over network"))
  61. self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network"))
  62. self._printer_uuid_to_unique_name_mapping = {} # type: Dict[str, str]
  63. self._finished_jobs = [] # type: List[PrintJobOutputModel]
  64. self._cluster_size = int(properties.get(b"cluster_size", 0))
  65. self._latest_reply_handler = None #type: Optional[QNetworkReply]
  66. def requestWrite(self, nodes: List[SceneNode], file_name: Optional[str] = None, limit_mimetypes: bool = False, file_handler: Optional[FileHandler] = None, **kwargs: str) -> None:
  67. self.writeStarted.emit(self)
  68. self.sendMaterialProfiles()
  69. #Formats supported by this application (file types that we can actually write).
  70. if file_handler:
  71. file_formats = file_handler.getSupportedFileTypesWrite()
  72. else:
  73. file_formats = CuraApplication.getInstance().getMeshFileHandler().getSupportedFileTypesWrite()
  74. #Create a list from the supported file formats string.
  75. machine_file_formats = CuraApplication.getInstance().getGlobalContainerStack().getMetaDataEntry("file_formats").split(";")
  76. machine_file_formats = [file_type.strip() for file_type in machine_file_formats]
  77. #Exception for UM3 firmware version >=4.4: UFP is now supported and should be the preferred file format.
  78. if "application/x-ufp" not in machine_file_formats and self.printerType == "ultimaker3" and Version(self.firmwareVersion) >= Version("4.4"):
  79. machine_file_formats = ["application/x-ufp"] + machine_file_formats
  80. # Take the intersection between file_formats and machine_file_formats.
  81. format_by_mimetype = {format["mime_type"]: format for format in file_formats}
  82. file_formats = [format_by_mimetype[mimetype] for mimetype in machine_file_formats] #Keep them ordered according to the preference in machine_file_formats.
  83. if len(file_formats) == 0:
  84. Logger.log("e", "There are no file formats available to write with!")
  85. raise OutputDeviceError.WriteRequestFailedError(i18n_catalog.i18nc("@info:status", "There are no file formats available to write with!"))
  86. preferred_format = file_formats[0]
  87. #Just take the first file format available.
  88. if file_handler is not None:
  89. writer = file_handler.getWriterByMimeType(cast(str, preferred_format["mime_type"]))
  90. else:
  91. writer = CuraApplication.getInstance().getMeshFileHandler().getWriterByMimeType(cast(str, preferred_format["mime_type"]))
  92. #This function pauses with the yield, waiting on instructions on which printer it needs to print with.
  93. self._sending_job = self._sendPrintJob(writer, preferred_format, nodes)
  94. self._sending_job.send(None) #Start the generator.
  95. if len(self._printers) > 1: #We need to ask the user.
  96. self._spawnPrinterSelectionDialog()
  97. is_job_sent = True
  98. else: #Just immediately continue.
  99. self._sending_job.send("") #No specifically selected printer.
  100. is_job_sent = self._sending_job.send(None)
  101. def _spawnPrinterSelectionDialog(self):
  102. if self._printer_selection_dialog is None:
  103. path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "PrintWindow.qml")
  104. self._printer_selection_dialog = CuraApplication.getInstance().createQmlComponent(path, {"OutputDevice": self})
  105. if self._printer_selection_dialog is not None:
  106. self._printer_selection_dialog.show()
  107. @pyqtProperty(int, constant=True)
  108. def clusterSize(self):
  109. return self._cluster_size
  110. ## Allows the user to choose a printer to print with from the printer
  111. # selection dialogue.
  112. # \param target_printer The name of the printer to target.
  113. @pyqtSlot(str)
  114. def selectPrinter(self, target_printer: str = "") -> None:
  115. self._sending_job.send(target_printer)
  116. @pyqtSlot()
  117. def cancelPrintSelection(self) -> None:
  118. self._sending_gcode = False
  119. ## Greenlet to send a job to the printer over the network.
  120. #
  121. # This greenlet gets called asynchronously in requestWrite. It is a
  122. # greenlet in order to optionally wait for selectPrinter() to select a
  123. # printer.
  124. # The greenlet yields exactly three times: First time None,
  125. # \param writer The file writer to use to create the data.
  126. # \param preferred_format A dictionary containing some information about
  127. # what format to write to. This is necessary to create the correct buffer
  128. # types and file extension and such.
  129. def _sendPrintJob(self, writer: FileWriter, preferred_format: Dict, nodes: List[SceneNode]):
  130. Logger.log("i", "Sending print job to printer.")
  131. if self._sending_gcode:
  132. self._error_message = Message(
  133. i18n_catalog.i18nc("@info:status",
  134. "Sending new jobs (temporarily) blocked, still sending the previous print job."))
  135. self._error_message.show()
  136. yield #Wait on the user to select a target printer.
  137. yield #Wait for the write job to be finished.
  138. yield False #Return whether this was a success or not.
  139. yield #Prevent StopIteration.
  140. self._sending_gcode = True
  141. target_printer = yield #Potentially wait on the user to select a target printer.
  142. # Using buffering greatly reduces the write time for many lines of gcode
  143. stream = io.BytesIO() # type: Union[io.BytesIO, io.StringIO]# Binary mode.
  144. if preferred_format["mode"] == FileWriter.OutputMode.TextMode:
  145. stream = io.StringIO()
  146. job = WriteFileJob(writer, stream, nodes, preferred_format["mode"])
  147. self._write_job_progress_message = Message(i18n_catalog.i18nc("@info:status", "Sending data to printer"), lifetime = 0, dismissable = False, progress = -1,
  148. title = i18n_catalog.i18nc("@info:title", "Sending Data"), use_inactivity_timer = False)
  149. self._write_job_progress_message.show()
  150. self._dummy_lambdas = (target_printer, preferred_format, stream)
  151. job.finished.connect(self._sendPrintJobWaitOnWriteJobFinished)
  152. job.start()
  153. yield True #Return that we had success!
  154. yield #To prevent having to catch the StopIteration exception.
  155. def _sendPrintJobWaitOnWriteJobFinished(self, job: WriteFileJob) -> None:
  156. self._write_job_progress_message.hide()
  157. self._progress_message = Message(i18n_catalog.i18nc("@info:status", "Sending data to printer"), lifetime = 0, dismissable = False, progress = -1,
  158. title = i18n_catalog.i18nc("@info:title", "Sending Data"))
  159. self._progress_message.addAction("Abort", i18n_catalog.i18nc("@action:button", "Cancel"), icon = None, description = "")
  160. self._progress_message.actionTriggered.connect(self._progressMessageActionTriggered)
  161. self._progress_message.show()
  162. parts = []
  163. target_printer, preferred_format, stream = self._dummy_lambdas
  164. # If a specific printer was selected, it should be printed with that machine.
  165. if target_printer:
  166. target_printer = self._printer_uuid_to_unique_name_mapping[target_printer]
  167. parts.append(self._createFormPart("name=require_printer_name", bytes(target_printer, "utf-8"), "text/plain"))
  168. # Add user name to the print_job
  169. parts.append(self._createFormPart("name=owner", bytes(self._getUserName(), "utf-8"), "text/plain"))
  170. file_name = CuraApplication.getInstance().getPrintInformation().jobName + "." + preferred_format["extension"]
  171. output = stream.getvalue() #Either str or bytes depending on the output mode.
  172. if isinstance(stream, io.StringIO):
  173. output = cast(str, output).encode("utf-8")
  174. output = cast(bytes, output)
  175. parts.append(self._createFormPart("name=\"file\"; filename=\"%s\"" % file_name, output))
  176. self._latest_reply_handler = self.postFormWithParts("print_jobs/", parts, on_finished = self._onPostPrintJobFinished, on_progress = self._onUploadPrintJobProgress)
  177. @pyqtProperty(QObject, notify = activePrinterChanged)
  178. def activePrinter(self) -> Optional[PrinterOutputModel]:
  179. return self._active_printer
  180. @pyqtSlot(QObject)
  181. def setActivePrinter(self, printer: Optional[PrinterOutputModel]) -> None:
  182. if self._active_printer != printer:
  183. if self._active_printer and self._active_printer.camera:
  184. self._active_printer.camera.stop()
  185. self._active_printer = printer
  186. self.activePrinterChanged.emit()
  187. def _onPostPrintJobFinished(self, reply: QNetworkReply) -> None:
  188. self._progress_message.hide()
  189. self._compressing_gcode = False
  190. self._sending_gcode = False
  191. def _onUploadPrintJobProgress(self, bytes_sent: int, bytes_total: int) -> None:
  192. if bytes_total > 0:
  193. new_progress = bytes_sent / bytes_total * 100
  194. # Treat upload progress as response. Uploading can take more than 10 seconds, so if we don't, we can get
  195. # timeout responses if this happens.
  196. self._last_response_time = time()
  197. if self._progress_message and new_progress > self._progress_message.getProgress():
  198. self._progress_message.show() # Ensure that the message is visible.
  199. self._progress_message.setProgress(bytes_sent / bytes_total * 100)
  200. # If successfully sent:
  201. if bytes_sent == bytes_total:
  202. # Show a confirmation to the user so they know the job was sucessful and provide the option to switch to the
  203. # monitor tab.
  204. self._success_message = Message(
  205. i18n_catalog.i18nc("@info:status", "Print job was successfully sent to the printer."),
  206. lifetime=5, dismissable=True,
  207. title=i18n_catalog.i18nc("@info:title", "Data Sent"))
  208. self._success_message.addAction("View", i18n_catalog.i18nc("@action:button", "View in Monitor"), icon=None,
  209. description="")
  210. self._success_message.actionTriggered.connect(self._successMessageActionTriggered)
  211. self._success_message.show()
  212. else:
  213. if self._progress_message is not None:
  214. self._progress_message.setProgress(0)
  215. self._progress_message.hide()
  216. def _progressMessageActionTriggered(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
  217. if action_id == "Abort":
  218. Logger.log("d", "User aborted sending print to remote.")
  219. if self._progress_message is not None:
  220. self._progress_message.hide()
  221. self._compressing_gcode = False
  222. self._sending_gcode = False
  223. CuraApplication.getInstance().getController().setActiveStage("PrepareStage")
  224. # After compressing the sliced model Cura sends data to printer, to stop receiving updates from the request
  225. # the "reply" should be disconnected
  226. if self._latest_reply_handler:
  227. self._latest_reply_handler.disconnect()
  228. self._latest_reply_handler = None
  229. def _successMessageActionTriggered(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
  230. if action_id == "View":
  231. CuraApplication.getInstance().getController().setActiveStage("MonitorStage")
  232. @pyqtSlot()
  233. def openPrintJobControlPanel(self) -> None:
  234. Logger.log("d", "Opening print job control panel...")
  235. QDesktopServices.openUrl(QUrl("http://" + self._address + "/print_jobs"))
  236. @pyqtSlot()
  237. def openPrinterControlPanel(self) -> None:
  238. Logger.log("d", "Opening printer control panel...")
  239. QDesktopServices.openUrl(QUrl("http://" + self._address + "/printers"))
  240. @pyqtProperty("QVariantList", notify = printJobsChanged)
  241. def printJobs(self)-> List[PrintJobOutputModel]:
  242. return self._print_jobs
  243. @pyqtProperty("QVariantList", notify = printJobsChanged)
  244. def queuedPrintJobs(self) -> List[PrintJobOutputModel]:
  245. return [print_job for print_job in self._print_jobs if print_job.state == "queued"]
  246. @pyqtProperty("QVariantList", notify = printJobsChanged)
  247. def activePrintJobs(self) -> List[PrintJobOutputModel]:
  248. return [print_job for print_job in self._print_jobs if print_job.assignedPrinter is not None and print_job.state != "queued"]
  249. @pyqtProperty("QVariantList", notify = clusterPrintersChanged)
  250. def connectedPrintersTypeCount(self) -> List[Dict[str, str]]:
  251. printer_count = {} # type: Dict[str, int]
  252. for printer in self._printers:
  253. if printer.type in printer_count:
  254. printer_count[printer.type] += 1
  255. else:
  256. printer_count[printer.type] = 1
  257. result = []
  258. for machine_type in printer_count:
  259. result.append({"machine_type": machine_type, "count": str(printer_count[machine_type])})
  260. return result
  261. @pyqtSlot(int, result = str)
  262. def formatDuration(self, seconds: int) -> str:
  263. return Duration(seconds).getDisplayString(DurationFormat.Format.Short)
  264. @pyqtSlot(int, result = str)
  265. def getTimeCompleted(self, time_remaining: int) -> str:
  266. current_time = time()
  267. datetime_completed = datetime.fromtimestamp(current_time + time_remaining)
  268. return "{hour:02d}:{minute:02d}".format(hour=datetime_completed.hour, minute=datetime_completed.minute)
  269. @pyqtSlot(int, result = str)
  270. def getDateCompleted(self, time_remaining: int) -> str:
  271. current_time = time()
  272. datetime_completed = datetime.fromtimestamp(current_time + time_remaining)
  273. return (datetime_completed.strftime("%a %b ") + "{day}".format(day=datetime_completed.day)).upper()
  274. def _printJobStateChanged(self) -> None:
  275. username = self._getUserName()
  276. if username is None:
  277. return # We only want to show notifications if username is set.
  278. finished_jobs = [job for job in self._print_jobs if job.state == "wait_cleanup"]
  279. newly_finished_jobs = [job for job in finished_jobs if job not in self._finished_jobs and job.owner == username]
  280. for job in newly_finished_jobs:
  281. if job.assignedPrinter:
  282. job_completed_text = i18n_catalog.i18nc("@info:status", "Printer '{printer_name}' has finished printing '{job_name}'.".format(printer_name=job.assignedPrinter.name, job_name = job.name))
  283. else:
  284. job_completed_text = i18n_catalog.i18nc("@info:status", "The print job '{job_name}' was finished.".format(job_name = job.name))
  285. job_completed_message = Message(text=job_completed_text, title = i18n_catalog.i18nc("@info:status", "Print finished"))
  286. job_completed_message.show()
  287. # Ensure UI gets updated
  288. self.printJobsChanged.emit()
  289. # Keep a list of all completed jobs so we know if something changed next time.
  290. self._finished_jobs = finished_jobs
  291. ## Called when the connection to the cluster changes.
  292. def connect(self) -> None:
  293. super().connect()
  294. self.sendMaterialProfiles()
  295. def _update(self) -> None:
  296. super()._update()
  297. self.get("printers/", on_finished = self._onGetPrintersDataFinished)
  298. self.get("print_jobs/", on_finished = self._onGetPrintJobsFinished)
  299. def _onGetPrintJobsFinished(self, reply: QNetworkReply) -> None:
  300. if not checkValidGetReply(reply):
  301. return
  302. result = loadJsonFromReply(reply)
  303. if result is None:
  304. return
  305. print_jobs_seen = []
  306. job_list_changed = False
  307. for print_job_data in result:
  308. print_job = findByKey(self._print_jobs, print_job_data["uuid"])
  309. if print_job is None:
  310. print_job = self._createPrintJobModel(print_job_data)
  311. job_list_changed = True
  312. self._updatePrintJob(print_job, print_job_data)
  313. if print_job.state != "queued": # Print job should be assigned to a printer.
  314. if print_job.state in ["failed", "finished", "aborted", "none"]:
  315. # Print job was already completed, so don't attach it to a printer.
  316. printer = None
  317. else:
  318. printer = self._getPrinterByKey(print_job_data["printer_uuid"])
  319. else: # The job can "reserve" a printer if some changes are required.
  320. printer = self._getPrinterByKey(print_job_data["assigned_to"])
  321. if printer:
  322. printer.updateActivePrintJob(print_job)
  323. print_jobs_seen.append(print_job)
  324. # Check what jobs need to be removed.
  325. removed_jobs = [print_job for print_job in self._print_jobs if print_job not in print_jobs_seen]
  326. for removed_job in removed_jobs:
  327. job_list_changed = job_list_changed or self._removeJob(removed_job)
  328. if job_list_changed:
  329. self.printJobsChanged.emit() # Do a single emit for all print job changes.
  330. def _onGetPrintersDataFinished(self, reply: QNetworkReply) -> None:
  331. if not checkValidGetReply(reply):
  332. return
  333. result = loadJsonFromReply(reply)
  334. if result is None:
  335. return
  336. printer_list_changed = False
  337. printers_seen = []
  338. for printer_data in result:
  339. printer = findByKey(self._printers, printer_data["uuid"])
  340. if printer is None:
  341. printer = self._createPrinterModel(printer_data)
  342. printer_list_changed = True
  343. printers_seen.append(printer)
  344. self._updatePrinter(printer, printer_data)
  345. removed_printers = [printer for printer in self._printers if printer not in printers_seen]
  346. for printer in removed_printers:
  347. self._removePrinter(printer)
  348. if removed_printers or printer_list_changed:
  349. self.printersChanged.emit()
  350. def _createPrinterModel(self, data: Dict[str, Any]) -> PrinterOutputModel:
  351. printer = PrinterOutputModel(output_controller = ClusterUM3PrinterOutputController(self),
  352. number_of_extruders = self._number_of_extruders)
  353. printer.setCamera(NetworkCamera("http://" + data["ip_address"] + ":8080/?action=stream"))
  354. self._printers.append(printer)
  355. return printer
  356. def _createPrintJobModel(self, data: Dict[str, Any]) -> PrintJobOutputModel:
  357. print_job = PrintJobOutputModel(output_controller=ClusterUM3PrinterOutputController(self),
  358. key=data["uuid"], name= data["name"])
  359. print_job.stateChanged.connect(self._printJobStateChanged)
  360. self._print_jobs.append(print_job)
  361. return print_job
  362. def _updatePrintJob(self, print_job: PrintJobOutputModel, data: Dict[str, Any]) -> None:
  363. print_job.updateTimeTotal(data["time_total"])
  364. print_job.updateTimeElapsed(data["time_elapsed"])
  365. print_job.updateState(data["status"])
  366. print_job.updateOwner(data["owner"])
  367. def _updatePrinter(self, printer: PrinterOutputModel, data: Dict[str, Any]) -> None:
  368. # For some unknown reason the cluster wants UUID for everything, except for sending a job directly to a printer.
  369. # Then we suddenly need the unique name. So in order to not have to mess up all the other code, we save a mapping.
  370. self._printer_uuid_to_unique_name_mapping[data["uuid"]] = data["unique_name"]
  371. definitions = ContainerRegistry.getInstance().findDefinitionContainers(name = data["machine_variant"])
  372. if not definitions:
  373. Logger.log("w", "Unable to find definition for machine variant %s", data["machine_variant"])
  374. return
  375. machine_definition = definitions[0]
  376. printer.updateName(data["friendly_name"])
  377. printer.updateKey(data["uuid"])
  378. printer.updateType(data["machine_variant"])
  379. # Do not store the build plate information that comes from connect if the current printer has not build plate information
  380. if "build_plate" in data and machine_definition.getMetaDataEntry("has_variant_buildplates", False):
  381. printer.updateBuildplateName(data["build_plate"]["type"])
  382. if not data["enabled"]:
  383. printer.updateState("disabled")
  384. else:
  385. printer.updateState(data["status"])
  386. for index in range(0, self._number_of_extruders):
  387. extruder = printer.extruders[index]
  388. try:
  389. extruder_data = data["configuration"][index]
  390. except IndexError:
  391. break
  392. extruder.updateHotendID(extruder_data.get("print_core_id", ""))
  393. material_data = extruder_data["material"]
  394. if extruder.activeMaterial is None or extruder.activeMaterial.guid != material_data["guid"]:
  395. containers = ContainerRegistry.getInstance().findInstanceContainers(type="material",
  396. GUID=material_data["guid"])
  397. if containers:
  398. color = containers[0].getMetaDataEntry("color_code")
  399. brand = containers[0].getMetaDataEntry("brand")
  400. material_type = containers[0].getMetaDataEntry("material")
  401. name = containers[0].getName()
  402. else:
  403. Logger.log("w",
  404. "Unable to find material with guid {guid}. Using data as provided by cluster".format(
  405. guid=material_data["guid"]))
  406. color = material_data["color"]
  407. brand = material_data["brand"]
  408. material_type = material_data["material"]
  409. name = "Empty" if material_data["material"] == "empty" else "Unknown"
  410. material = MaterialOutputModel(guid=material_data["guid"], type=material_type,
  411. brand=brand, color=color, name=name)
  412. extruder.updateActiveMaterial(material)
  413. def _removeJob(self, job: PrintJobOutputModel) -> bool:
  414. if job not in self._print_jobs:
  415. return False
  416. if job.assignedPrinter:
  417. job.assignedPrinter.updateActivePrintJob(None)
  418. job.stateChanged.disconnect(self._printJobStateChanged)
  419. self._print_jobs.remove(job)
  420. return True
  421. def _removePrinter(self, printer: PrinterOutputModel) -> None:
  422. self._printers.remove(printer)
  423. if self._active_printer == printer:
  424. self._active_printer = None
  425. self.activePrinterChanged.emit()
  426. ## Sync the material profiles in Cura with the printer.
  427. #
  428. # This gets called when connecting to a printer as well as when sending a
  429. # print.
  430. def sendMaterialProfiles(self) -> None:
  431. job = SendMaterialJob(device = self)
  432. job.run()
  433. def loadJsonFromReply(reply: QNetworkReply) -> Optional[List[Dict[str, Any]]]:
  434. try:
  435. result = json.loads(bytes(reply.readAll()).decode("utf-8"))
  436. except json.decoder.JSONDecodeError:
  437. Logger.logException("w", "Unable to decode JSON from reply.")
  438. return None
  439. return result
  440. def checkValidGetReply(reply: QNetworkReply) -> bool:
  441. status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
  442. if status_code != 200:
  443. Logger.log("w", "Got status code {status_code} while trying to get data".format(status_code=status_code))
  444. return False
  445. return True
  446. def findByKey(list: List[Union[PrintJobOutputModel, PrinterOutputModel]], key: str) -> Optional[PrintJobOutputModel]:
  447. for item in list:
  448. if item.key == key:
  449. return item
  450. return None