CuraEngineBackend.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. def __init__(self):
  25. super().__init__()
  26. # 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.
  27. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  28. if hasattr(sys, "frozen"):
  29. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  30. if sys.platform == "win32":
  31. default_engine_location += ".exe"
  32. default_engine_location = os.path.abspath(default_engine_location)
  33. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  34. self._scene = Application.getInstance().getController().getScene()
  35. self._scene.sceneChanged.connect(self._onSceneChanged)
  36. # Workaround to disable layer view processing if layer view is not active.
  37. self._layer_view_active = False
  38. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  39. self._onActiveViewChanged()
  40. self._stored_layer_data = []
  41. # When there are current settings and machine instance is changed, there is no profile changed event. We should
  42. # pretend there is though.
  43. Application.getInstance().getMachineManager().activeMachineInstanceChanged.connect(self._onActiveProfileChanged)
  44. self._profile = None
  45. Application.getInstance().getMachineManager().activeProfileChanged.connect(self._onActiveProfileChanged)
  46. self._onActiveProfileChanged()
  47. self._change_timer = QTimer()
  48. self._change_timer.setInterval(500)
  49. self._change_timer.setSingleShot(True)
  50. self._change_timer.timeout.connect(self.slice)
  51. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  52. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  53. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  54. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  55. self._message_handlers["cura.proto.ObjectPrintTime"] = self._onObjectPrintTimeMessage
  56. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  57. self._slicing = False
  58. self._start_slice_job = None
  59. self._restart = False
  60. self._enabled = True
  61. self._always_restart = True
  62. self._process_layers_job = None #The currently active job to process layers, or None if it is not processing layers.
  63. self._message = None
  64. self.backendQuit.connect(self._onBackendQuit)
  65. self.backendConnected.connect(self._onBackendConnected)
  66. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  67. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  68. Application.getInstance().getMachineManager().activeMachineInstanceChanged.connect(self._onInstanceChanged)
  69. def close(self):
  70. # Terminate CuraEngine if it is still running at this point
  71. self._terminate()
  72. super().close()
  73. ## Get the command that is used to call the engine.
  74. # This is usefull for debugging and used to actually start the engine
  75. # \return list of commands and args / parameters.
  76. def getEngineCommand(self):
  77. active_machine = Application.getInstance().getMachineManager().getActiveMachineInstance()
  78. json_path = ""
  79. if not active_machine:
  80. json_path = Resources.getPath(Resources.MachineDefinitions, "fdmprinter.json")
  81. else:
  82. json_path = active_machine.getMachineDefinition().getPath()
  83. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, "-vv"]
  84. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  85. # \param time The amount of time the print will take.
  86. # \param material_amount The amount of material the print will use.
  87. printDurationMessage = Signal()
  88. ## Emitted when the slicing process starts.
  89. slicingStarted = Signal()
  90. ## Emitted whne the slicing process is aborted forcefully.
  91. slicingCancelled = Signal()
  92. ## Perform a slice of the scene.
  93. def slice(self):
  94. if not self._enabled:
  95. return
  96. if self._slicing:
  97. self._terminate()
  98. if self._message:
  99. self._message.hide()
  100. self._message = None
  101. return
  102. if self._process_layers_job:
  103. self._process_layers_job.abort()
  104. self._process_layers_job = None
  105. if self._profile.hasErrorValue():
  106. Logger.log("w", "Profile has error values. Aborting slicing")
  107. if self._message:
  108. self._message.hide()
  109. self._message = None
  110. self._message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."))
  111. self._message.show()
  112. return #No slicing if we have error values since those are by definition illegal values.
  113. self.processingProgress.emit(0.0)
  114. self.backendStateChange.emit(BackendState.NOT_STARTED)
  115. if self._message:
  116. self._message.setProgress(-1)
  117. #else:
  118. # self._message = Message(catalog.i18nc("@info:status", "Slicing..."), 0, False, -1)
  119. # self._message.show()
  120. self._scene.gcode_list = []
  121. self._slicing = True
  122. self.slicingStarted.emit()
  123. slice_message = self._socket.createMessage("cura.proto.Slice")
  124. settings_message = self._socket.createMessage("cura.proto.SettingList");
  125. self._start_slice_job = StartSliceJob.StartSliceJob(self._profile, slice_message, settings_message)
  126. self._start_slice_job.start()
  127. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  128. def _terminate(self):
  129. self._slicing = False
  130. self._restart = True
  131. self._stored_layer_data = []
  132. if self._start_slice_job is not None:
  133. self._start_slice_job.cancel()
  134. self.slicingCancelled.emit()
  135. self.processingProgress.emit(0)
  136. Logger.log("d", "Attempting to kill the engine process")
  137. if self._process is not None:
  138. Logger.log("d", "Killing engine process")
  139. try:
  140. self._process.terminate()
  141. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  142. self._process = None
  143. #self._createSocket() # Re create the socket
  144. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  145. Logger.log("d", "Exception occured while trying to kill the engine %s", str(e))
  146. def _onStartSliceCompleted(self, job):
  147. # Note that cancelled slice jobs can still call this method.
  148. if self._start_slice_job is job:
  149. self._start_slice_job = None
  150. if job.isCancelled() or job.getError() or job.getResult() != True:
  151. if self._message:
  152. self._message.hide()
  153. self._message = None
  154. return
  155. else:
  156. # Preparation completed, send it to the backend.
  157. self._socket.sendMessage(job.getSettingsMessage())
  158. self._socket.sendMessage(job.getSliceMessage())
  159. def _onSceneChanged(self, source):
  160. if type(source) is not SceneNode:
  161. return
  162. if source is self._scene.getRoot():
  163. return
  164. if source.getMeshData() is None:
  165. return
  166. if source.getMeshData().getVertices() is None:
  167. return
  168. self._onChanged()
  169. def _onSocketError(self, error):
  170. if Application.getInstance().isShuttingDown():
  171. return
  172. super()._onSocketError(error)
  173. self._terminate()
  174. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  175. Logger.log("e", "A socket error caused the connection to be reset")
  176. def _onActiveProfileChanged(self):
  177. if self._profile:
  178. self._profile.settingValueChanged.disconnect(self._onSettingChanged)
  179. self._profile = Application.getInstance().getMachineManager().getWorkingProfile()
  180. if self._profile:
  181. self._profile.settingValueChanged.connect(self._onSettingChanged)
  182. self._onChanged()
  183. def _onSettingChanged(self, setting):
  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. if not self._profile:
  217. return
  218. self._change_timer.start()
  219. def _onBackendConnected(self):
  220. if self._restart:
  221. self._onChanged()
  222. self._restart = False
  223. def _onToolOperationStarted(self, tool):
  224. self._terminate() # Do not continue slicing once a tool has started
  225. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  226. def _onToolOperationStopped(self, tool):
  227. self._enabled = True # Tool stop, start listening for changes again.
  228. def _onActiveViewChanged(self):
  229. if Application.getInstance().getController().getActiveView():
  230. view = Application.getInstance().getController().getActiveView()
  231. if view.getPluginId() == "LayerView":
  232. self._layer_view_active = True
  233. # There is data and we're not slicing at the moment
  234. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  235. if self._stored_layer_data and not self._slicing:
  236. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_layer_data)
  237. self._process_layers_job.start()
  238. self._stored_layer_data = []
  239. else:
  240. self._layer_view_active = False
  241. def _onInstanceChanged(self):
  242. self._terminate()
  243. def _onBackendQuit(self):
  244. if not self._restart and self._process:
  245. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  246. self._process = None
  247. self._createSocket()