CuraEngineBackend.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Backend.Backend import Backend
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Preferences import Preferences
  7. from UM.Signal import Signal
  8. from UM.Logger import Logger
  9. from UM.Qt.Bindings.BackendProxy import BackendState #To determine the state of the slicing job.
  10. from UM.Message import Message
  11. from UM.PluginRegistry import PluginRegistry
  12. from UM.Resources import Resources
  13. from cura.OneAtATimeIterator import OneAtATimeIterator
  14. from . import ProcessSlicedLayersJob
  15. from . import ProcessGCodeJob
  16. from . import StartSliceJob
  17. import os
  18. import sys
  19. from PyQt5.QtCore import QTimer
  20. import Arcus
  21. from UM.i18n import i18nCatalog
  22. catalog = i18nCatalog("cura")
  23. class CuraEngineBackend(Backend):
  24. ## Starts the back-end plug-in.
  25. #
  26. # This registers all the signal listeners and prepares for communication
  27. # with the back-end in general.
  28. def __init__(self):
  29. super().__init__()
  30. # Find out where the engine is located, and how it is called. This depends on how Cura is packaged and which OS we are running on.
  31. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  32. if hasattr(sys, "frozen"):
  33. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  34. if sys.platform == "win32":
  35. default_engine_location += ".exe"
  36. default_engine_location = os.path.abspath(default_engine_location)
  37. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  38. self._scene = Application.getInstance().getController().getScene()
  39. self._scene.sceneChanged.connect(self._onSceneChanged)
  40. # Workaround to disable layer view processing if layer view is not active.
  41. self._layer_view_active = False
  42. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  43. self._onActiveViewChanged()
  44. self._stored_layer_data = []
  45. #When any setting property changed, call the _onSettingChanged function.
  46. #This function will then see if we need to start slicing.
  47. Application.getInstance().getGlobalContainerStack().propertyChanged.connect(self._onSettingChanged)
  48. #When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  49. #This timer will group them up, and only slice for the last setting changed signal.
  50. #TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  51. self._change_timer = QTimer()
  52. self._change_timer.setInterval(500)
  53. self._change_timer.setSingleShot(True)
  54. self._change_timer.timeout.connect(self.slice)
  55. #Listeners for receiving messages from the back-end.
  56. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  57. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  58. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  59. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  60. self._message_handlers["cura.proto.ObjectPrintTime"] = self._onObjectPrintTimeMessage
  61. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  62. self._slicing = False #Are we currently slicing?
  63. self._restart = False #Back-end is currently restarting?
  64. self._enabled = True #Should we be slicing? Slicing might be paused when, for instance, the user is dragging the mesh around.
  65. self._always_restart = True #Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  66. self._process_layers_job = None #The currently active job to process layers, or None if it is not processing layers.
  67. self._message = None #Pop-up message that shows the slicing progress bar (or an error message).
  68. self.backendQuit.connect(self._onBackendQuit)
  69. self.backendConnected.connect(self._onBackendConnected)
  70. #When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  71. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  72. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  73. ## Called when closing the application.
  74. #
  75. # This function should terminate the engine process.
  76. def close(self):
  77. # Terminate CuraEngine if it is still running at this point
  78. self._terminate()
  79. super().close()
  80. ## Get the command that is used to call the engine.
  81. # This is useful for debugging and used to actually start the engine.
  82. # \return list of commands and args / parameters.
  83. def getEngineCommand(self):
  84. active_machine = Application.getInstance().getMachineManager().getActiveMachineInstance()
  85. if not active_machine:
  86. json_path = Resources.getPath(Resources.MachineDefinitions, "fdmprinter.json")
  87. else:
  88. json_path = active_machine.getMachineDefinition().getPath()
  89. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, "-vv"]
  90. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  91. # \param time The amount of time the print will take.
  92. # \param material_amount The amount of material the print will use.
  93. printDurationMessage = Signal()
  94. ## Emitted when the slicing process starts.
  95. slicingStarted = Signal()
  96. ## Emitted when the slicing process is aborted forcefully.
  97. slicingCancelled = Signal()
  98. ## Perform a slice of the scene.
  99. def slice(self):
  100. if not self._enabled: #We shouldn't be slicing.
  101. return
  102. if self._slicing: #We were already slicing. Stop the old job.
  103. self._terminate()
  104. if self._process_layers_job: #We were processing layers. Stop that, the layers are going to change soon.
  105. self._process_layers_job.abort()
  106. self._process_layers_job = None
  107. #TODO: Re-add don't slice with error stuff.
  108. #if self._profile.hasErrorValue():
  109. # Logger.log("w", "Profile has error values. Aborting slicing")
  110. # if self._message:
  111. # self._message.hide()
  112. # self._message = None
  113. # self._message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."))
  114. # self._message.show()
  115. # return #No slicing if we have error values since those are by definition illegal values.
  116. self.processingProgress.emit(0.0)
  117. self.backendStateChange.emit(BackendState.NOT_STARTED)
  118. if self._message:
  119. self._message.setProgress(-1)
  120. else:
  121. self._message = Message(catalog.i18nc("@info:status", "Slicing..."), 0, False, -1)
  122. self._message.show()
  123. self._scene.gcode_list = []
  124. self._slicing = True
  125. self.slicingStarted.emit()
  126. job = StartSliceJob.StartSliceJob(self._socket)
  127. job.start()
  128. job.finished.connect(self._onStartSliceCompleted)
  129. def _terminate(self):
  130. self._slicing = False
  131. self._restart = True
  132. self._stored_layer_data = []
  133. self.slicingCancelled.emit()
  134. self.processingProgress.emit(0)
  135. Logger.log("d", "Attempting to kill the engine process")
  136. if self._process is not None:
  137. Logger.log("d", "Killing engine process")
  138. try:
  139. self._process.terminate()
  140. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  141. self._process = None
  142. #self._createSocket() # Re create the socket
  143. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  144. Logger.log("d", "Exception occured while trying to kill the engine %s", str(e))
  145. if self._message:
  146. self._message.hide()
  147. self._message = None
  148. def _onStartSliceCompleted(self, job):
  149. if job.getError() or job.getResult() != True:
  150. if self._message:
  151. self._message.hide()
  152. self._message = None
  153. return
  154. def _onSceneChanged(self, source):
  155. if type(source) is not SceneNode:
  156. return
  157. if source is self._scene.getRoot():
  158. return
  159. if source.getMeshData() is None:
  160. return
  161. if source.getMeshData().getVertices() is None:
  162. return
  163. self._onChanged()
  164. def _onSocketError(self, error):
  165. if Application.getInstance().isShuttingDown():
  166. return
  167. super()._onSocketError(error)
  168. self._terminate()
  169. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  170. Logger.log("e", "A socket error caused the connection to be reset")
  171. def _onActiveProfileChanged(self):
  172. if self._profile:
  173. self._profile.settingValueChanged.disconnect(self._onSettingChanged)
  174. self._profile = Application.getInstance().getMachineManager().getWorkingProfile()
  175. if self._profile:
  176. self._profile.settingValueChanged.connect(self._onSettingChanged)
  177. self._onChanged()
  178. ## A setting has changed, so check if we must reslice.
  179. #
  180. # \param instance The setting instance that has changed.
  181. # \param property The property of the setting instance that has changed.
  182. def _onSettingChanged(self, instance, property):
  183. if property == "value": #Only reslice if the value has changed.
  184. self._onChanged()
  185. def _onLayerMessage(self, message):
  186. self._stored_layer_data.append(message)
  187. def _onProgressMessage(self, message):
  188. if self._message:
  189. self._message.setProgress(round(message.amount * 100))
  190. self.processingProgress.emit(message.amount)
  191. self.backendStateChange.emit(BackendState.PROCESSING)
  192. def _onSlicingFinishedMessage(self, message):
  193. self.backendStateChange.emit(BackendState.DONE)
  194. self.processingProgress.emit(1.0)
  195. self._slicing = False
  196. if self._message:
  197. self._message.setProgress(100)
  198. self._message.hide()
  199. self._message = None
  200. if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
  201. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_layer_data)
  202. self._process_layers_job.start()
  203. self._stored_layer_data = []
  204. def _onGCodeLayerMessage(self, message):
  205. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  206. def _onGCodePrefixMessage(self, message):
  207. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  208. def _onObjectPrintTimeMessage(self, message):
  209. self.printDurationMessage.emit(message.time, message.material_amount)
  210. def _createSocket(self):
  211. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  212. ## Manually triggers a reslice
  213. def forceSlice(self):
  214. self._change_timer.start()
  215. def _onChanged(self):
  216. self._change_timer.start()
  217. def _onBackendConnected(self):
  218. if self._restart:
  219. self._onChanged()
  220. self._restart = False
  221. def _onToolOperationStarted(self, tool):
  222. self._terminate() # Do not continue slicing once a tool has started
  223. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  224. def _onToolOperationStopped(self, tool):
  225. self._enabled = True # Tool stop, start listening for changes again.
  226. def _onActiveViewChanged(self):
  227. if Application.getInstance().getController().getActiveView():
  228. view = Application.getInstance().getController().getActiveView()
  229. if view.getPluginId() == "LayerView":
  230. self._layer_view_active = True
  231. # There is data and we're not slicing at the moment
  232. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  233. if self._stored_layer_data and not self._slicing:
  234. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_layer_data)
  235. self._process_layers_job.start()
  236. self._stored_layer_data = []
  237. else:
  238. self._layer_view_active = False
  239. def _onInstanceChanged(self):
  240. self._terminate()
  241. def _onBackendQuit(self):
  242. if not self._restart and self._process:
  243. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  244. self._process = None
  245. self._createSocket()