ClusterUM3OutputDevice.py 28 KB

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