NetworkedPrinterOutputDevice.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.FileHandler.FileHandler import FileHandler #For typing.
  4. from UM.Logger import Logger
  5. from UM.Scene.SceneNode import SceneNode #For typing.
  6. from cura.API import Account
  7. from cura.CuraApplication import CuraApplication
  8. from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState, ConnectionType
  9. from PyQt5.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager, QNetworkReply, QAuthenticator
  10. from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QUrl, QCoreApplication
  11. from time import time
  12. from typing import Callable, Dict, List, Optional, Union
  13. from enum import IntEnum
  14. import os # To get the username
  15. import gzip
  16. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  17. class AuthState(IntEnum):
  18. NotAuthenticated = 1
  19. AuthenticationRequested = 2
  20. Authenticated = 3
  21. AuthenticationDenied = 4
  22. AuthenticationReceived = 5
  23. class NetworkedPrinterOutputDevice(PrinterOutputDevice):
  24. authenticationStateChanged = pyqtSignal()
  25. def __init__(self, device_id, address: str, properties: Dict[bytes, bytes], connection_type: ConnectionType = ConnectionType.NetworkConnection, parent: Optional[QObject] = None) -> None:
  26. super().__init__(device_id = device_id, connection_type = connection_type, parent = parent)
  27. self._manager = None # type: Optional[QNetworkAccessManager]
  28. self._timeout_time = 10 # After how many seconds of no response should a timeout occur?
  29. self._last_response_time = None # type: Optional[float]
  30. self._last_request_time = None # type: Optional[float]
  31. self._api_prefix = ""
  32. self._address = address
  33. self._properties = properties
  34. self._user_agent = "%s/%s " % (CuraApplication.getInstance().getApplicationName(),
  35. CuraApplication.getInstance().getVersion())
  36. self._onFinishedCallbacks = {} # type: Dict[str, Callable[[QNetworkReply], None]]
  37. self._authentication_state = AuthState.NotAuthenticated
  38. # QHttpMultiPart objects need to be kept alive and not garbage collected during the
  39. # HTTP which uses them. We hold references to these QHttpMultiPart objects here.
  40. self._kept_alive_multiparts = {} # type: Dict[QNetworkReply, QHttpMultiPart]
  41. self._sending_gcode = False
  42. self._compressing_gcode = False
  43. self._gcode = [] # type: List[str]
  44. self._connection_state_before_timeout = None # type: Optional[ConnectionState]
  45. def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False,
  46. file_handler: Optional["FileHandler"] = None, filter_by_machine: bool = False, **kwargs) -> None:
  47. raise NotImplementedError("requestWrite needs to be implemented")
  48. def setAuthenticationState(self, authentication_state: AuthState) -> None:
  49. if self._authentication_state != authentication_state:
  50. self._authentication_state = authentication_state
  51. self.authenticationStateChanged.emit()
  52. @pyqtProperty(int, notify = authenticationStateChanged)
  53. def authenticationState(self) -> AuthState:
  54. return self._authentication_state
  55. def _compressDataAndNotifyQt(self, data_to_append: str) -> bytes:
  56. compressed_data = gzip.compress(data_to_append.encode("utf-8"))
  57. self._progress_message.setProgress(-1) # Tickle the message so that it's clear that it's still being used.
  58. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  59. # Pretend that this is a response, as zipping might take a bit of time.
  60. # If we don't do this, the device might trigger a timeout.
  61. self._last_response_time = time()
  62. return compressed_data
  63. def _compressGCode(self) -> Optional[bytes]:
  64. self._compressing_gcode = True
  65. max_chars_per_line = int(1024 * 1024 / 4) # 1/4 MB per line.
  66. """Mash the data into single string"""
  67. file_data_bytes_list = []
  68. batched_lines = []
  69. batched_lines_count = 0
  70. for line in self._gcode:
  71. if not self._compressing_gcode:
  72. self._progress_message.hide()
  73. # Stop trying to zip / send as abort was called.
  74. return None
  75. # if the gcode was read from a gcode file, self._gcode will be a list of all lines in that file.
  76. # Compressing line by line in this case is extremely slow, so we need to batch them.
  77. batched_lines.append(line)
  78. batched_lines_count += len(line)
  79. if batched_lines_count >= max_chars_per_line:
  80. file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines)))
  81. batched_lines = []
  82. batched_lines_count = 0
  83. # Don't miss the last batch (If any)
  84. if len(batched_lines) != 0:
  85. file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines)))
  86. self._compressing_gcode = False
  87. return b"".join(file_data_bytes_list)
  88. def _update(self) -> None:
  89. if self._last_response_time:
  90. time_since_last_response = time() - self._last_response_time
  91. else:
  92. time_since_last_response = 0
  93. if self._last_request_time:
  94. time_since_last_request = time() - self._last_request_time
  95. else:
  96. time_since_last_request = float("inf") # An irrelevantly large number of seconds
  97. if time_since_last_response > self._timeout_time >= time_since_last_request:
  98. # Go (or stay) into timeout.
  99. if self._connection_state_before_timeout is None:
  100. self._connection_state_before_timeout = self._connection_state
  101. self.setConnectionState(ConnectionState.Closed)
  102. elif self._connection_state == ConnectionState.Closed:
  103. # Go out of timeout.
  104. if self._connection_state_before_timeout is not None: # sanity check, but it should never be None here
  105. self.setConnectionState(self._connection_state_before_timeout)
  106. self._connection_state_before_timeout = None
  107. def _createEmptyRequest(self, target: str, content_type: Optional[str] = "application/json") -> QNetworkRequest:
  108. url = QUrl("http://" + self._address + self._api_prefix + target)
  109. request = QNetworkRequest(url)
  110. if content_type is not None:
  111. request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
  112. request.setHeader(QNetworkRequest.UserAgentHeader, self._user_agent)
  113. return request
  114. def createFormPart(self, content_header: str, data: bytes, content_type: Optional[str] = None) -> QHttpPart:
  115. """This method was only available privately before, but it was actually called from SendMaterialJob.py.
  116. We now have a public equivalent as well. We did not remove the private one as plugins might be using that.
  117. """
  118. return self._createFormPart(content_header, data, content_type)
  119. def _createFormPart(self, content_header: str, data: bytes, content_type: Optional[str] = None) -> QHttpPart:
  120. part = QHttpPart()
  121. if not content_header.startswith("form-data;"):
  122. content_header = "form-data; " + content_header
  123. part.setHeader(QNetworkRequest.ContentDispositionHeader, content_header)
  124. if content_type is not None:
  125. part.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
  126. part.setBody(data)
  127. return part
  128. def _getUserName(self) -> str:
  129. """Convenience function to get the username, either from the cloud or from the OS."""
  130. # check first if we are logged in with the Ultimaker Account
  131. account = CuraApplication.getInstance().getCuraAPI().account # type: Account
  132. if account and account.isLoggedIn:
  133. return account.userName
  134. # Otherwise get the username from the US
  135. # The code below was copied from the getpass module, as we try to use as little dependencies as possible.
  136. for name in ("LOGNAME", "USER", "LNAME", "USERNAME"):
  137. user = os.environ.get(name)
  138. if user:
  139. return user
  140. return "Unknown User" # Couldn't find out username.
  141. def _clearCachedMultiPart(self, reply: QNetworkReply) -> None:
  142. if reply in self._kept_alive_multiparts:
  143. del self._kept_alive_multiparts[reply]
  144. def _validateManager(self) -> None:
  145. if self._manager is None:
  146. self._createNetworkManager()
  147. assert (self._manager is not None)
  148. def put(self, url: str, data: Union[str, bytes], content_type: Optional[str] = "application/json",
  149. on_finished: Optional[Callable[[QNetworkReply], None]] = None,
  150. on_progress: Optional[Callable[[int, int], None]] = None) -> None:
  151. """Sends a put request to the given path.
  152. :param url: The path after the API prefix.
  153. :param data: The data to be sent in the body
  154. :param content_type: The content type of the body data.
  155. :param on_finished: The function to call when the response is received.
  156. :param on_progress: The function to call when the progress changes. Parameters are bytes_sent / bytes_total.
  157. """
  158. self._validateManager()
  159. request = self._createEmptyRequest(url, content_type = content_type)
  160. self._last_request_time = time()
  161. if not self._manager:
  162. Logger.log("e", "No network manager was created to execute the PUT call with.")
  163. return
  164. body = data if isinstance(data, bytes) else data.encode() # type: bytes
  165. reply = self._manager.put(request, body)
  166. self._registerOnFinishedCallback(reply, on_finished)
  167. if on_progress is not None:
  168. reply.uploadProgress.connect(on_progress)
  169. def delete(self, url: str, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
  170. """Sends a delete request to the given path.
  171. :param url: The path after the API prefix.
  172. :param on_finished: The function to be call when the response is received.
  173. """
  174. self._validateManager()
  175. request = self._createEmptyRequest(url)
  176. self._last_request_time = time()
  177. if not self._manager:
  178. Logger.log("e", "No network manager was created to execute the DELETE call with.")
  179. return
  180. reply = self._manager.deleteResource(request)
  181. self._registerOnFinishedCallback(reply, on_finished)
  182. def get(self, url: str, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
  183. """Sends a get request to the given path.
  184. :param url: The path after the API prefix.
  185. :param on_finished: The function to be call when the response is received.
  186. """
  187. self._validateManager()
  188. request = self._createEmptyRequest(url)
  189. self._last_request_time = time()
  190. if not self._manager:
  191. Logger.log("e", "No network manager was created to execute the GET call with.")
  192. return
  193. reply = self._manager.get(request)
  194. self._registerOnFinishedCallback(reply, on_finished)
  195. def post(self, url: str, data: Union[str, bytes],
  196. on_finished: Optional[Callable[[QNetworkReply], None]],
  197. on_progress: Optional[Callable[[int, int], None]] = None) -> None:
  198. """Sends a post request to the given path.
  199. :param url: The path after the API prefix.
  200. :param data: The data to be sent in the body
  201. :param on_finished: The function to call when the response is received.
  202. :param on_progress: The function to call when the progress changes. Parameters are bytes_sent / bytes_total.
  203. """
  204. self._validateManager()
  205. request = self._createEmptyRequest(url)
  206. self._last_request_time = time()
  207. if not self._manager:
  208. Logger.log("e", "Could not find manager.")
  209. return
  210. body = data if isinstance(data, bytes) else data.encode() # type: bytes
  211. reply = self._manager.post(request, body)
  212. if on_progress is not None:
  213. reply.uploadProgress.connect(on_progress)
  214. self._registerOnFinishedCallback(reply, on_finished)
  215. def postFormWithParts(self, target: str, parts: List[QHttpPart],
  216. on_finished: Optional[Callable[[QNetworkReply], None]],
  217. on_progress: Optional[Callable[[int, int], None]] = None) -> QNetworkReply:
  218. self._validateManager()
  219. request = self._createEmptyRequest(target, content_type=None)
  220. multi_post_part = QHttpMultiPart(QHttpMultiPart.FormDataType)
  221. for part in parts:
  222. multi_post_part.append(part)
  223. self._last_request_time = time()
  224. if self._manager is not None:
  225. reply = self._manager.post(request, multi_post_part)
  226. self._kept_alive_multiparts[reply] = multi_post_part
  227. if on_progress is not None:
  228. reply.uploadProgress.connect(on_progress)
  229. self._registerOnFinishedCallback(reply, on_finished)
  230. return reply
  231. else:
  232. Logger.log("e", "Could not find manager.")
  233. def postForm(self, target: str, header_data: str, body_data: bytes, on_finished: Optional[Callable[[QNetworkReply], None]], on_progress: Callable = None) -> None:
  234. post_part = QHttpPart()
  235. post_part.setHeader(QNetworkRequest.ContentDispositionHeader, header_data)
  236. post_part.setBody(body_data)
  237. self.postFormWithParts(target, [post_part], on_finished, on_progress)
  238. def _onAuthenticationRequired(self, reply: QNetworkReply, authenticator: QAuthenticator) -> None:
  239. Logger.log("w", "Request to {url} required authentication, which was not implemented".format(url = reply.url().toString()))
  240. def _createNetworkManager(self) -> None:
  241. Logger.log("d", "Creating network manager")
  242. if self._manager:
  243. self._manager.finished.disconnect(self._handleOnFinished)
  244. self._manager.authenticationRequired.disconnect(self._onAuthenticationRequired)
  245. self._manager = QNetworkAccessManager()
  246. self._manager.finished.connect(self._handleOnFinished)
  247. self._manager.authenticationRequired.connect(self._onAuthenticationRequired)
  248. if self._properties.get(b"temporary", b"false") != b"true":
  249. self._checkCorrectGroupName(self.getId(), self.name)
  250. def _registerOnFinishedCallback(self, reply: QNetworkReply, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
  251. if on_finished is not None:
  252. self._onFinishedCallbacks[reply.url().toString() + str(reply.operation())] = on_finished
  253. def _checkCorrectGroupName(self, device_id: str, group_name: str) -> None:
  254. """This method checks if the name of the group stored in the definition container is correct.
  255. After updating from 3.2 to 3.3 some group names may be temporary. If there is a mismatch in the name of the group
  256. then all the container stacks are updated, both the current and the hidden ones.
  257. """
  258. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  259. active_machine_network_name = CuraApplication.getInstance().getMachineManager().activeMachineNetworkKey()
  260. if global_container_stack and device_id == active_machine_network_name:
  261. # Check if the group_name is correct. If not, update all the containers connected to the same printer
  262. if CuraApplication.getInstance().getMachineManager().activeMachineNetworkGroupName != group_name:
  263. metadata_filter = {"um_network_key": active_machine_network_name}
  264. containers = CuraContainerRegistry.getInstance().findContainerStacks(type="machine",
  265. **metadata_filter)
  266. for container in containers:
  267. container.setMetaDataEntry("group_name", group_name)
  268. def _handleOnFinished(self, reply: QNetworkReply) -> None:
  269. # Due to garbage collection, we need to cache certain bits of post operations.
  270. # As we don't want to keep them around forever, delete them if we get a reply.
  271. if reply.operation() == QNetworkAccessManager.PostOperation:
  272. self._clearCachedMultiPart(reply)
  273. if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) is None:
  274. # No status code means it never even reached remote.
  275. return
  276. self._last_response_time = time()
  277. if self._connection_state == ConnectionState.Connecting:
  278. self.setConnectionState(ConnectionState.Connected)
  279. callback_key = reply.url().toString() + str(reply.operation())
  280. try:
  281. if callback_key in self._onFinishedCallbacks:
  282. self._onFinishedCallbacks[callback_key](reply)
  283. except Exception:
  284. Logger.logException("w", "something went wrong with callback")
  285. @pyqtSlot(str, result=str)
  286. def getProperty(self, key: str) -> str:
  287. bytes_key = key.encode("utf-8")
  288. if bytes_key in self._properties:
  289. return self._properties.get(bytes_key, b"").decode("utf-8")
  290. else:
  291. return ""
  292. def getProperties(self):
  293. return self._properties
  294. @pyqtProperty(str, constant = True)
  295. def key(self) -> str:
  296. """Get the unique key of this machine
  297. :return: key String containing the key of the machine.
  298. """
  299. return self._id
  300. @pyqtProperty(str, constant = True)
  301. def address(self) -> str:
  302. """The IP address of the printer."""
  303. return self._properties.get(b"address", b"").decode("utf-8")
  304. @pyqtProperty(str, constant = True)
  305. def name(self) -> str:
  306. """Name of the printer (as returned from the ZeroConf properties)"""
  307. return self._properties.get(b"name", b"").decode("utf-8")
  308. @pyqtProperty(str, constant = True)
  309. def firmwareVersion(self) -> str:
  310. """Firmware version (as returned from the ZeroConf properties)"""
  311. return self._properties.get(b"firmware_version", b"").decode("utf-8")
  312. @pyqtProperty(str, constant = True)
  313. def printerType(self) -> str:
  314. return self._properties.get(b"printer_type", b"Unknown").decode("utf-8")
  315. @pyqtProperty(str, constant = True)
  316. def ipAddress(self) -> str:
  317. """IP adress of this printer"""
  318. return self._address