ClusterUM3OutputDevice.py 26 KB

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