SliceInfo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 PyQt5.QtCore import pyqtSlot, QObject
  8. from UM.Extension import Extension
  9. from UM.Application import Application
  10. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  11. from UM.Message import Message
  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 typing import cast, Optional
  17. from .SliceInfoJob import SliceInfoJob
  18. catalog = i18nCatalog("cura")
  19. ## This Extension runs in the background and sends several bits of information to the Ultimaker servers.
  20. # The data is only sent when the user in question gave permission to do so. All data is anonymous and
  21. # no model files are being sent (Just a SHA256 hash of the model).
  22. class SliceInfo(QObject, Extension):
  23. info_url = "https://stats.ultimaker.com/api/cura"
  24. def __init__(self, parent = None):
  25. QObject.__init__(self, parent)
  26. Extension.__init__(self)
  27. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self._onWriteStarted)
  28. Application.getInstance().getPreferences().addPreference("info/send_slice_info", True)
  29. Application.getInstance().getPreferences().addPreference("info/asked_send_slice_info", False)
  30. self._more_info_dialog = None
  31. self._example_data_content = None
  32. if not Application.getInstance().getPreferences().getValue("info/asked_send_slice_info"):
  33. self.send_slice_info_message = Message(catalog.i18nc("@info", "Cura collects anonymized usage statistics."),
  34. lifetime = 0,
  35. dismissable = False,
  36. title = catalog.i18nc("@info:title", "Collecting Data"))
  37. self.send_slice_info_message.addAction("MoreInfo", name = catalog.i18nc("@action:button", "More info"), icon = None,
  38. description = catalog.i18nc("@action:tooltip", "See more information on what data Cura sends."), button_style = Message.ActionButtonStyle.LINK)
  39. self.send_slice_info_message.addAction("Dismiss", name = catalog.i18nc("@action:button", "Allow"), icon = None,
  40. description = catalog.i18nc("@action:tooltip", "Allow Cura to send anonymized usage statistics to help prioritize future improvements to Cura. Some of your preferences and settings are sent, the Cura version and a hash of the models you're slicing."))
  41. self.send_slice_info_message.actionTriggered.connect(self.messageActionTriggered)
  42. self.send_slice_info_message.show()
  43. Application.getInstance().initializationFinished.connect(self._onAppInitialized)
  44. def _onAppInitialized(self):
  45. if self._more_info_dialog is None:
  46. self._more_info_dialog = self._createDialog("MoreInfoWindow.qml")
  47. ## Perform action based on user input.
  48. # Note that clicking "Disable" won't actually disable the data sending, but rather take the user to preferences where they can disable it.
  49. def messageActionTriggered(self, message_id, action_id):
  50. Application.getInstance().getPreferences().setValue("info/asked_send_slice_info", True)
  51. if action_id == "MoreInfo":
  52. self.showMoreInfoDialog()
  53. self.send_slice_info_message.hide()
  54. def showMoreInfoDialog(self):
  55. if self._more_info_dialog is None:
  56. self._more_info_dialog = self._createDialog("MoreInfoWindow.qml")
  57. self._more_info_dialog.open()
  58. def _createDialog(self, qml_name):
  59. Logger.log("d", "Creating dialog [%s]", qml_name)
  60. file_path = os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), qml_name)
  61. dialog = Application.getInstance().createQmlComponent(file_path, {"manager": self})
  62. return dialog
  63. @pyqtSlot(result = str)
  64. def getExampleData(self) -> Optional[str]:
  65. if self._example_data_content is None:
  66. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  67. if not plugin_path:
  68. Logger.log("e", "Could not get plugin path!", self.getPluginId())
  69. return None
  70. file_path = os.path.join(plugin_path, "example_data.json")
  71. if file_path:
  72. with open(file_path, "r", encoding = "utf-8") as f:
  73. self._example_data_content = f.read()
  74. return self._example_data_content
  75. @pyqtSlot(bool)
  76. def setSendSliceInfo(self, enabled: bool):
  77. Application.getInstance().getPreferences().setValue("info/send_slice_info", enabled)
  78. def _getUserModifiedSettingKeys(self) -> list:
  79. application = Application.getInstance()
  80. machine_manager = application.getMachineManager()
  81. global_stack = machine_manager.activeMachine
  82. user_modified_setting_keys = set()
  83. for stack in [global_stack] + list(global_stack.extruders.values()):
  84. # Get all settings in user_changes and quality_changes
  85. all_keys = stack.userChanges.getAllKeys() | stack.qualityChanges.getAllKeys()
  86. user_modified_setting_keys |= all_keys
  87. return list(sorted(user_modified_setting_keys))
  88. def _onWriteStarted(self, output_device):
  89. try:
  90. if not Application.getInstance().getPreferences().getValue("info/send_slice_info"):
  91. Logger.log("d", "'info/send_slice_info' is turned off.")
  92. return # Do nothing, user does not want to send data
  93. application = Application.getInstance()
  94. machine_manager = application.getMachineManager()
  95. print_information = application.getPrintInformation()
  96. global_stack = machine_manager.activeMachine
  97. data = dict() # The data that we're going to submit.
  98. data["time_stamp"] = time.time()
  99. data["schema_version"] = 0
  100. data["cura_version"] = application.getVersion()
  101. active_mode = Application.getInstance().getPreferences().getValue("cura/active_mode")
  102. if active_mode == 0:
  103. data["active_mode"] = "recommended"
  104. else:
  105. data["active_mode"] = "custom"
  106. definition_changes = global_stack.definitionChanges
  107. machine_settings_changed_by_user = False
  108. if definition_changes.getId() != "empty":
  109. # Now a definition_changes container will always be created for a stack,
  110. # so we also need to check if there is any instance in the definition_changes container
  111. if definition_changes.getAllKeys():
  112. machine_settings_changed_by_user = True
  113. data["machine_settings_changed_by_user"] = machine_settings_changed_by_user
  114. data["language"] = Application.getInstance().getPreferences().getValue("general/language")
  115. data["os"] = {"type": platform.system(), "version": platform.version()}
  116. data["active_machine"] = {"definition_id": global_stack.definition.getId(),
  117. "manufacturer": global_stack.definition.getMetaDataEntry("manufacturer", "")}
  118. # add extruder specific data to slice info
  119. data["extruders"] = []
  120. extruders = list(global_stack.extruders.values())
  121. extruders = sorted(extruders, key = lambda extruder: extruder.getMetaDataEntry("position"))
  122. for extruder in extruders:
  123. extruder_dict = dict()
  124. extruder_dict["active"] = machine_manager.activeStack == extruder
  125. extruder_dict["material"] = {"GUID": extruder.material.getMetaData().get("GUID", ""),
  126. "type": extruder.material.getMetaData().get("material", ""),
  127. "brand": extruder.material.getMetaData().get("brand", "")
  128. }
  129. extruder_position = int(extruder.getMetaDataEntry("position", "0"))
  130. if len(print_information.materialLengths) > extruder_position:
  131. extruder_dict["material_used"] = print_information.materialLengths[extruder_position]
  132. extruder_dict["variant"] = extruder.variant.getName()
  133. extruder_dict["nozzle_size"] = extruder.getProperty("machine_nozzle_size", "value")
  134. extruder_settings = dict()
  135. extruder_settings["wall_line_count"] = extruder.getProperty("wall_line_count", "value")
  136. extruder_settings["retraction_enable"] = extruder.getProperty("retraction_enable", "value")
  137. extruder_settings["infill_sparse_density"] = extruder.getProperty("infill_sparse_density", "value")
  138. extruder_settings["infill_pattern"] = extruder.getProperty("infill_pattern", "value")
  139. extruder_settings["gradual_infill_steps"] = extruder.getProperty("gradual_infill_steps", "value")
  140. extruder_settings["default_material_print_temperature"] = extruder.getProperty("default_material_print_temperature", "value")
  141. extruder_settings["material_print_temperature"] = extruder.getProperty("material_print_temperature", "value")
  142. extruder_dict["extruder_settings"] = extruder_settings
  143. data["extruders"].append(extruder_dict)
  144. data["quality_profile"] = global_stack.quality.getMetaData().get("quality_type")
  145. data["user_modified_setting_keys"] = self._getUserModifiedSettingKeys()
  146. data["models"] = []
  147. # Listing all files placed on the build plate
  148. for node in DepthFirstIterator(application.getController().getScene().getRoot()):
  149. if node.callDecoration("isSliceable"):
  150. model = dict()
  151. model["hash"] = node.getMeshData().getHash()
  152. bounding_box = node.getBoundingBox()
  153. model["bounding_box"] = {"minimum": {"x": bounding_box.minimum.x,
  154. "y": bounding_box.minimum.y,
  155. "z": bounding_box.minimum.z},
  156. "maximum": {"x": bounding_box.maximum.x,
  157. "y": bounding_box.maximum.y,
  158. "z": bounding_box.maximum.z}}
  159. model["transformation"] = {"data": str(node.getWorldTransformation().getData()).replace("\n", "")}
  160. extruder_position = node.callDecoration("getActiveExtruderPosition")
  161. model["extruder"] = 0 if extruder_position is None else int(extruder_position)
  162. model_settings = dict()
  163. model_stack = node.callDecoration("getStack")
  164. if model_stack:
  165. model_settings["support_enabled"] = model_stack.getProperty("support_enable", "value")
  166. model_settings["support_extruder_nr"] = int(model_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))
  167. # Mesh modifiers;
  168. model_settings["infill_mesh"] = model_stack.getProperty("infill_mesh", "value")
  169. model_settings["cutting_mesh"] = model_stack.getProperty("cutting_mesh", "value")
  170. model_settings["support_mesh"] = model_stack.getProperty("support_mesh", "value")
  171. model_settings["anti_overhang_mesh"] = model_stack.getProperty("anti_overhang_mesh", "value")
  172. model_settings["wall_line_count"] = model_stack.getProperty("wall_line_count", "value")
  173. model_settings["retraction_enable"] = model_stack.getProperty("retraction_enable", "value")
  174. # Infill settings
  175. model_settings["infill_sparse_density"] = model_stack.getProperty("infill_sparse_density", "value")
  176. model_settings["infill_pattern"] = model_stack.getProperty("infill_pattern", "value")
  177. model_settings["gradual_infill_steps"] = model_stack.getProperty("gradual_infill_steps", "value")
  178. model["model_settings"] = model_settings
  179. data["models"].append(model)
  180. print_times = print_information.printTimes()
  181. data["print_times"] = {"travel": int(print_times["travel"].getDisplayString(DurationFormat.Format.Seconds)),
  182. "support": int(print_times["support"].getDisplayString(DurationFormat.Format.Seconds)),
  183. "infill": int(print_times["infill"].getDisplayString(DurationFormat.Format.Seconds)),
  184. "total": int(print_information.currentPrintTime.getDisplayString(DurationFormat.Format.Seconds))}
  185. print_settings = dict()
  186. print_settings["layer_height"] = global_stack.getProperty("layer_height", "value")
  187. # Support settings
  188. print_settings["support_enabled"] = global_stack.getProperty("support_enable", "value")
  189. print_settings["support_extruder_nr"] = int(global_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))
  190. # Platform adhesion settings
  191. print_settings["adhesion_type"] = global_stack.getProperty("adhesion_type", "value")
  192. # Shell settings
  193. print_settings["wall_line_count"] = global_stack.getProperty("wall_line_count", "value")
  194. print_settings["retraction_enable"] = global_stack.getProperty("retraction_enable", "value")
  195. # Prime tower settings
  196. print_settings["prime_tower_enable"] = global_stack.getProperty("prime_tower_enable", "value")
  197. # Infill settings
  198. print_settings["infill_sparse_density"] = global_stack.getProperty("infill_sparse_density", "value")
  199. print_settings["infill_pattern"] = global_stack.getProperty("infill_pattern", "value")
  200. print_settings["gradual_infill_steps"] = global_stack.getProperty("gradual_infill_steps", "value")
  201. print_settings["print_sequence"] = global_stack.getProperty("print_sequence", "value")
  202. data["print_settings"] = print_settings
  203. # Send the name of the output device type that is used.
  204. data["output_to"] = type(output_device).__name__
  205. # Convert data to bytes
  206. binary_data = json.dumps(data).encode("utf-8")
  207. # Sending slice info non-blocking
  208. reportJob = SliceInfoJob(self.info_url, binary_data)
  209. reportJob.start()
  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.