PrinterOutputDevice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from enum import IntEnum
  4. from typing import Callable, List, Optional, Union
  5. from PyQt5.QtCore import pyqtProperty, pyqtSignal, QObject, QTimer, QUrl
  6. from PyQt5.QtWidgets import QMessageBox
  7. import cura.CuraApplication # Imported like this to prevent circular imports.
  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 UM.i18n import i18nCatalog
  13. from UM.OutputDevice.OutputDevice import OutputDevice
  14. MYPY = False
  15. if MYPY:
  16. from UM.FileHandler.FileHandler import FileHandler
  17. from UM.Scene.SceneNode import SceneNode
  18. from .Models.PrinterOutputModel import PrinterOutputModel
  19. from .Models.PrinterConfigurationModel import PrinterConfigurationModel
  20. from .FirmwareUpdater import FirmwareUpdater
  21. i18n_catalog = i18nCatalog("cura")
  22. class ConnectionState(IntEnum):
  23. """The current processing state of the backend."""
  24. Closed = 0
  25. Connecting = 1
  26. Connected = 2
  27. Busy = 3
  28. Error = 4
  29. class ConnectionType(IntEnum):
  30. NotConnected = 0
  31. UsbConnection = 1
  32. NetworkConnection = 2
  33. CloudConnection = 3
  34. @signalemitter
  35. class PrinterOutputDevice(QObject, OutputDevice):
  36. """Printer output device adds extra interface options on top of output device.
  37. The assumption is made the printer is a FDM printer.
  38. Note that a number of settings are marked as "final". This is because decorators
  39. are not inherited by children. To fix this we use the private counter part of those
  40. functions to actually have the implementation.
  41. For all other uses it should be used in the same way as a "regular" OutputDevice.
  42. """
  43. printersChanged = pyqtSignal()
  44. connectionStateChanged = pyqtSignal(str)
  45. acceptsCommandsChanged = pyqtSignal()
  46. # Signal to indicate that the material of the active printer on the remote changed.
  47. materialIdChanged = pyqtSignal()
  48. # # Signal to indicate that the hotend of the active printer on the remote changed.
  49. hotendIdChanged = pyqtSignal()
  50. # Signal to indicate that the info text about the connection has changed.
  51. connectionTextChanged = pyqtSignal()
  52. # Signal to indicate that the configuration of one of the printers has changed.
  53. uniqueConfigurationsChanged = pyqtSignal()
  54. def __init__(self, device_id: str, connection_type: "ConnectionType" = ConnectionType.NotConnected, parent: QObject = None) -> None:
  55. super().__init__(device_id = device_id, parent = parent) # type: ignore # MyPy complains with the multiple inheritance
  56. self._printers = [] # type: List[PrinterOutputModel]
  57. self._unique_configurations = [] # type: List[PrinterConfigurationModel]
  58. self._monitor_view_qml_path = "" # type: str
  59. self._monitor_component = None # type: Optional[QObject]
  60. self._monitor_item = None # type: Optional[QObject]
  61. self._control_view_qml_path = "" # type: str
  62. self._control_component = None # type: Optional[QObject]
  63. self._control_item = None # type: Optional[QObject]
  64. self._accepts_commands = False # type: bool
  65. self._update_timer = QTimer() # type: QTimer
  66. self._update_timer.setInterval(2000) # TODO; Add preference for update interval
  67. self._update_timer.setSingleShot(False)
  68. self._update_timer.timeout.connect(self._update)
  69. self._connection_state = ConnectionState.Closed # type: ConnectionState
  70. self._connection_type = connection_type # type: ConnectionType
  71. self._firmware_updater = None # type: Optional[FirmwareUpdater]
  72. self._firmware_name = None # type: Optional[str]
  73. self._address = "" # type: str
  74. self._connection_text = "" # type: str
  75. self.printersChanged.connect(self._onPrintersChanged)
  76. QtApplication.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(self._updateUniqueConfigurations)
  77. @pyqtProperty(str, notify = connectionTextChanged)
  78. def address(self) -> str:
  79. return self._address
  80. def setConnectionText(self, connection_text):
  81. if self._connection_text != connection_text:
  82. self._connection_text = connection_text
  83. self.connectionTextChanged.emit()
  84. @pyqtProperty(str, constant=True)
  85. def connectionText(self) -> str:
  86. return self._connection_text
  87. def materialHotendChangedMessage(self, callback: Callable[[int], None]) -> None:
  88. Logger.log("w", "materialHotendChangedMessage needs to be implemented, returning 'Yes'")
  89. callback(QMessageBox.Yes)
  90. def isConnected(self) -> bool:
  91. """
  92. Returns whether we could theoretically send commands to this printer.
  93. :return: `True` if we are connected, or `False` if not.
  94. """
  95. return self.connectionState != ConnectionState.Closed and self.connectionState != ConnectionState.Error
  96. def setConnectionState(self, connection_state: "ConnectionState") -> None:
  97. """
  98. Store the connection state of the printer.
  99. Causes everything that displays the connection state to update its QML models.
  100. :param connection_state: The new connection state to store.
  101. """
  102. if self.connectionState != connection_state:
  103. self._connection_state = connection_state
  104. cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack().setMetaDataEntry("is_online", self.isConnected())
  105. self.connectionStateChanged.emit(self._id)
  106. @pyqtProperty(int, constant = True)
  107. def connectionType(self) -> "ConnectionType":
  108. return self._connection_type
  109. @pyqtProperty(int, notify = connectionStateChanged)
  110. def connectionState(self) -> "ConnectionState":
  111. """
  112. Get the connection state of the printer, e.g. whether it is connected, still connecting, error state, etc.
  113. :return: The current connection state of this output device.
  114. """
  115. return self._connection_state
  116. def _update(self) -> None:
  117. pass
  118. def _getPrinterByKey(self, key: str) -> Optional["PrinterOutputModel"]:
  119. for printer in self._printers:
  120. if printer.key == key:
  121. return printer
  122. return None
  123. def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False,
  124. file_handler: Optional["FileHandler"] = None, filter_by_machine: bool = False, **kwargs) -> None:
  125. raise NotImplementedError("requestWrite needs to be implemented")
  126. @pyqtProperty(QObject, notify = printersChanged)
  127. def activePrinter(self) -> Optional["PrinterOutputModel"]:
  128. if self._printers:
  129. return self._printers[0]
  130. return None
  131. @pyqtProperty("QVariantList", notify = printersChanged)
  132. def printers(self) -> List["PrinterOutputModel"]:
  133. return self._printers
  134. @pyqtProperty(QObject, constant = True)
  135. def monitorItem(self) -> QObject:
  136. # Note that we specifically only check if the monitor component is created.
  137. # It could be that it failed to actually create the qml item! If we check if the item was created, it will try to
  138. # create the item (and fail) every time.
  139. if not self._monitor_component:
  140. self._createMonitorViewFromQML()
  141. return self._monitor_item
  142. @pyqtProperty(QObject, constant = True)
  143. def controlItem(self) -> QObject:
  144. if not self._control_component:
  145. self._createControlViewFromQML()
  146. return self._control_item
  147. def _createControlViewFromQML(self) -> None:
  148. if not self._control_view_qml_path:
  149. return
  150. if self._control_item is None:
  151. self._control_item = QtApplication.getInstance().createQmlComponent(self._control_view_qml_path, {"OutputDevice": self})
  152. def _createMonitorViewFromQML(self) -> None:
  153. if not self._monitor_view_qml_path:
  154. return
  155. if self._monitor_item is None:
  156. self._monitor_item = QtApplication.getInstance().createQmlComponent(self._monitor_view_qml_path, {"OutputDevice": self})
  157. def connect(self) -> None:
  158. """Attempt to establish connection"""
  159. self.setConnectionState(ConnectionState.Connecting)
  160. self._update_timer.start()
  161. def close(self) -> None:
  162. """Attempt to close the connection"""
  163. self._update_timer.stop()
  164. self.setConnectionState(ConnectionState.Closed)
  165. def __del__(self) -> None:
  166. """Ensure that close gets called when object is destroyed"""
  167. self.close()
  168. @pyqtProperty(bool, notify = acceptsCommandsChanged)
  169. def acceptsCommands(self) -> bool:
  170. return self._accepts_commands
  171. def _setAcceptsCommands(self, accepts_commands: bool) -> None:
  172. """Set a flag to signal the UI that the printer is not (yet) ready to receive commands"""
  173. if self._accepts_commands != accepts_commands:
  174. self._accepts_commands = accepts_commands
  175. self.acceptsCommandsChanged.emit()
  176. # Returns the unique configurations of the printers within this output device
  177. @pyqtProperty("QVariantList", notify = uniqueConfigurationsChanged)
  178. def uniqueConfigurations(self) -> List["PrinterConfigurationModel"]:
  179. return self._unique_configurations
  180. def _updateUniqueConfigurations(self) -> None:
  181. all_configurations = set()
  182. for printer in self._printers:
  183. if printer.printerConfiguration is not None and printer.printerConfiguration.hasAnyMaterialLoaded():
  184. all_configurations.add(printer.printerConfiguration)
  185. all_configurations.update(printer.availableConfigurations)
  186. if None in all_configurations: # Shouldn't happen, but it does. I don't see how it could ever happen. Skip adding that configuration. List could end up empty!
  187. Logger.log("e", "Found a broken configuration in the synced list!")
  188. all_configurations.remove(None)
  189. new_configurations = sorted(all_configurations, key = lambda config: config.printerType or "")
  190. if new_configurations != self._unique_configurations:
  191. self._unique_configurations = new_configurations
  192. self.uniqueConfigurationsChanged.emit()
  193. # Returns the unique configurations of the printers within this output device
  194. @pyqtProperty("QStringList", notify = uniqueConfigurationsChanged)
  195. def uniquePrinterTypes(self) -> List[str]:
  196. return list(sorted(set([configuration.printerType or "" for configuration in self._unique_configurations])))
  197. def _onPrintersChanged(self) -> None:
  198. for printer in self._printers:
  199. printer.configurationChanged.connect(self._updateUniqueConfigurations)
  200. printer.availableConfigurationsChanged.connect(self._updateUniqueConfigurations)
  201. # At this point there may be non-updated configurations
  202. self._updateUniqueConfigurations()
  203. def _setFirmwareName(self, name: str) -> None:
  204. """Set the device firmware name
  205. :param name: The name of the firmware.
  206. """
  207. self._firmware_name = name
  208. def getFirmwareName(self) -> Optional[str]:
  209. """Get the name of device firmware
  210. This name can be used to define device type
  211. """
  212. return self._firmware_name
  213. def getFirmwareUpdater(self) -> Optional["FirmwareUpdater"]:
  214. return self._firmware_updater
  215. @pyqtSlot(str)
  216. def updateFirmware(self, firmware_file: Union[str, QUrl]) -> None:
  217. if not self._firmware_updater:
  218. return
  219. self._firmware_updater.updateFirmware(firmware_file)