NetworkedPrinterOutputDevice.py 19 KB

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