SliceInfo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import os
  5. import platform
  6. import time
  7. from typing import cast, Optional, Set, TYPE_CHECKING
  8. from PyQt5.QtCore import pyqtSlot, QObject
  9. from PyQt5.QtNetwork import QNetworkRequest
  10. from UM.Extension import Extension
  11. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  12. from UM.i18n import i18nCatalog
  13. from UM.Logger import Logger
  14. from UM.PluginRegistry import PluginRegistry
  15. from UM.Qt.Duration import DurationFormat
  16. from cura import ApplicationMetadata
  17. if TYPE_CHECKING:
  18. from PyQt5.QtNetwork import QNetworkReply
  19. catalog = i18nCatalog("cura")
  20. ## This Extension runs in the background and sends several bits of information to the Ultimaker servers.
  21. # The data is only sent when the user in question gave permission to do so. All data is anonymous and
  22. # no model files are being sent (Just a SHA256 hash of the model).
  23. class SliceInfo(QObject, Extension):
  24. info_url = "https://stats.ultimaker.com/api/cura"
  25. def __init__(self, parent = None):
  26. QObject.__init__(self, parent)
  27. Extension.__init__(self)
  28. from cura.CuraApplication import CuraApplication
  29. self._application = CuraApplication.getInstance()
  30. self._application.getOutputDeviceManager().writeStarted.connect(self._onWriteStarted)
  31. self._application.getPreferences().addPreference("info/send_slice_info", True)
  32. self._application.getPreferences().addPreference("info/asked_send_slice_info", False)
  33. self._more_info_dialog = None
  34. self._example_data_content = None
  35. self._application.initializationFinished.connect(self._onAppInitialized)
  36. def _onAppInitialized(self):
  37. # DO NOT read any preferences values in the constructor because at the time plugins are created, no version
  38. # upgrade has been performed yet because version upgrades are plugins too!
  39. if self._more_info_dialog is None:
  40. self._more_info_dialog = self._createDialog("MoreInfoWindow.qml")
  41. ## Perform action based on user input.
  42. # Note that clicking "Disable" won't actually disable the data sending, but rather take the user to preferences where they can disable it.
  43. def messageActionTriggered(self, message_id, action_id):
  44. self._application.getPreferences().setValue("info/asked_send_slice_info", True)
  45. if action_id == "MoreInfo":
  46. self.showMoreInfoDialog()
  47. self.send_slice_info_message.hide()
  48. def showMoreInfoDialog(self):
  49. if self._more_info_dialog is None:
  50. self._more_info_dialog = self._createDialog("MoreInfoWindow.qml")
  51. self._more_info_dialog.show()
  52. def _createDialog(self, qml_name):
  53. Logger.log("d", "Creating dialog [%s]", qml_name)
  54. file_path = os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), qml_name)
  55. dialog = self._application.createQmlComponent(file_path, {"manager": self})
  56. return dialog
  57. @pyqtSlot(result = str)
  58. def getExampleData(self) -> Optional[str]:
  59. if self._example_data_content is None:
  60. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  61. if not plugin_path:
  62. Logger.log("e", "Could not get plugin path!", self.getPluginId())
  63. return None
  64. file_path = os.path.join(plugin_path, "example_data.html")
  65. if file_path:
  66. with open(file_path, "r", encoding = "utf-8") as f:
  67. self._example_data_content = f.read()
  68. return self._example_data_content
  69. @pyqtSlot(bool)
  70. def setSendSliceInfo(self, enabled: bool):
  71. self._application.getPreferences().setValue("info/send_slice_info", enabled)
  72. def _getUserModifiedSettingKeys(self) -> list:
  73. machine_manager = self._application.getMachineManager()
  74. global_stack = machine_manager.activeMachine
  75. user_modified_setting_keys = set() # type: Set[str]
  76. for stack in [global_stack] + list(global_stack.extruders.values()):
  77. # Get all settings in user_changes and quality_changes
  78. all_keys = stack.userChanges.getAllKeys() | stack.qualityChanges.getAllKeys()
  79. user_modified_setting_keys |= all_keys
  80. return list(sorted(user_modified_setting_keys))
  81. def _onWriteStarted(self, output_device):
  82. try:
  83. if not self._application.getPreferences().getValue("info/send_slice_info"):
  84. Logger.log("d", "'info/send_slice_info' is turned off.")
  85. return # Do nothing, user does not want to send data
  86. machine_manager = self._application.getMachineManager()
  87. print_information = self._application.getPrintInformation()
  88. global_stack = machine_manager.activeMachine
  89. data = dict() # The data that we're going to submit.
  90. data["time_stamp"] = time.time()
  91. data["schema_version"] = 0
  92. data["cura_version"] = self._application.getVersion()
  93. data["cura_build_type"] = ApplicationMetadata.CuraBuildType
  94. active_mode = self._application.getPreferences().getValue("cura/active_mode")
  95. if active_mode == 0:
  96. data["active_mode"] = "recommended"
  97. else:
  98. data["active_mode"] = "custom"
  99. data["camera_view"] = self._application.getPreferences().getValue("general/camera_perspective_mode")
  100. if data["camera_view"] == "orthographic":
  101. data["camera_view"] = "orthogonal" #The database still only recognises the old name "orthogonal".
  102. definition_changes = global_stack.definitionChanges
  103. machine_settings_changed_by_user = False
  104. if definition_changes.getId() != "empty":
  105. # Now a definition_changes container will always be created for a stack,
  106. # so we also need to check if there is any instance in the definition_changes container
  107. if definition_changes.getAllKeys():
  108. machine_settings_changed_by_user = True
  109. data["machine_settings_changed_by_user"] = machine_settings_changed_by_user
  110. data["language"] = self._application.getPreferences().getValue("general/language")
  111. data["os"] = {"type": platform.system(), "version": platform.version()}
  112. data["active_machine"] = {"definition_id": global_stack.definition.getId(),
  113. "manufacturer": global_stack.definition.getMetaDataEntry("manufacturer", "")}
  114. # add extruder specific data to slice info
  115. data["extruders"] = []
  116. extruders = list(global_stack.extruders.values())
  117. extruders = sorted(extruders, key = lambda extruder: extruder.getMetaDataEntry("position"))
  118. for extruder in extruders:
  119. extruder_dict = dict()
  120. extruder_dict["active"] = machine_manager.activeStack == extruder
  121. extruder_dict["material"] = {"GUID": extruder.material.getMetaData().get("GUID", ""),
  122. "type": extruder.material.getMetaData().get("material", ""),
  123. "brand": extruder.material.getMetaData().get("brand", "")
  124. }
  125. extruder_position = int(extruder.getMetaDataEntry("position", "0"))
  126. if len(print_information.materialLengths) > extruder_position:
  127. extruder_dict["material_used"] = print_information.materialLengths[extruder_position]
  128. extruder_dict["variant"] = extruder.variant.getName()
  129. extruder_dict["nozzle_size"] = extruder.getProperty("machine_nozzle_size", "value")
  130. extruder_settings = dict()
  131. extruder_settings["wall_line_count"] = extruder.getProperty("wall_line_count", "value")
  132. extruder_settings["retraction_enable"] = extruder.getProperty("retraction_enable", "value")
  133. extruder_settings["infill_sparse_density"] = extruder.getProperty("infill_sparse_density", "value")
  134. extruder_settings["infill_pattern"] = extruder.getProperty("infill_pattern", "value")
  135. extruder_settings["gradual_infill_steps"] = extruder.getProperty("gradual_infill_steps", "value")
  136. extruder_settings["default_material_print_temperature"] = extruder.getProperty("default_material_print_temperature", "value")
  137. extruder_settings["material_print_temperature"] = extruder.getProperty("material_print_temperature", "value")
  138. extruder_dict["extruder_settings"] = extruder_settings
  139. data["extruders"].append(extruder_dict)
  140. data["intent_category"] = global_stack.getIntentCategory()
  141. data["quality_profile"] = global_stack.quality.getMetaData().get("quality_type")
  142. data["user_modified_setting_keys"] = self._getUserModifiedSettingKeys()
  143. data["models"] = []
  144. # Listing all files placed on the build plate
  145. for node in DepthFirstIterator(self._application.getController().getScene().getRoot()):
  146. if node.callDecoration("isSliceable"):
  147. model = dict()
  148. model["hash"] = node.getMeshData().getHash()
  149. bounding_box = node.getBoundingBox()
  150. if not bounding_box:
  151. continue
  152. model["bounding_box"] = {"minimum": {"x": bounding_box.minimum.x,
  153. "y": bounding_box.minimum.y,
  154. "z": bounding_box.minimum.z},
  155. "maximum": {"x": bounding_box.maximum.x,
  156. "y": bounding_box.maximum.y,
  157. "z": bounding_box.maximum.z}}
  158. model["transformation"] = {"data": str(node.getWorldTransformation().getData()).replace("\n", "")}
  159. extruder_position = node.callDecoration("getActiveExtruderPosition")
  160. model["extruder"] = 0 if extruder_position is None else int(extruder_position)
  161. model_settings = dict()
  162. model_stack = node.callDecoration("getStack")
  163. if model_stack:
  164. model_settings["support_enabled"] = model_stack.getProperty("support_enable", "value")
  165. model_settings["support_extruder_nr"] = int(model_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))
  166. # Mesh modifiers;
  167. model_settings["infill_mesh"] = model_stack.getProperty("infill_mesh", "value")
  168. model_settings["cutting_mesh"] = model_stack.getProperty("cutting_mesh", "value")
  169. model_settings["support_mesh"] = model_stack.getProperty("support_mesh", "value")
  170. model_settings["anti_overhang_mesh"] = model_stack.getProperty("anti_overhang_mesh", "value")
  171. model_settings["wall_line_count"] = model_stack.getProperty("wall_line_count", "value")
  172. model_settings["retraction_enable"] = model_stack.getProperty("retraction_enable", "value")
  173. # Infill settings
  174. model_settings["infill_sparse_density"] = model_stack.getProperty("infill_sparse_density", "value")
  175. model_settings["infill_pattern"] = model_stack.getProperty("infill_pattern", "value")
  176. model_settings["gradual_infill_steps"] = model_stack.getProperty("gradual_infill_steps", "value")
  177. model["model_settings"] = model_settings
  178. data["models"].append(model)
  179. print_times = print_information.printTimes()
  180. data["print_times"] = {"travel": int(print_times["travel"].getDisplayString(DurationFormat.Format.Seconds)),
  181. "support": int(print_times["support"].getDisplayString(DurationFormat.Format.Seconds)),
  182. "infill": int(print_times["infill"].getDisplayString(DurationFormat.Format.Seconds)),
  183. "total": int(print_information.currentPrintTime.getDisplayString(DurationFormat.Format.Seconds))}
  184. print_settings = dict()
  185. print_settings["layer_height"] = global_stack.getProperty("layer_height", "value")
  186. # Support settings
  187. print_settings["support_enabled"] = global_stack.getProperty("support_enable", "value")
  188. print_settings["support_extruder_nr"] = int(global_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))
  189. # Platform adhesion settings
  190. print_settings["adhesion_type"] = global_stack.getProperty("adhesion_type", "value")
  191. # Shell settings
  192. print_settings["wall_line_count"] = global_stack.getProperty("wall_line_count", "value")
  193. print_settings["retraction_enable"] = global_stack.getProperty("retraction_enable", "value")
  194. # Prime tower settings
  195. print_settings["prime_tower_enable"] = global_stack.getProperty("prime_tower_enable", "value")
  196. # Infill settings
  197. print_settings["infill_sparse_density"] = global_stack.getProperty("infill_sparse_density", "value")
  198. print_settings["infill_pattern"] = global_stack.getProperty("infill_pattern", "value")
  199. print_settings["gradual_infill_steps"] = global_stack.getProperty("gradual_infill_steps", "value")
  200. print_settings["print_sequence"] = global_stack.getProperty("print_sequence", "value")
  201. data["print_settings"] = print_settings
  202. # Send the name of the output device type that is used.
  203. data["output_to"] = type(output_device).__name__
  204. # Convert data to bytes
  205. binary_data = json.dumps(data).encode("utf-8")
  206. # Send slice info non-blocking
  207. network_manager = self._application.getHttpRequestManager()
  208. network_manager.post(self.info_url, data = binary_data,
  209. callback = self._onRequestFinished, error_callback = self._onRequestError)
  210. except Exception:
  211. # We really can't afford to have a mistake here, as this would break the sending of g-code to a device
  212. # (Either saving or directly to a printer). The functionality of the slice data is not *that* important.
  213. Logger.logException("e", "Exception raised while sending slice info.") # But we should be notified about these problems of course.
  214. def _onRequestFinished(self, reply: "QNetworkReply") -> None:
  215. status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
  216. if status_code == 200:
  217. Logger.log("i", "SliceInfo sent successfully")
  218. return
  219. data = reply.readAll().data().decode("utf-8")
  220. Logger.log("e", "SliceInfo request failed, status code %s, data: %s", status_code, data)
  221. def _onRequestError(self, reply: "QNetworkReply", error: "QNetworkReply.NetworkError") -> None:
  222. Logger.log("e", "Got error for SliceInfo request: %s", reply.errorString())