NetworkedPrinterOutputDevice.py 14 KB

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