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 cura.CuraApplication import CuraApplication
  4. from UM.Extension import Extension
  5. from UM.Application import Application
  6. from UM.Preferences import Preferences
  7. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Message import Message
  10. from UM.i18n import i18nCatalog
  11. from UM.Logger import Logger
  12. from UM.Platform import Platform
  13. from UM.Qt.Duration import DurationFormat
  14. from UM.Job import Job
  15. import platform
  16. import math
  17. import urllib.request
  18. import urllib.parse
  19. import ssl
  20. import hashlib
  21. import json
  22. catalog = i18nCatalog("cura")
  23. class SliceInfoJob(Job):
  24. data = None
  25. url = None
  26. def __init__(self, url, data):
  27. super().__init__()
  28. self.url = url
  29. self.data = data
  30. def run(self):
  31. if not self.url or not self.data:
  32. Logger.log("e", "URL or DATA for sending slice info was not set!")
  33. return
  34. # Submit data
  35. kwoptions = {"data" : self.data,
  36. "timeout" : 5
  37. }
  38. if Platform.isOSX():
  39. kwoptions["context"] = ssl._create_unverified_context()
  40. Logger.log("d", "Sending anonymous slice info to [%s]...", self.url)
  41. try:
  42. f = urllib.request.urlopen(self.url, **kwoptions)
  43. Logger.log("i", "Sent anonymous slice info.")
  44. f.close()
  45. except urllib.error.HTTPError as http_exception:
  46. Logger.log("e", "An HTTP error occurred while trying to send slice information: %s" % http_exception)
  47. except Exception as e: # We don't want any exception to cause problems
  48. Logger.log("e", "An exception occurred while trying to send slice information: %s" % e)
  49. ## This Extension runs in the background and sends several bits of information to the Ultimaker servers.
  50. # The data is only sent when the user in question gave permission to do so. All data is anonymous and
  51. # no model files are being sent (Just a SHA256 hash of the model).
  52. class SliceInfo(Extension):
  53. info_url = "https://stats.youmagine.com/curastats/slice"
  54. def __init__(self):
  55. super().__init__()
  56. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self._onWriteStarted)
  57. Preferences.getInstance().addPreference("info/send_slice_info", True)
  58. Preferences.getInstance().addPreference("info/asked_send_slice_info", False)
  59. if not Preferences.getInstance().getValue("info/asked_send_slice_info"):
  60. self.send_slice_info_message = Message(catalog.i18nc("@info", "Cura collects anonymised slicing statistics. You can disable this in preferences"), lifetime = 0, dismissable = False)
  61. self.send_slice_info_message.addAction("Dismiss", catalog.i18nc("@action:button", "Dismiss"), None, "")
  62. self.send_slice_info_message.actionTriggered.connect(self.messageActionTriggered)
  63. self.send_slice_info_message.show()
  64. def messageActionTriggered(self, message_id, action_id):
  65. self.send_slice_info_message.hide()
  66. Preferences.getInstance().setValue("info/asked_send_slice_info", True)
  67. def _onWriteStarted(self, output_device):
  68. try:
  69. if not Preferences.getInstance().getValue("info/send_slice_info"):
  70. Logger.log("d", "'info/send_slice_info' is turned off.")
  71. return # Do nothing, user does not want to send data
  72. # Listing all files placed on the buildplate
  73. modelhashes = []
  74. for node in DepthFirstIterator(CuraApplication.getInstance().getController().getScene().getRoot()):
  75. if type(node) is not SceneNode or not node.getMeshData():
  76. continue
  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.