SliceInfo.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from typing import Any
  4. from cura.CuraApplication import CuraApplication
  5. from UM.Extension import Extension
  6. from UM.Application import Application
  7. from UM.Preferences import Preferences
  8. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  9. from UM.Scene.SceneNode import SceneNode
  10. from UM.Message import Message
  11. from UM.i18n import i18nCatalog
  12. from UM.Logger import Logger
  13. from UM.Platform import Platform
  14. from UM.Qt.Duration import DurationFormat
  15. from UM.Job import Job
  16. import platform
  17. import math
  18. import urllib.request
  19. import urllib.parse
  20. import ssl
  21. import hashlib
  22. import json
  23. catalog = i18nCatalog("cura")
  24. class SliceInfoJob(Job):
  25. data = None # type: Any
  26. url = None # type: str
  27. def __init__(self, url, data):
  28. super().__init__()
  29. self.url = url
  30. self.data = data
  31. def run(self):
  32. if not self.url or not self.data:
  33. Logger.log("e", "URL or DATA for sending slice info was not set!")
  34. return
  35. # Submit data
  36. kwoptions = {"data" : self.data,
  37. "timeout" : 5
  38. }
  39. if Platform.isOSX():
  40. kwoptions["context"] = ssl._create_unverified_context()
  41. Logger.log("d", "Sending anonymous slice info to [%s]...", self.url)
  42. try:
  43. f = urllib.request.urlopen(self.url, **kwoptions)
  44. Logger.log("i", "Sent anonymous slice info.")
  45. f.close()
  46. except urllib.error.HTTPError as http_exception:
  47. Logger.log("e", "An HTTP error occurred while trying to send slice information: %s" % http_exception)
  48. except Exception as e: # We don't want any exception to cause problems
  49. Logger.log("e", "An exception occurred while trying to send slice information: %s" % e)
  50. ## This Extension runs in the background and sends several bits of information to the Ultimaker servers.
  51. # The data is only sent when the user in question gave permission to do so. All data is anonymous and
  52. # no model files are being sent (Just a SHA256 hash of the model).
  53. class SliceInfo(Extension):
  54. info_url = "https://stats.youmagine.com/curastats/slice"
  55. def __init__(self):
  56. super().__init__()
  57. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self._onWriteStarted)
  58. Preferences.getInstance().addPreference("info/send_slice_info", True)
  59. Preferences.getInstance().addPreference("info/asked_send_slice_info", False)
  60. if not Preferences.getInstance().getValue("info/asked_send_slice_info"):
  61. self.send_slice_info_message = Message(catalog.i18nc("@info", "Cura collects anonymised slicing statistics. You can disable this in preferences"), lifetime = 0, dismissable = False)
  62. self.send_slice_info_message.addAction("Dismiss", catalog.i18nc("@action:button", "Dismiss"), None, "")
  63. self.send_slice_info_message.actionTriggered.connect(self.messageActionTriggered)
  64. self.send_slice_info_message.show()
  65. def messageActionTriggered(self, message_id, action_id):
  66. self.send_slice_info_message.hide()
  67. Preferences.getInstance().setValue("info/asked_send_slice_info", True)
  68. def _onWriteStarted(self, output_device):
  69. try:
  70. if not Preferences.getInstance().getValue("info/send_slice_info"):
  71. Logger.log("d", "'info/send_slice_info' is turned off.")
  72. return # Do nothing, user does not want to send data
  73. # Listing all files placed on the buildplate
  74. modelhashes = []
  75. for node in DepthFirstIterator(CuraApplication.getInstance().getController().getScene().getRoot()):
  76. if node.callDecoration("isSliceable"):
  77. modelhashes.append(node.getMeshData().getHash())
  78. # Creating md5sums and formatting them as discussed on JIRA
  79. modelhash_formatted = ",".join(modelhashes)
  80. global_container_stack = Application.getInstance().getGlobalContainerStack()
  81. # Get total material used (in mm^3)
  82. print_information = Application.getInstance().getPrintInformation()
  83. material_radius = 0.5 * global_container_stack.getProperty("material_diameter", "value")
  84. # Send material per extruder
  85. material_used = [str(math.pi * material_radius * material_radius * material_length) for material_length in print_information.materialLengths]
  86. material_used = ",".join(material_used)
  87. containers = { "": global_container_stack.serialize() }
  88. for container in global_container_stack.getContainers():
  89. container_id = container.getId()
  90. try:
  91. container_serialized = container.serialize()
  92. except NotImplementedError:
  93. Logger.log("w", "Container %s could not be serialized!", container_id)
  94. continue
  95. if container_serialized:
  96. containers[container_id] = container_serialized
  97. else:
  98. Logger.log("i", "No data found in %s to be serialized!", container_id)
  99. # Bundle the collected data
  100. submitted_data = {
  101. "processor": platform.processor(),
  102. "machine": platform.machine(),
  103. "platform": platform.platform(),
  104. "settings": json.dumps(containers), # bundle of containers with their serialized contents
  105. "version": Application.getInstance().getVersion(),
  106. "modelhash": modelhash_formatted,
  107. "printtime": print_information.currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601),
  108. "filament": material_used,
  109. "language": Preferences.getInstance().getValue("general/language"),
  110. }
  111. # Convert data to bytes
  112. submitted_data = urllib.parse.urlencode(submitted_data)
  113. binary_data = submitted_data.encode("utf-8")
  114. # Sending slice info non-blocking
  115. reportJob = SliceInfoJob(self.info_url, binary_data)
  116. reportJob.start()
  117. except Exception as e:
  118. # We really can't afford to have a mistake here, as this would break the sending of g-code to a device
  119. # (Either saving or directly to a printer). The functionality of the slice data is not *that* important.
  120. Logger.log("e", "Exception raised while sending slice info: %s" %(repr(e))) # But we should be notified about these problems of course.