NetworkedPrinterOutputDevice.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Application import Application
  4. from UM.Logger import Logger
  5. from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
  6. from PyQt5.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager, QNetworkReply
  7. from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, pyqtSignal, QUrl, QCoreApplication
  8. from time import time
  9. from typing import Callable, Any, Optional, Dict, Tuple
  10. from enum import IntEnum
  11. from typing import List
  12. import os # To get the username
  13. import gzip
  14. class AuthState(IntEnum):
  15. NotAuthenticated = 1
  16. AuthenticationRequested = 2
  17. Authenticated = 3
  18. AuthenticationDenied = 4
  19. AuthenticationReceived = 5
  20. class NetworkedPrinterOutputDevice(PrinterOutputDevice):
  21. authenticationStateChanged = pyqtSignal()
  22. def __init__(self, device_id, address: str, properties, parent = None) -> None:
  23. super().__init__(device_id = device_id, parent = parent)
  24. self._manager = None # type: QNetworkAccessManager
  25. self._last_manager_create_time = None # type: float
  26. self._recreate_network_manager_time = 30
  27. self._timeout_time = 10 # After how many seconds of no response should a timeout occur?
  28. self._last_response_time = None # type: float
  29. self._last_request_time = None # type: float
  30. self._api_prefix = ""
  31. self._address = address
  32. self._properties = properties
  33. self._user_agent = "%s/%s " % (Application.getInstance().getApplicationName(), Application.getInstance().getVersion())
  34. self._onFinishedCallbacks = {} # type: Dict[str, Callable[[QNetworkReply], None]]
  35. self._authentication_state = AuthState.NotAuthenticated
  36. # QHttpMultiPart objects need to be kept alive and not garbage collected during the
  37. # HTTP which uses them. We hold references to these QHttpMultiPart objects here.
  38. self._kept_alive_multiparts = {} # type: Dict[QNetworkReply, QHttpMultiPart]
  39. self._sending_gcode = False
  40. self._compressing_gcode = False
  41. self._gcode = [] # type: List[str]
  42. self._connection_state_before_timeout = None # type: Optional[ConnectionState]
  43. printer_type = self._properties.get(b"machine", b"").decode("utf-8")
  44. printer_type_identifiers = {
  45. "9066": "ultimaker3",
  46. "9511": "ultimaker3_extended",
  47. "9051": "ultimaker_s5"
  48. }
  49. self._printer_type = "Unknown"
  50. for key, value in printer_type_identifiers.items():
  51. if printer_type.startswith(key):
  52. self._printer_type = value
  53. break
  54. def requestWrite(self, nodes, file_name=None, filter_by_machine=False, file_handler=None, **kwargs) -> None:
  55. raise NotImplementedError("requestWrite needs to be implemented")
  56. def setAuthenticationState(self, authentication_state) -> None:
  57. if self._authentication_state != authentication_state:
  58. self._authentication_state = authentication_state
  59. self.authenticationStateChanged.emit()
  60. @pyqtProperty(int, notify=authenticationStateChanged)
  61. def authenticationState(self) -> int:
  62. return self._authentication_state
  63. def _compressDataAndNotifyQt(self, data_to_append: str) -> bytes:
  64. compressed_data = gzip.compress(data_to_append.encode("utf-8"))
  65. self._progress_message.setProgress(-1) # Tickle the message so that it's clear that it's still being used.
  66. QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
  67. # Pretend that this is a response, as zipping might take a bit of time.
  68. # If we don't do this, the device might trigger a timeout.
  69. self._last_response_time = time()
  70. return compressed_data
  71. def _compressGCode(self) -> Optional[bytes]:
  72. self._compressing_gcode = True
  73. ## Mash the data into single string
  74. max_chars_per_line = int(1024 * 1024 / 4) # 1/4 MB per line.
  75. file_data_bytes_list = []
  76. batched_lines = []
  77. batched_lines_count = 0
  78. for line in self._gcode:
  79. if not self._compressing_gcode:
  80. self._progress_message.hide()
  81. # Stop trying to zip / send as abort was called.
  82. return None
  83. # if the gcode was read from a gcode file, self._gcode will be a list of all lines in that file.
  84. # Compressing line by line in this case is extremely slow, so we need to batch them.
  85. batched_lines.append(line)
  86. batched_lines_count += len(line)
  87. if batched_lines_count >= max_chars_per_line:
  88. file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines)))
  89. batched_lines = []
  90. batched_lines_count = 0
  91. # Don't miss the last batch (If any)
  92. if len(batched_lines) != 0:
  93. file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines)))
  94. self._compressing_gcode = False
  95. return b"".join(file_data_bytes_list)
  96. def _update(self) -> bool:
  97. if self._last_response_time:
  98. time_since_last_response = time() - self._last_response_time
  99. else:
  100. time_since_last_response = 0
  101. if self._last_request_time:
  102. time_since_last_request = time() - self._last_request_time
  103. else:
  104. time_since_last_request = float("inf") # An irrelevantly large number of seconds
  105. if time_since_last_response > self._timeout_time >= time_since_last_request:
  106. # Go (or stay) into timeout.
  107. if self._connection_state_before_timeout is None:
  108. self._connection_state_before_timeout = self._connection_state
  109. self.setConnectionState(ConnectionState.closed)
  110. # We need to check if the manager needs to be re-created. If we don't, we get some issues when OSX goes to
  111. # sleep.
  112. if time_since_last_response > self._recreate_network_manager_time:
  113. if self._last_manager_create_time is None:
  114. self._createNetworkManager()
  115. if time() - self._last_manager_create_time > self._recreate_network_manager_time:
  116. self._createNetworkManager()
  117. elif self._connection_state == ConnectionState.closed:
  118. # Go out of timeout.
  119. self.setConnectionState(self._connection_state_before_timeout)
  120. self._connection_state_before_timeout = None
  121. return True
  122. def _createEmptyRequest(self, target, content_type: Optional[str] = "application/json") -> QNetworkRequest:
  123. url = QUrl("http://" + self._address + self._api_prefix + target)
  124. request = QNetworkRequest(url)
  125. if content_type is not None:
  126. request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
  127. request.setHeader(QNetworkRequest.UserAgentHeader, self._user_agent)
  128. return request
  129. def _createFormPart(self, content_header, data, content_type = None) -> QHttpPart:
  130. part = QHttpPart()
  131. if not content_header.startswith("form-data;"):
  132. content_header = "form_data; " + content_header
  133. part.setHeader(QNetworkRequest.ContentDispositionHeader, content_header)
  134. if content_type is not None:
  135. part.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
  136. part.setBody(data)
  137. return part
  138. ## Convenience function to get the username from the OS.
  139. # The code was copied from the getpass module, as we try to use as little dependencies as possible.
  140. def _getUserName(self) -> str:
  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 put(self, target: str, data: str, onFinished: Optional[Callable[[Any, QNetworkReply], None]]) -> None:
  150. if self._manager is None:
  151. self._createNetworkManager()
  152. request = self._createEmptyRequest(target)
  153. self._last_request_time = time()
  154. reply = self._manager.put(request, data.encode())
  155. self._registerOnFinishedCallback(reply, onFinished)
  156. def get(self, target: str, onFinished: Optional[Callable[[Any, QNetworkReply], None]]) -> None:
  157. if self._manager is None:
  158. self._createNetworkManager()
  159. request = self._createEmptyRequest(target)
  160. self._last_request_time = time()
  161. reply = self._manager.get(request)
  162. self._registerOnFinishedCallback(reply, onFinished)
  163. def post(self, target: str, data: str, onFinished: Optional[Callable[[Any, QNetworkReply], None]], onProgress: Callable = None) -> None:
  164. if self._manager is None:
  165. self._createNetworkManager()
  166. request = self._createEmptyRequest(target)
  167. self._last_request_time = time()
  168. reply = self._manager.post(request, data)
  169. if onProgress is not None:
  170. reply.uploadProgress.connect(onProgress)
  171. self._registerOnFinishedCallback(reply, onFinished)
  172. def postFormWithParts(self, target:str, parts: List[QHttpPart], onFinished: Optional[Callable[[Any, QNetworkReply], None]], onProgress: Callable = None) -> None:
  173. if self._manager is None:
  174. self._createNetworkManager()
  175. request = self._createEmptyRequest(target, content_type=None)
  176. multi_post_part = QHttpMultiPart(QHttpMultiPart.FormDataType)
  177. for part in parts:
  178. multi_post_part.append(part)
  179. self._last_request_time = time()
  180. reply = self._manager.post(request, multi_post_part)
  181. self._kept_alive_multiparts[reply] = multi_post_part
  182. if onProgress is not None:
  183. reply.uploadProgress.connect(onProgress)
  184. self._registerOnFinishedCallback(reply, onFinished)
  185. return reply
  186. def postForm(self, target: str, header_data: str, body_data: bytes, onFinished: Optional[Callable[[Any, QNetworkReply], None]], onProgress: Callable = None) -> None:
  187. post_part = QHttpPart()
  188. post_part.setHeader(QNetworkRequest.ContentDispositionHeader, header_data)
  189. post_part.setBody(body_data)
  190. self.postFormWithParts(target, [post_part], onFinished, onProgress)
  191. def _onAuthenticationRequired(self, reply, authenticator) -> None:
  192. Logger.log("w", "Request to {url} required authentication, which was not implemented".format(url = reply.url().toString()))
  193. def _createNetworkManager(self) -> None:
  194. Logger.log("d", "Creating network manager")
  195. if self._manager:
  196. self._manager.finished.disconnect(self.__handleOnFinished)
  197. self._manager.authenticationRequired.disconnect(self._onAuthenticationRequired)
  198. self._manager = QNetworkAccessManager()
  199. self._manager.finished.connect(self.__handleOnFinished)
  200. self._last_manager_create_time = time()
  201. self._manager.authenticationRequired.connect(self._onAuthenticationRequired)
  202. if self._properties.get(b"temporary", b"false") != b"true":
  203. Application.getInstance().getMachineManager().checkCorrectGroupName(self.getId(), self.name)
  204. def _registerOnFinishedCallback(self, reply: QNetworkReply, onFinished: Optional[Callable[[Any, QNetworkReply], None]]) -> None:
  205. if onFinished is not None:
  206. self._onFinishedCallbacks[reply.url().toString() + str(reply.operation())] = onFinished
  207. def __handleOnFinished(self, reply: QNetworkReply) -> None:
  208. # Due to garbage collection, we need to cache certain bits of post operations.
  209. # As we don't want to keep them around forever, delete them if we get a reply.
  210. if reply.operation() == QNetworkAccessManager.PostOperation:
  211. self._clearCachedMultiPart(reply)
  212. if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) is None:
  213. # No status code means it never even reached remote.
  214. return
  215. self._last_response_time = time()
  216. if self._connection_state == ConnectionState.connecting:
  217. self.setConnectionState(ConnectionState.connected)
  218. callback_key = reply.url().toString() + str(reply.operation())
  219. try:
  220. if callback_key in self._onFinishedCallbacks:
  221. self._onFinishedCallbacks[callback_key](reply)
  222. except Exception:
  223. Logger.logException("w", "something went wrong with callback")
  224. @pyqtSlot(str, result=str)
  225. def getProperty(self, key: str) -> str:
  226. bytes_key = key.encode("utf-8")
  227. if bytes_key in self._properties:
  228. return self._properties.get(bytes_key, b"").decode("utf-8")
  229. else:
  230. return ""
  231. def getProperties(self):
  232. return self._properties
  233. ## Get the unique key of this machine
  234. # \return key String containing the key of the machine.
  235. @pyqtProperty(str, constant=True)
  236. def key(self) -> str:
  237. return self._id
  238. ## The IP address of the printer.
  239. @pyqtProperty(str, constant=True)
  240. def address(self) -> str:
  241. return self._properties.get(b"address", b"").decode("utf-8")
  242. ## Name of the printer (as returned from the ZeroConf properties)
  243. @pyqtProperty(str, constant=True)
  244. def name(self) -> str:
  245. return self._properties.get(b"name", b"").decode("utf-8")
  246. ## Firmware version (as returned from the ZeroConf properties)
  247. @pyqtProperty(str, constant=True)
  248. def firmwareVersion(self) -> str:
  249. return self._properties.get(b"firmware_version", b"").decode("utf-8")
  250. @pyqtProperty(str, constant=True)
  251. def printerType(self) -> str:
  252. return self._printer_type
  253. ## IPadress of this printer
  254. @pyqtProperty(str, constant=True)
  255. def ipAddress(self) -> str:
  256. return self._address