PrinterOutputDevice.py 10 KB

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