UM3OutputDevicePlugin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
  4. from UM.Logger import Logger
  5. from UM.Application import Application
  6. from UM.Signal import Signal, signalemitter
  7. from UM.Preferences import Preferences
  8. from UM.Version import Version
  9. from . import ClusterUM3OutputDevice, LegacyUM3OutputDevice
  10. from PyQt5.QtNetwork import QNetworkRequest, QNetworkAccessManager
  11. from PyQt5.QtCore import QUrl
  12. from zeroconf import Zeroconf, ServiceBrowser, ServiceStateChange, ServiceInfo
  13. from queue import Queue
  14. from threading import Event, Thread
  15. from time import time
  16. import json
  17. ## This plugin handles the connection detection & creation of output device objects for the UM3 printer.
  18. # Zero-Conf is used to detect printers, which are saved in a dict.
  19. # If we discover a printer that has the same key as the active machine instance a connection is made.
  20. @signalemitter
  21. class UM3OutputDevicePlugin(OutputDevicePlugin):
  22. addDeviceSignal = Signal()
  23. removeDeviceSignal = Signal()
  24. discoveredDevicesChanged = Signal()
  25. def __init__(self):
  26. super().__init__()
  27. self._zero_conf = None
  28. self._zero_conf_browser = None
  29. # Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  30. self.addDeviceSignal.connect(self._onAddDevice)
  31. self.removeDeviceSignal.connect(self._onRemoveDevice)
  32. Application.getInstance().globalContainerStackChanged.connect(self.reCheckConnections)
  33. self._discovered_devices = {}
  34. self._network_manager = QNetworkAccessManager()
  35. self._network_manager.finished.connect(self._onNetworkRequestFinished)
  36. self._min_cluster_version = Version("4.0.0")
  37. self._api_version = "1"
  38. self._api_prefix = "/api/v" + self._api_version + "/"
  39. self._cluster_api_version = "1"
  40. self._cluster_api_prefix = "/cluster-api/v" + self._cluster_api_version + "/"
  41. # Get list of manual instances from preferences
  42. self._preferences = Preferences.getInstance()
  43. self._preferences.addPreference("um3networkprinting/manual_instances",
  44. "") # A comma-separated list of ip adresses or hostnames
  45. self._manual_instances = self._preferences.getValue("um3networkprinting/manual_instances").split(",")
  46. # The zero-conf service changed requests are handled in a separate thread, so we can re-schedule the requests
  47. # which fail to get detailed service info.
  48. # Any new or re-scheduled requests will be appended to the request queue, and the handling thread will pick
  49. # them up and process them.
  50. self._service_changed_request_queue = Queue()
  51. self._service_changed_request_event = Event()
  52. self._service_changed_request_thread = Thread(target=self._handleOnServiceChangedRequests, daemon=True)
  53. self._service_changed_request_thread.start()
  54. def getDiscoveredDevices(self):
  55. return self._discovered_devices
  56. ## Start looking for devices on network.
  57. def start(self):
  58. self.startDiscovery()
  59. def startDiscovery(self):
  60. self.stop()
  61. if self._zero_conf_browser:
  62. self._zero_conf_browser.cancel()
  63. self._zero_conf_browser = None # Force the old ServiceBrowser to be destroyed.
  64. for instance_name in list(self._discovered_devices):
  65. self._onRemoveDevice(instance_name)
  66. self._zero_conf = Zeroconf()
  67. self._zero_conf_browser = ServiceBrowser(self._zero_conf, u'_ultimaker._tcp.local.',
  68. [self._appendServiceChangedRequest])
  69. # Look for manual instances from preference
  70. for address in self._manual_instances:
  71. if address:
  72. self.addManualDevice(address)
  73. def reCheckConnections(self):
  74. active_machine = Application.getInstance().getGlobalContainerStack()
  75. if not active_machine:
  76. return
  77. um_network_key = active_machine.getMetaDataEntry("um_network_key")
  78. for key in self._discovered_devices:
  79. if key == um_network_key:
  80. if not self._discovered_devices[key].isConnected():
  81. Logger.log("d", "Attempting to connect with [%s]" % key)
  82. self._discovered_devices[key].connect()
  83. self._discovered_devices[key].connectionStateChanged.connect(self._onDeviceConnectionStateChanged)
  84. else:
  85. self._onDeviceConnectionStateChanged(key)
  86. else:
  87. if self._discovered_devices[key].isConnected():
  88. Logger.log("d", "Attempting to close connection with [%s]" % key)
  89. self._discovered_devices[key].close()
  90. self._discovered_devices[key].connectionStateChanged.disconnect(self._onDeviceConnectionStateChanged)
  91. def _onDeviceConnectionStateChanged(self, key):
  92. if key not in self._discovered_devices:
  93. return
  94. if self._discovered_devices[key].isConnected():
  95. # Sometimes the status changes after changing the global container and maybe the device doesn't belong to this machine
  96. um_network_key = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("um_network_key")
  97. if key == um_network_key:
  98. self.getOutputDeviceManager().addOutputDevice(self._discovered_devices[key])
  99. else:
  100. self.getOutputDeviceManager().removeOutputDevice(key)
  101. def stop(self):
  102. if self._zero_conf is not None:
  103. Logger.log("d", "zeroconf close...")
  104. self._zero_conf.close()
  105. def removeManualDevice(self, key, address = None):
  106. if key in self._discovered_devices:
  107. if not address:
  108. address = self._discovered_devices[key].ipAddress
  109. self._onRemoveDevice(key)
  110. if address in self._manual_instances:
  111. self._manual_instances.remove(address)
  112. self._preferences.setValue("um3networkprinting/manual_instances", ",".join(self._manual_instances))
  113. def addManualDevice(self, address):
  114. if address not in self._manual_instances:
  115. self._manual_instances.append(address)
  116. self._preferences.setValue("um3networkprinting/manual_instances", ",".join(self._manual_instances))
  117. instance_name = "manual:%s" % address
  118. properties = {
  119. b"name": address.encode("utf-8"),
  120. b"address": address.encode("utf-8"),
  121. b"manual": b"true",
  122. b"incomplete": b"true"
  123. }
  124. if instance_name not in self._discovered_devices:
  125. # Add a preliminary printer instance
  126. self._onAddDevice(instance_name, address, properties)
  127. self._checkManualDevice(address)
  128. def _checkManualDevice(self, address):
  129. # Check if a UM3 family device exists at this address.
  130. # If a printer responds, it will replace the preliminary printer created above
  131. # origin=manual is for tracking back the origin of the call
  132. url = QUrl("http://" + address + self._api_prefix + "system")
  133. name_request = QNetworkRequest(url)
  134. self._network_manager.get(name_request)
  135. def _onNetworkRequestFinished(self, reply):
  136. reply_url = reply.url().toString()
  137. if "system" in reply_url:
  138. if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
  139. # Something went wrong with checking the firmware version!
  140. return
  141. try:
  142. system_info = json.loads(bytes(reply.readAll()).decode("utf-8"))
  143. except:
  144. Logger.log("e", "Something went wrong converting the JSON.")
  145. return
  146. address = reply.url().host()
  147. has_cluster_capable_firmware = Version(system_info["firmware"]) > self._min_cluster_version
  148. instance_name = "manual:%s" % address
  149. properties = {
  150. b"name": system_info["name"].encode("utf-8"),
  151. b"address": address.encode("utf-8"),
  152. b"firmware_version": system_info["firmware"].encode("utf-8"),
  153. b"manual": b"true",
  154. b"machine": system_info["variant"].encode("utf-8")
  155. }
  156. if has_cluster_capable_firmware:
  157. # Cluster needs an additional request, before it's completed.
  158. properties[b"incomplete"] = b"true"
  159. # Check if the device is still in the list & re-add it with the updated
  160. # information.
  161. if instance_name in self._discovered_devices:
  162. self._onRemoveDevice(instance_name)
  163. self._onAddDevice(instance_name, address, properties)
  164. if has_cluster_capable_firmware:
  165. # We need to request more info in order to figure out the size of the cluster.
  166. cluster_url = QUrl("http://" + address + self._cluster_api_prefix + "printers/")
  167. cluster_request = QNetworkRequest(cluster_url)
  168. self._network_manager.get(cluster_request)
  169. elif "printers" in reply_url:
  170. if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
  171. # Something went wrong with checking the amount of printers the cluster has!
  172. return
  173. # So we confirmed that the device is in fact a cluster printer, and we should now know how big it is.
  174. try:
  175. cluster_printers_list = json.loads(bytes(reply.readAll()).decode("utf-8"))
  176. except:
  177. Logger.log("e", "Something went wrong converting the JSON.")
  178. return
  179. address = reply.url().host()
  180. instance_name = "manual:%s" % address
  181. if instance_name in self._discovered_devices:
  182. device = self._discovered_devices[instance_name]
  183. properties = device.getProperties().copy()
  184. if b"incomplete" in properties:
  185. del properties[b"incomplete"]
  186. properties[b'cluster_size'] = len(cluster_printers_list)
  187. self._onRemoveDevice(instance_name)
  188. self._onAddDevice(instance_name, address, properties)
  189. def _onRemoveDevice(self, device_id):
  190. device = self._discovered_devices.pop(device_id, None)
  191. if device:
  192. if device.isConnected():
  193. device.disconnect()
  194. try:
  195. device.connectionStateChanged.disconnect(self._onDeviceConnectionStateChanged)
  196. except TypeError:
  197. # Disconnect already happened.
  198. pass
  199. self.discoveredDevicesChanged.emit()
  200. def _onAddDevice(self, name, address, properties):
  201. # Check what kind of device we need to add; Depending on the firmware we either add a "Connect"/"Cluster"
  202. # or "Legacy" UM3 device.
  203. cluster_size = int(properties.get(b"cluster_size", -1))
  204. if cluster_size >= 0:
  205. device = ClusterUM3OutputDevice.ClusterUM3OutputDevice(name, address, properties)
  206. else:
  207. device = LegacyUM3OutputDevice.LegacyUM3OutputDevice(name, address, properties)
  208. self._discovered_devices[device.getId()] = device
  209. self.discoveredDevicesChanged.emit()
  210. global_container_stack = Application.getInstance().getGlobalContainerStack()
  211. if global_container_stack and device.getId() == global_container_stack.getMetaDataEntry("um_network_key"):
  212. device.connect()
  213. device.connectionStateChanged.connect(self._onDeviceConnectionStateChanged)
  214. ## Appends a service changed request so later the handling thread will pick it up and processes it.
  215. def _appendServiceChangedRequest(self, zeroconf, service_type, name, state_change):
  216. # append the request and set the event so the event handling thread can pick it up
  217. item = (zeroconf, service_type, name, state_change)
  218. self._service_changed_request_queue.put(item)
  219. self._service_changed_request_event.set()
  220. def _handleOnServiceChangedRequests(self):
  221. while True:
  222. # Wait for the event to be set
  223. self._service_changed_request_event.wait(timeout = 5.0)
  224. # Stop if the application is shutting down
  225. if Application.getInstance().isShuttingDown():
  226. return
  227. self._service_changed_request_event.clear()
  228. # Handle all pending requests
  229. reschedule_requests = [] # A list of requests that have failed so later they will get re-scheduled
  230. while not self._service_changed_request_queue.empty():
  231. request = self._service_changed_request_queue.get()
  232. zeroconf, service_type, name, state_change = request
  233. try:
  234. result = self._onServiceChanged(zeroconf, service_type, name, state_change)
  235. if not result:
  236. reschedule_requests.append(request)
  237. except Exception:
  238. Logger.logException("e", "Failed to get service info for [%s] [%s], the request will be rescheduled",
  239. service_type, name)
  240. reschedule_requests.append(request)
  241. # Re-schedule the failed requests if any
  242. if reschedule_requests:
  243. for request in reschedule_requests:
  244. self._service_changed_request_queue.put(request)
  245. ## Handler for zeroConf detection.
  246. # Return True or False indicating if the process succeeded.
  247. # Note that this function can take over 3 seconds to complete. Be carefull calling it from the main thread.
  248. def _onServiceChanged(self, zero_conf, service_type, name, state_change):
  249. if state_change == ServiceStateChange.Added:
  250. Logger.log("d", "Bonjour service added: %s" % name)
  251. # First try getting info from zero-conf cache
  252. info = ServiceInfo(service_type, name, properties={})
  253. for record in zero_conf.cache.entries_with_name(name.lower()):
  254. info.update_record(zero_conf, time(), record)
  255. for record in zero_conf.cache.entries_with_name(info.server):
  256. info.update_record(zero_conf, time(), record)
  257. if info.address:
  258. break
  259. # Request more data if info is not complete
  260. if not info.address:
  261. Logger.log("d", "Trying to get address of %s", name)
  262. info = zero_conf.get_service_info(service_type, name)
  263. if info:
  264. type_of_device = info.properties.get(b"type", None)
  265. if type_of_device:
  266. if type_of_device == b"printer":
  267. address = '.'.join(map(lambda n: str(n), info.address))
  268. self.addDeviceSignal.emit(str(name), address, info.properties)
  269. else:
  270. Logger.log("w",
  271. "The type of the found device is '%s', not 'printer'! Ignoring.." % type_of_device)
  272. else:
  273. Logger.log("w", "Could not get information about %s" % name)
  274. return False
  275. elif state_change == ServiceStateChange.Removed:
  276. Logger.log("d", "Bonjour service removed: %s" % name)
  277. self.removeDeviceSignal.emit(str(name))
  278. return True