PrinterOutputDevice.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Decorators import deprecated
  4. from UM.i18n import i18nCatalog
  5. from UM.OutputDevice.OutputDevice import OutputDevice
  6. from PyQt5.QtCore import pyqtProperty, pyqtSignal, QObject, QTimer, QUrl
  7. from PyQt5.QtWidgets import QMessageBox
  8. from UM.Logger import Logger
  9. from UM.Signal import signalemitter
  10. from UM.Qt.QtApplication import QtApplication
  11. from UM.FlameProfiler import pyqtSlot
  12. from enum import IntEnum # For the connection state tracking.
  13. from typing import Callable, List, Optional, Union
  14. MYPY = False
  15. if MYPY:
  16. from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
  17. from cura.PrinterOutput.ConfigurationModel import ConfigurationModel
  18. from cura.PrinterOutput.FirmwareUpdater import FirmwareUpdater
  19. from UM.FileHandler.FileHandler import FileHandler
  20. from UM.Scene.SceneNode import SceneNode
  21. i18n_catalog = i18nCatalog("cura")
  22. ## The current processing state of the backend.
  23. class ConnectionState(IntEnum):
  24. closed = 0
  25. connecting = 1
  26. connected = 2
  27. busy = 3
  28. error = 4
  29. ## Printer output device adds extra interface options on top of output device.
  30. #
  31. # The assumption is made the printer is a FDM printer.
  32. #
  33. # Note that a number of settings are marked as "final". This is because decorators
  34. # are not inherited by children. To fix this we use the private counter part of those
  35. # functions to actually have the implementation.
  36. #
  37. # For all other uses it should be used in the same way as a "regular" OutputDevice.
  38. @signalemitter
  39. class PrinterOutputDevice(QObject, OutputDevice):
  40. printersChanged = pyqtSignal()
  41. connectionStateChanged = pyqtSignal(str)
  42. acceptsCommandsChanged = pyqtSignal()
  43. # Signal to indicate that the material of the active printer on the remote changed.
  44. materialIdChanged = pyqtSignal()
  45. # # Signal to indicate that the hotend of the active printer on the remote changed.
  46. hotendIdChanged = pyqtSignal()
  47. # Signal to indicate that the info text about the connection has changed.
  48. connectionTextChanged = pyqtSignal()
  49. # Signal to indicate that the configuration of one of the printers has changed.
  50. uniqueConfigurationsChanged = pyqtSignal()
  51. def __init__(self, device_id: str, parent: QObject = None) -> None:
  52. super().__init__(device_id = device_id, parent = parent) # type: ignore # MyPy complains with the multiple inheritance
  53. self._printers = [] # type: List[PrinterOutputModel]
  54. self._unique_configurations = [] # type: List[ConfigurationModel]
  55. self._monitor_view_qml_path = "" #type: str
  56. self._monitor_component = None #type: Optional[QObject]
  57. self._monitor_item = None #type: Optional[QObject]
  58. self._control_view_qml_path = "" #type: str
  59. self._control_component = None #type: Optional[QObject]
  60. self._control_item = None #type: Optional[QObject]
  61. self._accepts_commands = False #type: bool
  62. self._update_timer = QTimer() #type: QTimer
  63. self._update_timer.setInterval(2000) # TODO; Add preference for update interval
  64. self._update_timer.setSingleShot(False)
  65. self._update_timer.timeout.connect(self._update)
  66. self._connection_state = ConnectionState.closed #type: ConnectionState
  67. self._firmware_updater = None #type: Optional[FirmwareUpdater]
  68. self._firmware_name = None #type: Optional[str]
  69. self._address = "" #type: str
  70. self._connection_text = "" #type: str
  71. self.printersChanged.connect(self._onPrintersChanged)
  72. QtApplication.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._updateUniqueConfigurations)
  73. @pyqtProperty(str, notify = connectionTextChanged)
  74. def address(self) -> str:
  75. return self._address
  76. def setConnectionText(self, connection_text):
  77. if self._connection_text != connection_text:
  78. self._connection_text = connection_text
  79. self.connectionTextChanged.emit()
  80. @pyqtProperty(str, constant=True)
  81. def connectionText(self) -> str:
  82. return self._connection_text
  83. def materialHotendChangedMessage(self, callback: Callable[[int], None]) -> None:
  84. Logger.log("w", "materialHotendChangedMessage needs to be implemented, returning 'Yes'")
  85. callback(QMessageBox.Yes)
  86. def isConnected(self) -> bool:
  87. return self._connection_state != ConnectionState.closed and self._connection_state != ConnectionState.error
  88. def setConnectionState(self, connection_state: ConnectionState) -> None:
  89. if self._connection_state != connection_state:
  90. self._connection_state = connection_state
  91. self.connectionStateChanged.emit(self._id)
  92. @pyqtProperty(str, notify = connectionStateChanged)
  93. def connectionState(self) -> ConnectionState:
  94. return self._connection_state
  95. def _update(self) -> None:
  96. pass
  97. def _getPrinterByKey(self, key: str) -> Optional["PrinterOutputModel"]:
  98. for printer in self._printers:
  99. if printer.key == key:
  100. return printer
  101. return None
  102. def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False, file_handler: Optional["FileHandler"] = None, **kwargs: str) -> None:
  103. raise NotImplementedError("requestWrite needs to be implemented")
  104. @pyqtProperty(QObject, notify = printersChanged)
  105. def activePrinter(self) -> Optional["PrinterOutputModel"]:
  106. if len(self._printers):
  107. return self._printers[0]
  108. return None
  109. @pyqtProperty("QVariantList", notify = printersChanged)
  110. def printers(self) -> List["PrinterOutputModel"]:
  111. return self._printers
  112. @pyqtProperty(QObject, constant = True)
  113. def monitorItem(self) -> QObject:
  114. # Note that we specifically only check if the monitor component is created.
  115. # It could be that it failed to actually create the qml item! If we check if the item was created, it will try to
  116. # create the item (and fail) every time.
  117. if not self._monitor_component:
  118. self._createMonitorViewFromQML()
  119. return self._monitor_item
  120. @pyqtProperty(QObject, constant = True)
  121. def controlItem(self) -> QObject:
  122. if not self._control_component:
  123. self._createControlViewFromQML()
  124. return self._control_item
  125. def _createControlViewFromQML(self) -> None:
  126. if not self._control_view_qml_path:
  127. return
  128. if self._control_item is None:
  129. self._control_item = QtApplication.getInstance().createQmlComponent(self._control_view_qml_path, {"OutputDevice": self})
  130. def _createMonitorViewFromQML(self) -> None:
  131. if not self._monitor_view_qml_path:
  132. return
  133. if self._monitor_item is None:
  134. self._monitor_item = QtApplication.getInstance().createQmlComponent(self._monitor_view_qml_path, {"OutputDevice": self})
  135. ## Attempt to establish connection
  136. def connect(self) -> None:
  137. self.setConnectionState(ConnectionState.connecting)
  138. self._update_timer.start()
  139. ## Attempt to close the connection
  140. def close(self) -> None:
  141. self._update_timer.stop()
  142. self.setConnectionState(ConnectionState.closed)
  143. ## Ensure that close gets called when object is destroyed
  144. def __del__(self) -> None:
  145. self.close()
  146. @pyqtProperty(bool, notify = acceptsCommandsChanged)
  147. def acceptsCommands(self) -> bool:
  148. return self._accepts_commands
  149. @deprecated("Please use the protected function instead", "3.2")
  150. def setAcceptsCommands(self, accepts_commands: bool) -> None:
  151. self._setAcceptsCommands(accepts_commands)
  152. ## Set a flag to signal the UI that the printer is not (yet) ready to receive commands
  153. def _setAcceptsCommands(self, accepts_commands: bool) -> None:
  154. if self._accepts_commands != accepts_commands:
  155. self._accepts_commands = accepts_commands
  156. self.acceptsCommandsChanged.emit()
  157. # Returns the unique configurations of the printers within this output device
  158. @pyqtProperty("QVariantList", notify = uniqueConfigurationsChanged)
  159. def uniqueConfigurations(self) -> List["ConfigurationModel"]:
  160. return self._unique_configurations
  161. def _updateUniqueConfigurations(self) -> None:
  162. self._unique_configurations = list(set([printer.printerConfiguration for printer in self._printers if printer.printerConfiguration is not None]))
  163. self._unique_configurations.sort(key = lambda k: k.printerType)
  164. self.uniqueConfigurationsChanged.emit()
  165. def _onPrintersChanged(self) -> None:
  166. for printer in self._printers:
  167. printer.configurationChanged.connect(self._updateUniqueConfigurations)
  168. # At this point there may be non-updated configurations
  169. self._updateUniqueConfigurations()
  170. ## Set the device firmware name
  171. #
  172. # \param name The name of the firmware.
  173. def _setFirmwareName(self, name: str) -> None:
  174. self._firmware_name = name
  175. ## Get the name of device firmware
  176. #
  177. # This name can be used to define device type
  178. def getFirmwareName(self) -> Optional[str]:
  179. return self._firmware_name
  180. def getFirmwareUpdater(self) -> Optional["FirmwareUpdater"]:
  181. return self._firmware_updater
  182. @pyqtSlot(str)
  183. def updateFirmware(self, firmware_file: Union[str, QUrl]) -> None:
  184. if not self._firmware_updater:
  185. return
  186. self._firmware_updater.updateFirmware(firmware_file)