├── .gitattributes
├── .gitignore
├── CMakeLists.txt
├── Cura 4.1 testing doc.rtf.zip
├── DiscoverRepetierAction.py
├── DiscoverRepetierAction.qml
├── LICENSE
├── NetworkMJPGImage.py
├── NetworkReplyTimeout.py
├── README.md
├── RepetierComponents.qml
├── RepetierOutputDevice.py
├── RepetierOutputDevicePlugin.py
├── __init__.py
├── config.jpg
├── icon.png
├── plugin.json
├── qml
└── MonitorItem.qml
└── webcam.jpg
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 | *.qmlc
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Distribution / packaging
11 | .Python
12 | env/
13 | build/
14 | develop-eggs/
15 | dist/
16 | downloads/
17 | eggs/
18 | .eggs/
19 | lib/
20 | lib64/
21 | parts/
22 | sdist/
23 | var/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *,cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 |
56 | # Sphinx documentation
57 | docs/_build/
58 |
59 | # PyBuilder
60 | target/
61 |
62 | #Ipython Notebook
63 | .ipynb_checkpoints
64 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | project(RepetierIntegration NONE)
2 | cmake_minimum_required(VERSION 2.8.12)
3 |
4 | install(FILES
5 | __init__.py
6 | plugin.json
7 | DiscoverRepetierAction.py
8 | DiscoverRepetierAction.qml
9 | RepetierComponents.qml
10 | RepetierOutputDevice.py
11 | RepetierOutputDevicePlugin.py
12 | NetworkMJPGImage.py
13 | zeroconf.py
14 | MonitorItem.qml
15 | LICENSE
16 | README.md
17 | DESTINATION lib/cura/plugins/RepetierIntegration
18 | )
19 |
--------------------------------------------------------------------------------
/Cura 4.1 testing doc.rtf.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/VMaxx/RepetierIntegration/de0dbe77d5aa870c44f65234a488240f0c509512/Cura 4.1 testing doc.rtf.zip
--------------------------------------------------------------------------------
/DiscoverRepetierAction.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView & Shane Bumpurs
2 | # RepetierPlugin is released under the terms of the AGPLv3 or higher.
3 |
4 | from UM.i18n import i18nCatalog
5 | from UM.Logger import Logger
6 | from UM.Settings.DefinitionContainer import DefinitionContainer
7 | from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
8 | from UM.Settings.ContainerRegistry import ContainerRegistry
9 |
10 | from cura.CuraApplication import CuraApplication
11 | from cura.MachineAction import MachineAction
12 | from cura.Settings.CuraStackBuilder import CuraStackBuilder
13 |
14 | from PyQt6.QtCore import pyqtSignal, pyqtProperty, pyqtSlot, QUrl, QObject, QTimer
15 | from PyQt6.QtQml import QQmlComponent, QQmlContext
16 | from PyQt6.QtGui import QDesktopServices
17 | from PyQt6.QtWidgets import QMessageBox
18 | from PyQt6.QtNetwork import QNetworkRequest, QNetworkAccessManager, QNetworkReply
19 | from .NetworkReplyTimeout import NetworkReplyTimeout
20 | from .RepetierOutputDevicePlugin import RepetierOutputDevicePlugin
21 | from .RepetierOutputDevice import RepetierOutputDevice
22 |
23 | QNetworkAccessManagerOperations = QNetworkAccessManager.Operation
24 | QNetworkRequestKnownHeaders = QNetworkRequest.KnownHeaders
25 | QNetworkRequestAttributes = QNetworkRequest.Attribute
26 | QNetworkReplyNetworkErrors = QNetworkReply.NetworkError
27 |
28 | import re
29 | import os.path
30 | import json
31 | import base64
32 |
33 | from typing import cast, Any, Tuple, Dict, List, Optional, TYPE_CHECKING
34 | if TYPE_CHECKING:
35 | from UM.Settings.ContainerInterface import ContainerInterface
36 |
37 | catalog = i18nCatalog("cura")
38 |
39 | class DiscoverRepetierAction(MachineAction):
40 | def __init__(self, parent: QObject = None) -> None:
41 | super().__init__("DiscoverRepetierAction", catalog.i18nc("@action", "Connect Repetier"))
42 |
43 | self._qml_url = "DiscoverRepetierAction.qml"
44 |
45 | self._application = CuraApplication.getInstance()
46 | self._network_plugin = None
47 |
48 | # QNetwork manager needs to be created in advance. If we don't it can happen that it doesn't correctly
49 | # hook itself into the event loop, which results in events never being fired / done.
50 | self._network_manager = QNetworkAccessManager()
51 | self._network_manager.finished.connect(self._onRequestFinished)
52 | self._printers = [""]
53 | self._groups = [""]
54 | self._printerlist_reply = None
55 | self._groupslist_reply = None
56 | self._settings_reply = None
57 | self._settings_reply_timeout = None # type: Optional[NetworkReplyTimeout]
58 |
59 | self._instance_supports_appkeys = False
60 | self._appkey_reply = None # type: Optional[QNetworkReply]
61 | self._appkey_request = None # type: Optional[QNetworkRequest]
62 | self._appkey_instance_id = ""
63 |
64 | self._appkey_poll_timer = QTimer()
65 | self._appkey_poll_timer.setInterval(500)
66 | self._appkey_poll_timer.setSingleShot(True)
67 | self._appkey_poll_timer.timeout.connect(self._pollApiKey)
68 |
69 | # Try to get version information from plugin.json
70 | plugin_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugin.json")
71 | try:
72 | with open(plugin_file_path) as plugin_file:
73 | plugin_info = json.load(plugin_file)
74 | self._plugin_version = plugin_info["version"]
75 | except:
76 | # The actual version info is not critical to have so we can continue
77 | self._plugin_version = "0.0"
78 | Logger.logException("w", "Could not get version information for the plugin")
79 |
80 | self._user_agent = ("%s/%s %s/%s" % (
81 | self._application.getApplicationName(),
82 | self._application.getVersion(),
83 |
84 | "RepetierIntegration",
85 | self._plugin_version
86 | )).encode()
87 |
88 | self._settings_instance = None
89 |
90 | self._instance_responded = False
91 | self._instance_in_error = False
92 | self._instance_api_key_accepted = False
93 | self._instance_supports_sd = False
94 | self._instance_supports_camera = False
95 | self._instance_webcamflip_y = False
96 | self._instance_webcamflip_x = False
97 | self._instance_webcamrot90 = False
98 | self._instance_webcamrot270 = False
99 |
100 | # Load keys cache from preferences
101 | self._preferences = self._application.getPreferences()
102 | self._preferences.addPreference("Repetier/keys_cache", "")
103 |
104 | try:
105 | self._keys_cache = json.loads(self._preferences.getValue("Repetier/keys_cache"))
106 | except ValueError:
107 | self._keys_cache = {}
108 | if not isinstance(self._keys_cache, dict):
109 | self._keys_cache = {}
110 |
111 | self._additional_components = None
112 |
113 | ContainerRegistry.getInstance().containerAdded.connect(self._onContainerAdded)
114 | self._application.engineCreatedSignal.connect(self._createAdditionalComponentsView)
115 |
116 | @pyqtProperty(str, constant=True)
117 | def pluginVersion(self) -> str:
118 | return self._plugin_version
119 |
120 | @pyqtSlot()
121 | def startDiscovery(self) -> None:
122 | if not self._plugin_id:
123 | return
124 | if not self._network_plugin:
125 | self._network_plugin = cast(RepetierOutputDevicePlugin, self._application.getOutputDeviceManager().getOutputDevicePlugin(self._plugin_id))
126 | if not self._network_plugin:
127 | return
128 | self._network_plugin.addInstanceSignal.connect(self._onInstanceDiscovery)
129 | self._network_plugin.removeInstanceSignal.connect(self._onInstanceDiscovery)
130 | self._network_plugin.instanceListChanged.connect(self._onInstanceDiscovery)
131 | self.instancesChanged.emit()
132 | else:
133 | # Restart bonjour discovery
134 | self._network_plugin.startDiscovery()
135 |
136 | def _onInstanceDiscovery(self, *args) -> None:
137 | self.instancesChanged.emit()
138 |
139 | @pyqtSlot(str)
140 | def removeManualInstance(self, name: str) -> None:
141 | if not self._network_plugin:
142 | return
143 |
144 | self._network_plugin.removeManualInstance(name)
145 |
146 | @pyqtSlot(str, str, int, str, bool, str, str,str)
147 | def setManualInstance(self, name, address, port, path, useHttps, userName, password,repetierid):
148 | if not self._network_plugin:
149 | return
150 | # This manual printer could replace a current manual printer
151 | self._network_plugin.removeManualInstance(name)
152 |
153 | self._network_plugin.addManualInstance(name, address, port, path, useHttps, userName, password, repetierid)
154 |
155 | def _onContainerAdded(self, container: "ContainerInterface") -> None:
156 | # Add this action as a supported action to all machine definitions
157 | if (
158 | isinstance(container, DefinitionContainer) and
159 | container.getMetaDataEntry("type") == "machine" and
160 | container.getMetaDataEntry("supports_usb_connection")
161 | ):
162 |
163 | self._application.getMachineActionManager().addSupportedAction(container.getId(), self.getKey())
164 |
165 | instancesChanged = pyqtSignal()
166 | appKeysSupportedChanged = pyqtSignal()
167 | appKeyReceived = pyqtSignal()
168 | instanceIdChanged = pyqtSignal()
169 |
170 | @pyqtProperty("QVariantList", notify = instancesChanged)
171 | def discoveredInstances(self) -> List[Any]:
172 | if self._network_plugin:
173 | instances = list(self._network_plugin.getInstances().values())
174 | instances.sort(key = lambda k: k.name)
175 | return instances
176 | else:
177 | return []
178 |
179 | @pyqtSlot(str)
180 | def setInstanceId(self, key: str) -> None:
181 | global_container_stack = self._application.getGlobalContainerStack()
182 | if global_container_stack:
183 | global_container_stack.setMetaDataEntry("repetier_id", key)
184 |
185 | if self._network_plugin:
186 | # Ensure that the connection states are refreshed.
187 | self._network_plugin.reCheckConnections()
188 |
189 | self.instanceIdChanged.emit()
190 |
191 | @pyqtProperty(str, notify = instanceIdChanged)
192 | def instanceId(self) -> str:
193 | global_container_stack = self._application.getGlobalContainerStack()
194 | if not global_container_stack:
195 | return ""
196 |
197 | return global_container_stack.getMetaDataEntry("repetier_id", "")
198 |
199 | @pyqtSlot(str)
200 | @pyqtSlot(result = str)
201 | def getInstanceId(self) -> str:
202 | global_container_stack = self._application.getGlobalContainerStack()
203 | if not global_container_stack:
204 | Logger.log("d", "getInstancdId - self._application.getGlobalContainerStack() returned nothing")
205 | return ""
206 |
207 | return global_container_stack.getMetaDataEntry("repetier_id", "")
208 | @pyqtSlot(str)
209 | def requestApiKey(self, instance_id: str) -> None:
210 | (instance, base_url, basic_auth_username, basic_auth_password) = self._getInstanceInfo(instance_id)
211 |
212 | if not base_url:
213 |
214 | return
215 |
216 | ## Request appkey
217 | self._appkey_instance_id = instance_id
218 | self._appkey_request = self._createRequest(
219 | QUrl(base_url + "plugin/appkeys/request"),
220 | basic_auth_username, basic_auth_password
221 | )
222 | self._appkey_request.setRawHeader(b"Content-Type", b"application/json")
223 | data = json.dumps({"app": "Cura"})
224 | self._appkey_reply = self._network_manager.post(self._appkey_request, data.encode())
225 |
226 | @pyqtSlot()
227 | def cancelApiKeyRequest(self) -> None:
228 | if self._appkey_reply:
229 | if self._appkey_reply.isRunning():
230 | self._appkey_reply.abort()
231 | self._appkey_reply = None
232 |
233 | self._appkey_request = None # type: Optional[QNetworkRequest]
234 |
235 | self._appkey_poll_timer.stop()
236 |
237 | def _pollApiKey(self) -> None:
238 | if not self._appkey_request:
239 | return
240 | self._appkey_reply = self._network_manager.get(self._appkey_request)
241 |
242 | @pyqtSlot(str)
243 | def probeAppKeySupport(self, instance_id: str) -> None:
244 | (instance, base_url, basic_auth_username, basic_auth_password) = self._getInstanceInfo(instance_id)
245 | if not base_url or not instance:
246 | return
247 |
248 | instance.getAdditionalData()
249 |
250 | self._instance_supports_appkeys = False
251 | self.appKeysSupportedChanged.emit()
252 |
253 | appkey_probe_request = self._createRequest(
254 | QUrl(base_url + "plugin/appkeys/probe"),
255 | basic_auth_username, basic_auth_password
256 | )
257 | self._appkey_reply = self._network_manager.get(appkey_probe_request)
258 |
259 | @pyqtSlot(str)
260 | def getPrinterList(self, base_url):
261 | self._instance_responded = False
262 | Logger.log("d", "getPrinterList:base_url:" + base_url)
263 | url = QUrl( base_url + "printer/info")
264 | Logger.log("d", "getPrinterList:" + url.toString())
265 | settings_request = QNetworkRequest(url)
266 | settings_request.setRawHeader("User-Agent".encode(), self._user_agent)
267 | self._printerlist_reply=self._network_manager.get(settings_request)
268 | return self._printers
269 |
270 | @pyqtSlot(str)
271 | def getModelGroups(self, base_url,slug,key):
272 | self._instance_responded = False
273 | url = QUrl( base_url + "/printer/api/" + slug +"?a=listModelGroups&apikey=" + key)
274 | Logger.log("d", "getModelGroups:" + url.toString())
275 | settings_request = QNetworkRequest(url)
276 | settings_request.setRawHeader("User-Agent".encode(), self._user_agent)
277 | self._grouplist_reply=self._network_manager.get(settings_request)
278 | return self._groups
279 |
280 | @pyqtSlot(str, str, str, str, str, str)
281 | def testApiKey(self,instance_id: str, base_url, api_key, basic_auth_username = "", basic_auth_password = "", work_id = "") -> None:
282 | (instance, base_url, basic_auth_username, basic_auth_password) = self._getInstanceInfo(instance_id)
283 | self._instance_responded = False
284 | self._instance_api_key_accepted = False
285 | self._instance_supports_sd = False
286 | self._instance_webcamflip_y = False
287 | self._instance_webcamflip_x = False
288 | self._instance_webcamrot90 = False
289 | self._instance_webcamrot270 = False
290 | self._instance_supports_camera = False
291 | self.selectedInstanceSettingsChanged.emit()
292 | if self._settings_reply:
293 | if self._settings_reply.isRunning():
294 | self._settings_reply.abort()
295 | self._settings_reply = None
296 | if self._settings_reply_timeout:
297 | self._settings_reply_timeout = None
298 | if ((api_key != "") and (api_key != None) and (work_id != "")):
299 | Logger.log("d", "Trying to access Repetier instance at %s with the provided API key." % base_url)
300 | Logger.log("d", "Using %s as work_id" % work_id)
301 | Logger.log("d", "Using %s as api_key" % api_key)
302 | url = QUrl(base_url + "/printer/api/" + work_id + "?a=getPrinterConfig&apikey=" + api_key)
303 | settings_request = QNetworkRequest(url)
304 | settings_request.setRawHeader("x-api-key".encode(), api_key.encode())
305 | settings_request.setRawHeader("User-Agent".encode(), self._user_agent)
306 | if basic_auth_username and basic_auth_password:
307 | data = base64.b64encode(("%s:%s" % (basic_auth_username, basic_auth_password)).encode()).decode("utf-8")
308 | settings_request.setRawHeader("Authorization".encode(), ("Basic %s" % data).encode())
309 | self._settings_reply = self._network_manager.get(settings_request)
310 | self._settings_instance = instance
311 | self.getModelGroups(base_url,work_id,api_key)
312 | else:
313 | self.getPrinterList(base_url)
314 |
315 | @pyqtSlot(str)
316 | def setApiKey(self, api_key: str) -> None:
317 | global_container_stack = self._application.getGlobalContainerStack()
318 | if not global_container_stack:
319 | return
320 | global_container_stack.setMetaDataEntry("repetier_api_key", api_key)
321 | self._keys_cache[self.getInstanceId()] = api_key
322 | keys_cache = base64.b64encode(json.dumps(self._keys_cache).encode("ascii")).decode("ascii")
323 | self._preferences.setValue("Repetier/keys_cache", keys_cache)
324 |
325 | if self._network_plugin:
326 | # Ensure that the connection states are refreshed.
327 | self._network_plugin.reCheckConnections()
328 |
329 | # Get the stored API key of this machine
330 | # \return key String containing the key of the machine.
331 | @pyqtSlot(str, result=str)
332 | def getApiKey(self, instance_id: str) -> str:
333 | global_container_stack = self._application.getGlobalContainerStack()
334 | if not global_container_stack:
335 | return ""
336 | Logger.log("d", "APIKEY read %s" % global_container_stack.getMetaDataEntry("repetier_api_key",""))
337 | if instance_id == self.getInstanceId():
338 | api_key = global_container_stack.getMetaDataEntry("repetier_api_key","")
339 | else:
340 | api_key = self._keys_cache.get(instance_id, "")
341 | return api_key
342 |
343 | selectedInstanceSettingsChanged = pyqtSignal()
344 |
345 | @pyqtProperty(list)
346 | def getPrinters(self):
347 | return self._printers
348 |
349 | @pyqtProperty(list)
350 | def getGroups(self):
351 | return self._groups
352 |
353 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
354 | def instanceResponded(self) -> bool:
355 | return self._instance_responded
356 |
357 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
358 | def instanceInError(self) -> bool:
359 | return self._instance_in_error
360 |
361 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
362 | def instanceApiKeyAccepted(self) -> bool:
363 | return self._instance_api_key_accepted
364 |
365 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
366 | def instanceSupportsSd(self) -> bool:
367 | return self._instance_supports_sd
368 |
369 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
370 | def instanceWebcamFlipY(self):
371 | return self._instance_webcamflip_y
372 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
373 | def instanceWebcamFlipX(self):
374 | return self._instance_webcamflip_x
375 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
376 | def instanceWebcamRot90(self):
377 | return self._instance_webcamrot90
378 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
379 | def instanceWebcamRot270(self):
380 | return self._instance_webcamrot270
381 |
382 | @pyqtProperty(bool, notify = selectedInstanceSettingsChanged)
383 | def instanceSupportsCamera(self) -> bool:
384 | return self._instance_supports_camera
385 |
386 | @pyqtSlot(str, str, str)
387 | def setContainerMetaDataEntry(self, container_id: str, key: str, value: str) -> None:
388 | containers = ContainerRegistry.getInstance().findContainers(id = container_id)
389 | if not containers:
390 | Logger.log("w", "Could not set metadata of container %s because it was not found.", container_id)
391 | return
392 |
393 | containers[0].setMetaDataEntry(key, value)
394 |
395 | @pyqtSlot(bool)
396 | def applyGcodeFlavorFix(self, apply_fix: bool) -> None:
397 | global_container_stack = self._application.getGlobalContainerStack()
398 | if not global_container_stack:
399 | return
400 |
401 | gcode_flavor = "RepRap (Marlin/Sprinter)" if apply_fix else "UltiGCode"
402 | if global_container_stack.getProperty("machine_gcode_flavor", "value") == gcode_flavor:
403 | # No need to add a definition_changes container if the setting is not going to be changed
404 | return
405 |
406 | # Make sure there is a definition_changes container to store the machine settings
407 | definition_changes_container = global_container_stack.definitionChanges
408 | if definition_changes_container == ContainerRegistry.getInstance().getEmptyInstanceContainer():
409 | definition_changes_container = CuraStackBuilder.createDefinitionChangesContainer(
410 | global_container_stack, global_container_stack.getId() + "_settings")
411 |
412 | definition_changes_container.setProperty("machine_gcode_flavor", "value", gcode_flavor)
413 |
414 | # Update the has_materials metadata flag after switching gcode flavor
415 | definition = global_container_stack.getBottom()
416 | if (
417 | not definition or
418 | definition.getProperty("machine_gcode_flavor", "value") != "UltiGCode" or
419 | definition.getMetaDataEntry("has_materials", False)
420 | ):
421 |
422 | # In other words: only continue for the UM2 (extended), but not for the UM2+
423 | return
424 |
425 | has_materials = global_container_stack.getProperty("machine_gcode_flavor", "value") != "UltiGCode"
426 |
427 | material_container = global_container_stack.material
428 |
429 | if has_materials:
430 | global_container_stack.setMetaDataEntry("has_materials", True)
431 |
432 | # Set the material container to a sane default
433 | if material_container == ContainerRegistry.getInstance().getEmptyInstanceContainer():
434 | search_criteria = {
435 | "type": "material",
436 | "definition": "fdmprinter",
437 | "id": global_container_stack.getMetaDataEntry("preferred_material")
438 | }
439 | materials = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
440 | if materials:
441 | global_container_stack.material = materials[0]
442 | else:
443 | # The metadata entry is stored in an ini, and ini files are parsed as strings only.
444 | # Because any non-empty string evaluates to a boolean True, we have to remove the entry to make it False.
445 | if "has_materials" in global_container_stack.getMetaData():
446 | global_container_stack.removeMetaDataEntry("has_materials")
447 |
448 | global_container_stack.material = ContainerRegistry.getInstance().getEmptyInstanceContainer()
449 |
450 | self._application.globalContainerStackChanged.emit()
451 |
452 | @pyqtSlot(str)
453 | def openWebPage(self, url: str) -> None:
454 | QDesktopServices.openUrl(QUrl(url))
455 |
456 | def _createAdditionalComponentsView(self) -> None:
457 | Logger.log("d", "Creating additional ui components for Repetier-connected printers.")
458 |
459 | path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "RepetierComponents.qml")
460 | self._additional_components = self._application.createQmlComponent(path, {"manager": self})
461 | if not self._additional_components:
462 | Logger.log("w", "Could not create additional components for Repetier-connected printers.")
463 | return
464 |
465 | self._application.addAdditionalComponent(
466 | "monitorButtons",
467 | self._additional_components.findChild(QObject, "openRepetierButton")
468 | )
469 |
470 | def _onRequestFailed(self, reply: QNetworkReply) -> None:
471 | # if reply.operation() == QNetworkAccessManager.GetOperation:
472 | if reply.operation() == QNetworkAccessManagerOperations.GetOperation:
473 | if "api/settings" in reply.url().toString(): # Repetier settings dump from /settings:
474 | Logger.log("w", "Connection refused or timeout when trying to access Repetier at %s" % reply.url().toString())
475 | self._instance_in_error = True
476 | self.selectedInstanceSettingsChanged.emit()
477 |
478 |
479 | # Handler for all requests that have finished.
480 | def _onRequestFinished(self, reply: QNetworkReply) -> None:
481 | if reply.error() == QNetworkReplyNetworkErrors.TimeoutError:
482 | # if reply.error() == QNetworkReply.TimeoutError:
483 | QMessageBox.warning(None,'Connection Timeout','Connection Timeout')
484 | return
485 | # http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
486 | http_status_code = reply.attribute(QNetworkRequestAttributes.HttpStatusCodeAttribute)
487 | if not http_status_code:
488 | #QMessageBox.warning(None,'Connection Attempt2',http_status_code)
489 | # Received no or empty reply
490 | Logger.log("d","Received no or empty reply")
491 | return
492 |
493 | # if reply.operation() == QNetworkAccessManager.GetOperation:
494 | if reply.operation() == QNetworkAccessManagerOperations.GetOperation:
495 | Logger.log("d",reply.url().toString())
496 | if "printer/info" in reply.url().toString(): # Repetier settings dump from printer/info:
497 | if http_status_code == 200:
498 | try:
499 | json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
500 | Logger.log("d",reply.url().toString())
501 | Logger.log("d", json_data)
502 | except json.decoder.JSONDecodeError:
503 | Logger.log("w", "Received invalid JSON from Repetier instance.")
504 | json_data = {}
505 |
506 | if "printers" in json_data:
507 | Logger.log("d", "DiscoverRepetierAction: printers: %s",len(json_data["printers"]))
508 | if len(json_data["printers"])>0:
509 | self._printers = [""]
510 | for printerinfo in json_data["printers"]:
511 | Logger.log("d", "Slug: %s",printerinfo["slug"])
512 | self._printers.append(printerinfo["slug"])
513 |
514 | if "apikey" in json_data:
515 | Logger.log("d", "DiscoverRepetierAction: apikey: %s",json_data["apikey"])
516 | global_container_stack = self._application.getGlobalContainerStack()
517 | if not global_container_stack:
518 | return
519 | global_container_stack.setMetaDataEntry("repetier_api_key", json_data["apikey"])
520 | self._keys_cache[self.getInstanceId()] = json_data["apikey"]
521 | keys_cache = base64.b64encode(json.dumps(self._keys_cache).encode("ascii")).decode("ascii")
522 | self._preferences.setValue("Repetier/keys_cache", keys_cache)
523 | self.appKeyReceived.emit()
524 | if "listModelGroups" in reply.url().toString(): # Repetier settings dump from listModelGroups:
525 | if http_status_code == 200:
526 | try:
527 | json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
528 | Logger.log("d",reply.url().toString())
529 | Logger.log("d", json_data)
530 | except json.decoder.JSONDecodeError:
531 | Logger.log("w", "Received invalid JSON from Repetier instance.")
532 | json_data = {}
533 | if "groupNames" in json_data:
534 | Logger.log("d", "DiscoverRepetierAction: groupNames: %s",len(json_data["groupNames"]))
535 | if len(json_data["groupNames"])>0:
536 | self._groups = [""]
537 | for gname in json_data["groupNames"]:
538 | Logger.log("d", "groupName: %s",gname)
539 | self._groups.append(gname)
540 | if self._network_plugin:
541 | # Ensure that the connection states are refreshed.
542 | self._network_plugin.reCheckConnections()
543 |
544 | if "getPrinterConfig" in reply.url().toString(): # Repetier settings dump from getPrinterConfig:
545 | if http_status_code == 200:
546 | Logger.log("d", "API key accepted by Repetier.")
547 | self._instance_api_key_accepted = True
548 |
549 | try:
550 | json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
551 | Logger.log("d",reply.url().toString())
552 | Logger.log("d", json_data)
553 | except json.decoder.JSONDecodeError:
554 | Logger.log("w", "Received invalid JSON from Repetier instance.")
555 | json_data = {}
556 |
557 | if "general" in json_data and "sdcard" in json_data["general"]:
558 | self._instance_supports_sd = json_data["general"]["sdcard"]
559 |
560 | if "webcam" in json_data and "dynamicUrl" in json_data["webcam"]:
561 | Logger.log("d", "DiscoverRepetierAction: Checking streamurl")
562 | Logger.log("d", "DiscoverRepetierAction: %s", reply.url())
563 | if not json_data["webcam"]["dynamicUrl"]: #empty string or None
564 | stream_url = ""
565 | else:
566 | stream_url = json_data["webcam"]["dynamicUrl"].replace("127.0.0.1",re.findall( r'[0-9]+(?:\.[0-9]+){3}', reply.url().toString())[0])
567 | Logger.log("d", "DiscoverRepetierAction: stream_url: %s",stream_url)
568 | Logger.log("d", "DiscoverRepetierAction: reply_url: %s",reply.url())
569 | if stream_url: #not empty string or None
570 | self._instance_supports_camera = True
571 | if "webcams" in json_data:
572 | Logger.log("d", "DiscoverRepetierAction: webcams: %s",len(json_data["webcams"]))
573 | if len(json_data["webcams"])>0:
574 | if "dynamicUrl" in json_data["webcams"][0]:
575 | Logger.log("d", "DiscoverRepetierAction: Checking streamurl")
576 | Logger.log("d", "DiscoverRepetierAction: reply_url: %s",reply.url())
577 | stream_url = ""
578 | if len(re.findall( r'[0-9]+(?:\.[0-9]+){3}', reply.url().toString()))>0:
579 | if not json_data["webcams"][0]["dynamicUrl"]: #empty string or None
580 | stream_url = ""
581 | else:
582 | stream_url = json_data["webcams"][0]["dynamicUrl"].replace("127.0.0.1",re.findall( r'[0-9]+(?:\.[0-9]+){3}', reply.url().toString())[0])
583 | Logger.log("d", "DiscoverRepetierAction: stream_url: %s",stream_url)
584 | if stream_url: #not empty string or None
585 | self._instance_supports_camera = True
586 | elif http_status_code == 401:
587 | Logger.log("d", "Invalid API key for Repetier.")
588 | self._instance_api_key_accepted = False
589 | self._instance_in_error = True
590 |
591 | self._instance_responded = True
592 | self.selectedInstanceSettingsChanged.emit()
593 |
594 | def _createRequest(self, url: str, basic_auth_username: str = "", basic_auth_password: str = "") -> QNetworkRequest:
595 | request = QNetworkRequest(url)
596 | request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
597 | request.setRawHeader(b"User-Agent", self._user_agent)
598 |
599 | if basic_auth_username and basic_auth_password:
600 | data = base64.b64encode(("%s:%s" % (basic_auth_username, basic_auth_password)).encode()).decode("utf-8")
601 | request.setRawHeader(b"Authorization", ("Basic %s" % data).encode())
602 |
603 | # ignore SSL errors (eg for self-signed certificates)
604 | ssl_configuration = QSslConfiguration.defaultConfiguration()
605 | ssl_configuration.setPeerVerifyMode(QSslSocket.VerifyNone)
606 | request.setSslConfiguration(ssl_configuration)
607 |
608 | return request
609 |
610 | ## Utility handler to base64-decode a string (eg an obfuscated API key), if it has been encoded before
611 | def _deobfuscateString(self, source: str) -> str:
612 | try:
613 | return base64.b64decode(source.encode("ascii")).decode("ascii")
614 | except UnicodeDecodeError:
615 | return source
616 |
617 | def _getInstanceInfo(self, instance_id: str) -> Tuple[Optional[RepetierOutputDevice], str, str, str]:
618 | if not self._network_plugin:
619 | return (None, "","","")
620 | instance = self._network_plugin.getInstanceById(instance_id)
621 | if not instance:
622 | return (None, "","","")
623 |
624 | return (instance, instance.baseURL, instance.getProperty("userName"), instance.getProperty("password"))
--------------------------------------------------------------------------------
/DiscoverRepetierAction.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 2.1
2 | import QtQuick.Controls 2.0
3 |
4 | import UM 1.5 as UM
5 | import Cura 1.0 as Cura
6 |
7 | Cura.MachineAction
8 | {
9 | id: base
10 | anchors.fill: parent;
11 | property var selectedInstance: null
12 | property string activeMachineId:
13 | {
14 | if (Cura.MachineManager.activeMachineId != undefined)
15 | {
16 | return Cura.MachineManager.activeMachineId;
17 | }
18 | else if (Cura.MachineManager.activeMachine !== null)
19 | {
20 | return Cura.MachineManager.activeMachine.id;
21 | }
22 |
23 | CuraApplication.log("There does not seem to be an active machine");
24 | return "";
25 | }
26 |
27 | onVisibleChanged:
28 | {
29 | if(!visible)
30 | {
31 | manager.cancelApiKeyRequest();
32 | }
33 | }
34 |
35 | function boolCheck(value) //Hack to ensure a good match between python and qml.
36 | {
37 | if(value == "True")
38 | {
39 | return true
40 | }else if(value == "False" || value == undefined)
41 | {
42 | return false
43 | }
44 | else
45 | {
46 | return value
47 | }
48 | }
49 | Column
50 | {
51 | anchors.fill: parent;
52 | id: discoverRepetierAction
53 |
54 |
55 | spacing: UM.Theme.getSize("default_margin").height
56 | width: parent.width
57 |
58 | UM.I18nCatalog { id: catalog; name:"repetier" }
59 |
60 | Item
61 | {
62 | width: parent.width
63 | height: pageTitle.height
64 |
65 | UM.Label
66 | {
67 | id: pageTitle
68 | text: catalog.i18nc("@title", "Connect to Repetier")
69 | font: UM.Theme.getFont("large_bold")
70 | }
71 |
72 | UM.Label
73 | {
74 | id: pluginVersion
75 | anchors.bottom: pageTitle.bottom
76 | anchors.right: parent.right
77 | text: manager.pluginVersion
78 | wrapMode: Text.WordWrap
79 | font.pointSize: 8
80 | }
81 | }
82 | UM.Label
83 | {
84 | id: pageDescription
85 | width: parent.width
86 | wrapMode: Text.WordWrap
87 | text: catalog.i18nc("@label", "Select your Repetier instance from the list below:")
88 | }
89 |
90 | Row
91 | {
92 | spacing: UM.Theme.getSize("default_lining").width
93 |
94 | Cura.SecondaryButton
95 | {
96 | id: addButton
97 | text: catalog.i18nc("@action:button", "Add");
98 | onClicked:
99 | {
100 | manualPrinterDialog.showDialog("", "192.168.1.250", "3344", "/", false, "", "","");
101 | }
102 | }
103 |
104 | Cura.SecondaryButton
105 | {
106 | id: editButton
107 | text: catalog.i18nc("@action:button", "Edit")
108 | enabled: base.selectedInstance != null && base.selectedInstance.getProperty("manual") == "true"
109 | onClicked:
110 | {
111 | if (Cura.ContainerManager.getContainerMetaDataEntry(base.selectedInstance.name, "repetier_id") != null)
112 | {
113 | manualPrinterDialog.showDialog(
114 | base.selectedInstance.name, base.selectedInstance.ipAddress,
115 | base.selectedInstance.port, base.selectedInstance.path,
116 | base.selectedInstance.getProperty("useHttps") == "true",
117 | base.selectedInstance.getProperty("userName"),
118 | base.selectedInstance.getProperty("password"),
119 | Cura.ContainerManager.getContainerMetaDataEntry(base.selectedInstance.name, "repetier_id")
120 | );
121 | }
122 | else
123 | {
124 | manualPrinterDialog.showDialog(
125 | base.selectedInstance.name, base.selectedInstance.ipAddress,
126 | base.selectedInstance.port, base.selectedInstance.path,
127 | base.selectedInstance.getProperty("useHttps") == "true",
128 | base.selectedInstance.getProperty("userName"),
129 | base.selectedInstance.getProperty("password"),
130 | ""
131 | );
132 | }
133 | }
134 | }
135 |
136 | Cura.SecondaryButton
137 | {
138 | id: removeButton
139 | text: catalog.i18nc("@action:button", "Remove")
140 | enabled: base.selectedInstance != null && base.selectedInstance.getProperty("manual") == "true"
141 | onClicked: manager.removeManualInstance(base.selectedInstance.name)
142 | }
143 |
144 | Cura.SecondaryButton
145 | {
146 | id: rediscoverButton
147 | text: catalog.i18nc("@action:button", "Refresh")
148 | onClicked: manager.startDiscovery()
149 | }
150 | }
151 |
152 | Row
153 | {
154 | width: parent.width
155 | spacing: UM.Theme.getSize("default_margin").width
156 |
157 | Rectangle
158 | {
159 | width: Math.floor(parent.width * 0.4)
160 | height: base.height - (parent.y + UM.Theme.getSize("default_margin").height)
161 |
162 | color: UM.Theme.getColor("main_background")
163 | border.width: UM.Theme.getSize("default_lining").width
164 | border.color: UM.Theme.getColor("thick_lining")
165 |
166 | ListView
167 | {
168 | id: listview
169 |
170 | clip: true
171 | ScrollBar.vertical: UM.ScrollBar {}
172 |
173 | anchors.fill: parent
174 | anchors.margins: UM.Theme.getSize("default_lining").width
175 |
176 | model: manager.discoveredInstances
177 | onModelChanged:
178 | {
179 | var selectedId = manager.instanceId;
180 | for(var i = 0; i < model.length; i++) {
181 | if(model[i].getId() == selectedId)
182 | {
183 | currentIndex = i;
184 | return
185 | }
186 | }
187 | currentIndex = -1;
188 | }
189 |
190 | currentIndex: activeIndex
191 | onCurrentIndexChanged:
192 | {
193 | base.selectedInstance = listview.model[currentIndex];
194 | apiCheckDelay.throttledCheck();
195 | comboGroups.clear();
196 | }
197 |
198 | Component.onCompleted: manager.startDiscovery()
199 |
200 | delegate: Rectangle
201 | {
202 | height: childrenRect.height
203 | color: ListView.isCurrentItem ? UM.Theme.getColor("text_selection") : UM.Theme.getColor("main_background")
204 | width: parent.width
205 | UM.Label
206 | {
207 | anchors.left: parent.left
208 | anchors.leftMargin: UM.Theme.getSize("default_margin").width
209 | anchors.right: parent.right
210 | text: listview.model[index].name
211 | elide: Text.ElideRight
212 | font.italic: listview.model[index].key == manager.instanceId
213 | wrapMode: Text.NoWrap
214 | }
215 |
216 | MouseArea
217 | {
218 | anchors.fill: parent;
219 | onClicked:
220 | {
221 | if(!parent.ListView.isCurrentItem)
222 | {
223 | parent.ListView.view.currentIndex = index;
224 | }
225 | }
226 | }
227 | }
228 | }
229 | }
230 |
231 | Column
232 | {
233 | width: Math.floor(parent.width * 0.6)
234 | spacing: UM.Theme.getSize("default_margin").height
235 | UM.Label
236 | {
237 | visible: base.selectedInstance != null
238 | width: parent.width
239 | wrapMode: Text.WordWrap
240 | text: base.selectedInstance ? base.selectedInstance.name : ""
241 | font: UM.Theme.getFont("large_bold")
242 | elide: Text.ElideRight
243 | }
244 | Grid
245 | {
246 | visible: base.selectedInstance != null
247 | width: parent.width
248 | columns: 2
249 | rowSpacing: UM.Theme.getSize("default_lining").height
250 | verticalItemAlignment: Grid.AlignVCenter
251 | UM.Label
252 | {
253 | width: Math.floor(parent.width * 0.2)
254 | wrapMode: Text.WordWrap
255 | text: catalog.i18nc("@label", "Version")
256 | }
257 | UM.Label
258 | {
259 | width: Math.floor(parent.width * 0.75)
260 | wrapMode: Text.WordWrap
261 | text: base.selectedInstance ? base.selectedInstance.repetierVersion : ""
262 | }
263 | UM.Label
264 | {
265 | width: Math.floor(parent.width * 0.2)
266 | wrapMode: Text.WordWrap
267 | text: catalog.i18nc("@label", "Address")
268 | }
269 | UM.Label
270 | {
271 | width: Math.floor(parent.width * 0.7)
272 | wrapMode: Text.WordWrap
273 | text: base.selectedInstance ? "%1:%2".arg(base.selectedInstance.ipAddress).arg(String(base.selectedInstance.port)) : ""
274 | }
275 | UM.Label
276 | {
277 | width: Math.floor(parent.width * 0.2)
278 | wrapMode: Text.WordWrap
279 | text: catalog.i18nc("@label", "RepetierID")
280 | }
281 | UM.Label
282 | {
283 | id: lblRepID
284 | width: Math.floor(parent.width * 0.2)
285 | text: base.selectedInstance ? Cura.ContainerManager.getContainerMetaDataEntry(base.selectedInstance.name, "repetier_id") : ""
286 | }
287 | UM.Label
288 | {
289 | width: Math.floor(parent.width * 0.2)
290 | wrapMode: Text.WordWrap
291 | text: catalog.i18nc("@label", "API Key")
292 | }
293 | Cura.TextField
294 | {
295 | id: apiKey
296 | width: Math.floor(parent.width * 0.8 - UM.Theme.getSize("default_margin").width)
297 | text: base.selectedInstance ? Cura.ContainerManager.getContainerMetaDataEntry(base.selectedInstance.name, "repetier_api_key") : ""
298 | onTextChanged:
299 | {
300 | apiCheckDelay.throttledCheck()
301 | comboGroups.clear()
302 | }
303 | }
304 | Connections
305 | {
306 | target: base
307 | function onSelectedInstanceChanged()
308 | {
309 | if(base.selectedInstance != null)
310 | {
311 | lblRepID.text = Cura.ContainerManager.getContainerMetaDataEntry(base.selectedInstance.name, "repetier_id")
312 | apiKey.text = Cura.ContainerManager.getContainerMetaDataEntry(base.selectedInstance.name, "repetier_api_key")
313 | //apiKey.text = manager.getApiKey(base.selectedInstance.getId())
314 | }
315 | }
316 | }
317 | Timer
318 | {
319 | id: apiCheckDelay
320 | interval: 500
321 |
322 | property bool checkOnTrigger: false
323 |
324 | function throttledCheck()
325 | {
326 | if(running)
327 | {
328 | checkOnTrigger = true;
329 | }
330 | else
331 | {
332 | check();
333 | }
334 | }
335 | function check()
336 | {
337 | if(base.selectedInstance != null)
338 | if(base.selectedInstance.baseURL != null)
339 | {
340 | manager.testApiKey(base.selectedInstance.getId(),base.selectedInstance.baseURL, apiKey.text, base.selectedInstance.getProperty("userName"), base.selectedInstance.getProperty("password"), lblRepID.text);
341 | checkOnTrigger = false;
342 | restart();
343 | }
344 | }
345 | onTriggered:
346 | {
347 | if(checkOnTrigger)
348 | {
349 | check();
350 | }
351 | }
352 | }
353 | }
354 |
355 | UM.Label
356 | {
357 | visible: base.selectedInstance != null && text != ""
358 | text:
359 | {
360 | var result = ""
361 | if (apiKey.text == "")
362 | {
363 | result = catalog.i18nc("@label", "Please enter the API key to access Repetier.");
364 | }
365 | else
366 | {
367 | if(manager.instanceInError)
368 | {
369 | return catalog.i18nc("@label", "Repetier is not available.")
370 | }
371 | if(manager.instanceResponded)
372 | {
373 | if(manager.instanceApiKeyAccepted)
374 | {
375 | return "";
376 | }
377 | else
378 | {
379 | result = catalog.i18nc("@label", "The API key is not valid.");
380 | }
381 | }
382 | else
383 | {
384 | return catalog.i18nc("@label", "Repetier printer name hasn't been selected, please edit and click get printers and choose the correct name from the drop down list.")
385 | }
386 | }
387 | result += " " + catalog.i18nc("@label", "You can get the API key through the Repetier web page.");
388 | return result;
389 | }
390 | width: parent.width - UM.Theme.getSize("default_margin").width
391 | wrapMode: Text.WordWrap
392 | }
393 |
394 | Column
395 | {
396 | visible: base.selectedInstance != null
397 | width: parent.width
398 | spacing: UM.Theme.getSize("default_lining").height
399 |
400 | UM.CheckBox
401 | {
402 | id: autoPrintCheckBox
403 | text: catalog.i18nc("@label", "Automatically start print job after uploading")
404 | enabled: manager.instanceApiKeyAccepted
405 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_auto_print") != "false"
406 | onClicked:
407 | {
408 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_auto_print", String(checked))
409 | }
410 | }
411 | UM.CheckBox
412 | {
413 | id: storeAndPrintCheckBox
414 | text: catalog.i18nc("@label", "Store print job and print")
415 | enabled: manager.instanceApiKeyAccepted
416 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_print") != "false"
417 | onClicked:
418 | {
419 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_print", String(checked))
420 | }
421 | }
422 | Cura.ComboBox
423 | {
424 | id: comboGroupsctl
425 | property bool populatingModel: false
426 | textRole: "label"
427 | editable: false
428 | width: Math.floor(parent.width * 0.4)
429 |
430 | model: ListModel
431 | {
432 | id: comboGroups
433 |
434 | Component.onCompleted: populateModel()
435 |
436 | function populateModel()
437 | {
438 | comboGroupsctl.populatingModel = true;
439 | var add = true
440 | for (var i = 0; i < manager.getGroups.length; i++)
441 | {
442 | for (var m = 0; m < comboGroups.count; m++)
443 | {
444 | if(comboGroups.get(m).key==manager.getGroups[i])
445 | {
446 | add=false;
447 | }
448 | }
449 | if(add==true)
450 | {
451 | if(manager.getGroups[i] != "")
452 | {
453 | comboGroups.append({ label: catalog.i18nc("@action:ComboBox option", manager.getGroups[i]), key: manager.getGroups[i] });
454 | }
455 | }
456 | }
457 | var current_index = -1;
458 | if (Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_group") != undefined)
459 | {
460 | if (manager.getGroups.length > 0)
461 | for(var i = 0; i < manager.getGroups.length; i++)
462 | { if(comboGroups.get(i) != undefined)
463 | if(comboGroups.get(i).key == Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_group"))
464 | {
465 | current_index = i;
466 | }
467 | }
468 | }
469 | comboGroupsctl.currentIndex = current_index;
470 | comboGroupsctl.populatingModel = false;
471 | }
472 | }
473 | currentIndex:
474 | {
475 | if (( activeIndex !== undefined )&&( comboGroups !== undefined ))
476 | {
477 | var currentValue = comboGroups.model[activeIndex]
478 | var index = 0
479 | for(var i = 0; i < comboGroups.length; i++)
480 | {
481 | if ( typeof comboGroups.get(i).key !== undefined )
482 | if( comboGroups.get(i).key == currentValue ) {
483 | index = i
484 | break
485 | }
486 | }
487 | return index
488 | }
489 | }
490 | onCurrentIndexChanged:
491 | {
492 | if ( typeof comboGroups.get(currentIndex).key !== undefined )
493 | {
494 | currentText = comboGroups.get(currentIndex).key
495 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_group", currentText)
496 | }
497 | }
498 | }
499 | Timer
500 | {
501 | id: groupTimer
502 | interval: 500; running: true; repeat: true
503 |
504 | function check()
505 | {
506 | if(base.selectedInstance != null)
507 | {
508 | if ((base.selectedInstance.baseURL.trim() != "") && (apiKey.text.trim() != ""))
509 | {
510 | if (manager.getGroups != undefined)
511 | {
512 | if (manager.getGroups.length > 0)
513 | {
514 | comboGroups.populateModel();
515 | }
516 | }
517 | }
518 | }
519 | }
520 | onTriggered:
521 | {
522 | check();
523 | }
524 | }
525 | UM.CheckBox
526 | {
527 | id: showCameraCheckBox
528 | text: catalog.i18nc("@label", "Show webcam image")
529 | enabled: manager.instanceSupportsCamera
530 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_show_camera") == "true"
531 | onClicked:
532 | {
533 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_show_camera", String(checked))
534 | }
535 | }
536 | UM.CheckBox
537 | {
538 | id: flipYCheckBox
539 | text: catalog.i18nc("@label", "Flip Webcam Y")
540 | enabled: manager.instanceSupportsCamera
541 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamflip_y") == "true"
542 | onClicked:
543 | {
544 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamflip_y", String(checked))
545 | }
546 | }
547 | UM.CheckBox
548 | {
549 | id: flipXCheckBox
550 | text: catalog.i18nc("@label", "Flip Webcam X")
551 | enabled: manager.instanceSupportsCamera
552 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamflip_x") == "true"
553 | onClicked:
554 | {
555 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamflip_x", String(checked))
556 | }
557 | }
558 | UM.CheckBox
559 | {
560 | id: rot90CheckBox
561 | text: catalog.i18nc("@label", "Rotate Webcam 90")
562 | enabled: manager.instanceSupportsCamera
563 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamrot_90") == "true"
564 | onClicked:
565 | {
566 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamrot_90", String(checked))
567 | }
568 | }
569 | UM.CheckBox
570 | {
571 | id: rot180CheckBox
572 | text: catalog.i18nc("@label", "Rotate Webcam 180")
573 | enabled: manager.instanceSupportsCamera
574 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamrot_180") == "true"
575 | onClicked:
576 | {
577 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamrot_180", String(checked))
578 | }
579 | }
580 | UM.CheckBox
581 | {
582 | id: rot270CheckBox
583 | text: catalog.i18nc("@label", "Rotate Webcam 270")
584 | enabled: manager.instanceSupportsCamera
585 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamrot_270") == "true"
586 | onClicked:
587 | {
588 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_webcamrot_270", String(checked))
589 | }
590 | }
591 | UM.CheckBox
592 | {
593 | id: storeOnSdCheckBox
594 | text: catalog.i18nc("@label", "Store G-code on the printer SD card")
595 | enabled: manager.instanceSupportsSd
596 | checked: manager.instanceApiKeyAccepted && Cura.ContainerManager.getContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_sd") == "true"
597 | onClicked:
598 | {
599 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_store_sd", String(checked))
600 | }
601 | }
602 | UM.Label
603 | {
604 | visible: storeOnSdCheckBox.checked
605 | wrapMode: Text.WordWrap
606 | width: parent.width
607 | text: catalog.i18nc("@label", "Note: Transfering files to the printer SD card takes very long. Using this option is not recommended.")
608 | }
609 | UM.CheckBox
610 | {
611 | id: fixGcodeFlavor
612 | text: catalog.i18nc("@label", "Set Gcode flavor to \"Marlin\"")
613 | checked: true
614 | visible: machineGCodeFlavorProvider.properties.value == "UltiGCode"
615 | }
616 | UM.Label
617 | {
618 | text: catalog.i18nc("@label", "Note: Printing UltiGCode using Repetier does not work. Setting Gcode flavor to \"Marlin\" fixes this, but overrides material settings on your printer.")
619 | width: parent.width - UM.Theme.getSize("default_margin").width
620 | wrapMode: Text.WordWrap
621 | visible: fixGcodeFlavor.visible
622 | }
623 | }
624 |
625 | Flow
626 | {
627 | visible: base.selectedInstance != null
628 | spacing: UM.Theme.getSize("default_margin").width
629 |
630 | Cura.SecondaryButton
631 | {
632 | text: catalog.i18nc("@action", "Open in browser...")
633 | onClicked: manager.openWebPage(base.selectedInstance.baseURL)
634 | }
635 |
636 | Cura.SecondaryButton
637 | {
638 | text: catalog.i18nc("@action:button", "Connect")
639 | enabled: apiKey.text != "" && manager.instanceApiKeyAccepted
640 | onClicked:
641 | {
642 | if(fixGcodeFlavor.visible)
643 | {
644 | manager.applyGcodeFlavorFix(fixGcodeFlavor.checked)
645 | }
646 | manager.setInstanceId(base.selectedInstance.repetier_id)
647 | manager.setApiKey(apiKey.text)
648 | completed()
649 | }
650 | }
651 | }
652 | }
653 | }
654 | }
655 |
656 | UM.SettingPropertyProvider
657 | {
658 | id: machineGCodeFlavorProvider
659 |
660 | containerStackId: Cura.MachineManager.activeMachine.id
661 | key: "machine_gcode_flavor"
662 | watchedProperties: [ "value" ]
663 | storeIndex: 4
664 | }
665 |
666 | UM.Dialog
667 | {
668 | id: manualPrinterDialog
669 | property string oldName
670 | property alias nameText: nameField.text
671 | property alias addressText: addressField.text
672 | property alias portText: portField.text
673 | property alias pathText: pathField.text
674 | property alias userNameText: userNameField.text
675 | property alias passwordText: passwordField.text
676 | property alias repidText: repid.editText
677 | property alias selrepidText: repid.currentText
678 |
679 | title: catalog.i18nc("@title:window", "Manually added Repetier instance")
680 |
681 | minimumWidth: 400 * screenScaleFactor
682 | minimumHeight: (showAdvancedOptions.checked ? 340 : 220) * screenScaleFactor
683 | width: minimumWidth
684 | height: minimumHeight
685 |
686 | signal showDialog(string name, string address, string port, string path_, bool useHttps, string userName, string password, string repetierid)
687 | onShowDialog:
688 | {
689 | oldName = name;
690 | nameText = name;
691 | nameField.selectAll();
692 | nameField.focus = true;
693 |
694 | addressText = address;
695 | portText = port;
696 | pathText = path_;
697 | httpsCheckbox.checked = useHttps;
698 | userNameText = userName;
699 | passwordText = password;
700 | repidText = repetierid;
701 | manualPrinterDialog.show();
702 | }
703 |
704 | onAccepted:
705 | {
706 | if(oldName != nameText)
707 | {
708 | manager.removeManualInstance(oldName);
709 | }
710 | if(portText == "")
711 | {
712 | portText = "3344" // default http port
713 | }
714 | if(pathText.substr(0,1) != "/")
715 | {
716 | pathText = "/" + pathText // ensure absolute path
717 | }
718 | manager.setManualInstance(nameText, addressText, parseInt(portText), pathText, httpsCheckbox.checked, userNameText, passwordText, repidText)
719 | manager.setContainerMetaDataEntry(Cura.MachineManager.activeMachine.id, "repetier_id", repidText)
720 | }
721 |
722 | Column {
723 | anchors.fill: parent
724 | spacing: UM.Theme.getSize("default_margin").height
725 |
726 | Grid
727 | {
728 | columns: 2
729 | width: parent.width
730 | verticalItemAlignment: Grid.AlignVCenter
731 | rowSpacing: UM.Theme.getSize("default_lining").height
732 |
733 | UM.Label
734 | {
735 | text: catalog.i18nc("@label","Instance Name")
736 | width: Math.floor(parent.width * 0.4)
737 | }
738 |
739 | Cura.TextField
740 | {
741 | id: nameField
742 | maximumLength: 20
743 | width: Math.floor(parent.width * 0.6)
744 | }
745 |
746 | UM.Label
747 | {
748 | text: catalog.i18nc("@label","IP Address or Hostname")
749 | width: Math.floor(parent.width * 0.4)
750 | }
751 |
752 | Cura.TextField
753 | {
754 | id: addressField
755 | maximumLength: 253
756 | width: Math.floor(parent.width * 0.6)
757 | }
758 |
759 | UM.Label
760 | {
761 | text: catalog.i18nc("@label","Port Number")
762 | width: Math.floor(parent.width * 0.4)
763 | }
764 |
765 | Cura.TextField
766 | {
767 | id: portField
768 | maximumLength: 5
769 | width: Math.floor(parent.width * 0.6)
770 | }
771 | UM.Label
772 | {
773 | text: catalog.i18nc("@label","Path")
774 | width: Math.floor(parent.width * 0.4)
775 | }
776 |
777 | Cura.TextField
778 | {
779 | id: pathField
780 | maximumLength: 30
781 | width: Math.floor(parent.width * 0.6)
782 | }
783 | Cura.SecondaryButton
784 | {
785 | text: catalog.i18nc("@action:button","Get Printers")
786 | onClicked:
787 | {
788 | manager.getPrinterList("http://" + manualPrinterDialog.addressText.trim()+":"+manualPrinterDialog.portText.trim()+"/")
789 | if (manager.getPrinters.length>0)
790 | {
791 | comboPrinters.clear()
792 | for (var i =0;i
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/NetworkMJPGImage.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView & Shane Bumpurs
2 | # NetworkMJPGImage is released under the terms of the LGPLv3 or higher.
3 |
4 | from PyQt6.QtCore import QUrl, pyqtProperty, pyqtSignal, pyqtSlot, QRect, QByteArray
5 | from PyQt6.QtGui import QImage, QPainter
6 | from PyQt6.QtQuick import QQuickPaintedItem
7 | from PyQt6.QtNetwork import QNetworkRequest, QNetworkReply, QNetworkAccessManager
8 |
9 | from UM.Logger import Logger
10 |
11 | #
12 | # A QQuickPaintedItem that progressively downloads a network mjpeg stream,
13 | # picks it apart in individual jpeg frames, and paints it.
14 | #
15 | class NetworkMJPGImage(QQuickPaintedItem):
16 |
17 | def __init__(self, *args, **kwargs) -> None:
18 | super().__init__(*args, **kwargs)
19 |
20 | self._stream_buffer = QByteArray()
21 | self._stream_buffer_start_index = -1
22 | self._network_manager = None # type: QNetworkAccessManager
23 | self._image_request = None # type: QNetworkRequest
24 | self._image_reply = None # type: QNetworkReply
25 | self._image = QImage()
26 | self._image_rect = QRect()
27 |
28 | self._source_url = QUrl()
29 | self._started = False
30 |
31 | self._mirror = False
32 |
33 | self.setAntialiasing(True)
34 |
35 | ## Ensure that close gets called when object is destroyed
36 | def __del__(self) -> None:
37 | self.stop()
38 |
39 |
40 | def paint(self, painter: "QPainter") -> None:
41 | if self._mirror:
42 | painter.drawImage(self.contentsBoundingRect(), self._image.mirrored())
43 | return
44 |
45 | painter.drawImage(self.contentsBoundingRect(), self._image)
46 |
47 |
48 | def setSourceURL(self, source_url: "QUrl") -> None:
49 | self._source_url = source_url
50 | self.sourceURLChanged.emit()
51 | if self._started:
52 | self.start()
53 |
54 | def getSourceURL(self) -> "QUrl":
55 | return self._source_url
56 |
57 | sourceURLChanged = pyqtSignal()
58 | source = pyqtProperty(QUrl, fget = getSourceURL, fset = setSourceURL, notify = sourceURLChanged)
59 |
60 | def setMirror(self, mirror: bool) -> None:
61 | if mirror == self._mirror:
62 | return
63 | self._mirror = mirror
64 | self.mirrorChanged.emit()
65 | self.update()
66 |
67 | def getMirror(self) -> bool:
68 | return self._mirror
69 |
70 | mirrorChanged = pyqtSignal()
71 | mirror = pyqtProperty(bool, fget = getMirror, fset = setMirror, notify = mirrorChanged)
72 |
73 | imageSizeChanged = pyqtSignal()
74 |
75 | @pyqtProperty(int, notify = imageSizeChanged)
76 | def imageWidth(self) -> int:
77 | return self._image.width()
78 |
79 | @pyqtProperty(int, notify = imageSizeChanged)
80 | def imageHeight(self) -> int:
81 | return self._image.height()
82 |
83 |
84 | @pyqtSlot()
85 | def start(self) -> None:
86 | self.stop() # Ensure that previous requests (if any) are stopped.
87 |
88 | if not self._source_url:
89 | Logger.log("w", "Unable to start camera stream without target!")
90 | return
91 | self._started = True
92 | Logger.log("w", "MJPEG starting stream...")
93 | self._image_request = QNetworkRequest(self._source_url)
94 | if self._network_manager is None:
95 | self._network_manager = QNetworkAccessManager()
96 |
97 | self._image_reply = self._network_manager.get(self._image_request)
98 | self._image_reply.downloadProgress.connect(self._onStreamDownloadProgress)
99 |
100 | @pyqtSlot()
101 | def stop(self) -> None:
102 | Logger.log("w", "MJPEG stopping stream...")
103 | self._stream_buffer = QByteArray()
104 | self._stream_buffer_start_index = -1
105 |
106 | if self._image_reply:
107 | try:
108 | try:
109 | self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
110 | except Exception:
111 | pass
112 |
113 | if not self._image_reply.isFinished():
114 | self._image_reply.close()
115 | except Exception as e: # RuntimeError
116 | pass # It can happen that the wrapped c++ object is already deleted.
117 |
118 | self._image_reply = None
119 | self._image_request = None
120 |
121 | self._network_manager = None
122 |
123 | self._started = False
124 |
125 |
126 | def _onStreamDownloadProgress(self, bytes_received: int, bytes_total: int) -> None:
127 | # An MJPG stream is (for our purpose) a stream of concatenated JPG images.
128 | # JPG images start with the marker 0xFFD8, and end with 0xFFD9
129 | if self._image_reply is None:
130 | return
131 | self._stream_buffer += self._image_reply.readAll()
132 | # if len(self._stream_buffer) > 2000000: # No single camera frame should be 2 Mb or larger
133 | # Logger.log("w", "MJPEG buffer exceeds reasonable size. Restarting stream...%d",len(self._stream_buffer))
134 | # self.stop() # resets stream buffer and start index
135 | # self.start()
136 | # return
137 |
138 | if self._stream_buffer_start_index == -1:
139 | self._stream_buffer_start_index = self._stream_buffer.indexOf(b'\xff\xd8')
140 | stream_buffer_end_index = self._stream_buffer.lastIndexOf(b'\xff\xd9')
141 | # If this happens to be more than a single frame, then so be it; the JPG decoder will
142 | # ignore the extra data. We do it like this in order not to get a buildup of frames
143 |
144 | if self._stream_buffer_start_index != -1 and stream_buffer_end_index != -1:
145 | jpg_data = self._stream_buffer[self._stream_buffer_start_index:stream_buffer_end_index + 2]
146 | self._stream_buffer = self._stream_buffer[stream_buffer_end_index + 2:]
147 | self._stream_buffer_start_index = -1
148 | self._image.loadFromData(jpg_data)
149 |
150 | if self._image.rect() != self._image_rect:
151 | self.imageSizeChanged.emit()
152 |
153 | self.update()
154 |
--------------------------------------------------------------------------------
/NetworkReplyTimeout.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView
2 | # NetworkReplyTimeout is released under the terms of the AGPLv3 or higher.
3 |
4 | from PyQt6.QtCore import QObject, QTimer
5 | from PyQt6.QtNetwork import QNetworkReply
6 |
7 | from UM.Signal import Signal
8 |
9 | from typing import Optional, Callable
10 |
11 | #
12 | # A timer that is started when a QNetworkRequest returns a QNetworkReply, which closes the
13 | # QNetworkReply does not reply in a timely manner
14 | #
15 | class NetworkReplyTimeout(QObject):
16 | timeout = Signal()
17 |
18 | def __init__(self, reply: QNetworkReply, timeout: int,
19 | callback: Optional[Callable[[QNetworkReply], None]] = None) -> None:
20 | super().__init__()
21 |
22 | self._reply = reply
23 | self._callback = callback
24 |
25 | self._timer = QTimer()
26 | self._timer.setInterval(timeout)
27 | self._timer.setSingleShot(True)
28 | self._timer.timeout.connect(self._onTimeout)
29 |
30 | self._timer.start()
31 |
32 | def _onTimeout(self):
33 | if self._reply.isRunning():
34 | self._reply.abort()
35 | if self._callback:
36 | self._callback(self._reply)
37 | self.timeout.emit(self._reply)
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RepetierIntegration
2 | # Version 5.1
3 | Shane Bumpurs
4 |
5 | Cura plugin which enables printing directly to Repetier and monitoring the progress
6 | The name has changed to RepetierIntegration in the plugin folder.
7 | This plugin is basically a copy of the Octoprint plugin with the necessary changes to work with repetier server.
8 | Updated to 5.1, this version will not work with 5.0+.
9 |
10 | Installation
11 | ----
12 | * Manually:
13 | - Make sure your Cura version is 5.0+
14 | - Download or clone the repository into [Cura installation folder]/plugins/RepetierIntegration
15 | or in the plugins folder inside the configuration folder. The configuration folder can be
16 | found via Help -> Show Configuration Folder inside Cura.
17 | NB: The folder of the plugin itself *must* be ```RepetierIntegration```
18 | NB: Make sure you download the branch that matches the Cura branch (ie: 3.1 for Cura 2.2-3.1, 3.2 for Cura 3.2, 3.3 for Cura 3.3 etc)
19 |
20 | Blurry Youtube Video showing Install
21 | https://youtu.be/VHw93Pt_QIo
22 |
23 | How to use
24 | ----
25 | - Make sure Repetier is up and running
26 | - In Cura, under Manage printers select your printer.
27 | - Select "Connect to Repetier" on the Manage Printers page.
28 | - Click add and **make sure you match the Name you give it in the plugin, with the name of the Printer in Cura.**
29 | - Fill in the IP and Port, if you have security turned on, click the advanced checkbox and enter that information
30 | - Click Get Printers button, it should populate the dropdown to select your repetier printer.
31 | - Click OK this will show the printer in the Printers list again but then ask for your Repetier API key. Once that is filled you can check the extra options if you have a webcam and need to rotate it.
32 | - If you do not want to print immediately but have your print job stored uncheck "Automatically start print job after uploading"
33 | - From this point on, the print monitor should be functional and you should be able to switch to "Print to Repetier" on the bottom of the sidebar.
34 |
35 | Config example:
36 | 
37 |
38 | Cura has a bug so that if you have ever renamed your printer this plugin won't work. You'll have to create a new printer from scratch.
39 |
40 |
--------------------------------------------------------------------------------
/RepetierComponents.qml:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Aldo Hoeben / fieldOfView & Shane Bumpurs
2 | // OctoPrintPlugin is released under the terms of the AGPLv3 or higher.
3 |
4 | import UM 1.2 as UM
5 | import Cura 1.0 as Cura
6 |
7 | import QtQuick 2.2
8 | import QtQuick.Controls 2.0
9 |
10 | Item
11 | {
12 | id: base
13 |
14 | property bool printerConnected: Cura.MachineManager.printerOutputDevices.length != 0
15 | property bool repetierConnected: printerConnected && Cura.MachineManager.printerOutputDevices[0].hasOwnProperty("repetierVersion")
16 |
17 | Cura.SecondaryButton
18 | {
19 | objectName: "openRepetierButton"
20 | height: UM.Theme.getSize("save_button_save_to_button").height
21 | tooltip: catalog.i18nc("@info:tooltip", "Open the Repetier web interface")
22 | text: catalog.i18nc("@action:button", "Open Repetier...")
23 | onClicked: manager.openWebPage(Cura.MachineManager.printerOutputDevices[0].baseURL)
24 | visible: repetierConnected
25 | }
26 |
27 | UM.I18nCatalog{id: catalog; name:"repetier"}
28 | }
--------------------------------------------------------------------------------
/RepetierOutputDevice.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView & Shane Bumpurs
2 | # RepetierPlugin is released under the terms of the AGPLv3 or higher.
3 |
4 | from UM.i18n import i18nCatalog
5 | from UM.Logger import Logger
6 | from UM.Signal import signalemitter
7 | from UM.Message import Message
8 | from UM.Util import parseBool
9 | from UM.Mesh.MeshWriter import MeshWriter
10 | from UM.PluginRegistry import PluginRegistry
11 |
12 | from cura.CuraApplication import CuraApplication
13 |
14 | from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
15 | from cura.PrinterOutput.NetworkedPrinterOutputDevice import NetworkedPrinterOutputDevice
16 | from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
17 | from cura.PrinterOutput.Models.PrintJobOutputModel import PrintJobOutputModel
18 |
19 | from cura.PrinterOutput.GenericOutputController import GenericOutputController
20 |
21 | from PyQt6.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager
22 | from PyQt6.QtNetwork import QNetworkReply, QSslConfiguration, QSslSocket
23 | from PyQt6.QtCore import QUrl, QTimer, pyqtSignal, pyqtProperty, pyqtSlot, QCoreApplication
24 | from PyQt6.QtGui import QImage, QDesktopServices
25 |
26 | QNetworkAccessManagerOperations = QNetworkAccessManager.Operation
27 | QNetworkRequestKnownHeaders = QNetworkRequest.KnownHeaders
28 | QNetworkRequestAttributes = QNetworkRequest.Attribute
29 | QNetworkReplyNetworkErrors = QNetworkReply.NetworkError
30 | QSslSocketPeerVerifyModes = QSslSocket.PeerVerifyMode
31 |
32 | import json
33 | import os.path
34 | import re
35 | import datetime
36 | from time import time
37 | import base64
38 | from io import StringIO, BytesIO
39 | from enum import IntEnum
40 |
41 | from typing import cast, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
42 | if TYPE_CHECKING:
43 | from UM.Scene.SceneNode import SceneNode #For typing.
44 | from UM.FileHandler.FileHandler import FileHandler #For typing.
45 |
46 | i18n_catalog = i18nCatalog("cura")
47 |
48 | # The current processing state of the backend.
49 | # This shadows PrinterOutputDevice.ConnectionState because its spelling changed
50 | # between Cura 4.0 beta 1 and beta 2
51 | class UnifiedConnectionState(IntEnum):
52 | try:
53 | Closed = ConnectionState.Closed
54 | Connecting = ConnectionState.Connecting
55 | Connected = ConnectionState.Connected
56 | Busy = ConnectionState.Busy
57 | Error = ConnectionState.Error
58 | except AttributeError:
59 | Closed = ConnectionState.closed # type: ignore
60 | Connecting = ConnectionState.connecting # type: ignore
61 | Connected = ConnectionState.connected # type: ignore
62 | Busy = ConnectionState.busy # type: ignore
63 | Error = ConnectionState.error # type: ignore
64 | # Repetier connected (wifi / lan) printer using the Repetier API
65 | @signalemitter
66 | class RepetierOutputDevice(NetworkedPrinterOutputDevice):
67 | def __init__(
68 | self, instance_id: str, address: str, port: int, properties: dict, **kwargs
69 | ) -> None:
70 | super().__init__(
71 | device_id=instance_id, address=address, properties=properties, **kwargs
72 | )
73 |
74 | self._address = address
75 | self._port = port
76 | self._path = properties.get(b"path", b"/").decode("utf-8")
77 | if self._path[-1:] != "/":
78 | self._path += "/"
79 | self._id = instance_id
80 | self._repetier_id = properties.get(b"repetier_id", b"").decode("utf-8")
81 | self._properties = properties # Properties dict as provided by zero conf
82 |
83 | self._printer_model = ""
84 | self._printer_name = ""
85 | self._gcode_stream = StringIO()
86 |
87 | self._auto_print = True
88 | self._store_print = False
89 | self._forced_queue = False
90 |
91 | # We start with a single extruder, but update this when we get data from Repetier
92 | self._number_of_extruders_set = False
93 | self._number_of_extruders = 1
94 |
95 | # Try to get version information from plugin.json
96 | plugin_file_path = os.path.join(
97 | os.path.dirname(os.path.abspath(__file__)), "plugin.json"
98 | )
99 | try:
100 | with open(plugin_file_path) as plugin_file:
101 | plugin_info = json.load(plugin_file)
102 | plugin_version = plugin_info["version"]
103 | except:
104 | # The actual version info is not critical to have so we can continue
105 | plugin_version = "Unknown"
106 | Logger.logException("w", "Could not get version information for the plugin")
107 |
108 | self._user_agent_header = "User-Agent".encode()
109 | self._user_agent = ("%s/%s %s/%s" % (
110 | CuraApplication.getInstance().getApplicationName(),
111 | CuraApplication.getInstance().getVersion(),
112 | "RepetierIntegration",
113 | plugin_version
114 | ))
115 | Logger.log("d", "Repetier_ID: %s", self._repetier_id)
116 | self._api_prefix = "printer/api/" + self._repetier_id
117 | self._job_prefix = "printer/job/" + self._repetier_id
118 | self._save_prefix = "printer/model/" + self._repetier_id
119 | self._api_header = "x-api-key".encode()
120 | self._api_key = b""
121 |
122 | self._protocol = "https" if properties.get(b'useHttps') == b"true" else "http"
123 | self._base_url = "%s://%s:%d%s" % (
124 | self._protocol,
125 | self._address,
126 | self._port,
127 | self._path,
128 | )
129 | self._api_url = self._base_url + self._api_prefix
130 | self._job_url = self._base_url + self._job_prefix
131 | self._save_url = self._base_url + self._save_prefix
132 |
133 | self._basic_auth_header = "Authorization".encode()
134 | self._basic_auth_data = None
135 | basic_auth_username = properties.get(b"userName", b"").decode("utf-8")
136 | basic_auth_password = properties.get(b"password", b"").decode("utf-8")
137 | if basic_auth_username and basic_auth_password:
138 | data = base64.b64encode(
139 | ("%s:%s" % (basic_auth_username, basic_auth_password)).encode()
140 | ).decode("utf-8")
141 | self._basic_auth_data = ("basic %s" % data).encode()
142 |
143 | # self._monitor_view_qml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "MonitorItem.qml")
144 | self._monitor_view_qml_path = os.path.join(
145 | os.path.dirname(os.path.abspath(__file__)), "qml", "MonitorItem.qml"
146 | )
147 |
148 | name = self._id
149 | matches = re.search(r"^\"(.*)\"\._Repetier\._tcp.local$", name)
150 | if matches:
151 | name = matches.group(1)
152 | Logger.log("d", "NAME IS: %s", name)
153 | Logger.log("d", "ADDRESS IS: %s", self._address)
154 | self.setPriority(2) # Make sure the output device gets selected above local file output
155 | self.setName(name)
156 | self.setShortDescription(i18n_catalog.i18nc("@action:button", "Print with Repetier"))
157 | self.setDescription(i18n_catalog.i18nc("@properties:tooltip", "Print with Repetier"))
158 | self.setIconName("print")
159 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected to Repetier on {0}").format(self._repetier_id))
160 |
161 | self._post_reply = None
162 |
163 | self._progress_message = None # type: Union[None, Message]
164 | self._error_message = None # type: Union[None, Message]
165 | self._connection_message = None # type: Union[None, Message]
166 |
167 | self._queued_gcode_commands = [] # type: List[str]
168 | self._queued_gcode_timer = QTimer()
169 | self._queued_gcode_timer.setInterval(0)
170 | self._queued_gcode_timer.setSingleShot(True)
171 | self._queued_gcode_timer.timeout.connect(self._sendQueuedGcode)
172 |
173 | self._update_timer = QTimer()
174 | self._update_timer.setInterval(2000) # TODO; Add preference for update interval
175 | self._update_timer.setSingleShot(False)
176 | self._update_timer.timeout.connect(self._update)
177 |
178 | self._show_camera = True
179 | self._camera_mirror = False
180 | self._camera_rotation = 0
181 | self._camera_url = ""
182 | self._camera_shares_proxy = False
183 |
184 | self._sd_supported = False
185 |
186 | self._plugin_data = {} #type: Dict[str, Any]
187 |
188 | self._output_controller = GenericOutputController(self)
189 |
190 | def getProperties(self) -> Dict[bytes, bytes]:
191 | return self._properties
192 |
193 | @pyqtSlot(str, result = str)
194 | def getProperty(self, key: str) -> str:
195 | key_b = key.encode("utf-8")
196 | if key_b in self._properties:
197 | return self._properties.get(key_b, b"").decode("utf-8")
198 | else:
199 | return ""
200 |
201 | # Get the unique key of this machine
202 | # \return key String containing the key of the machine.
203 | @pyqtSlot(result = str)
204 | def getId(self) -> str:
205 | return self._id
206 |
207 | # Set the API key of this Repetier instance
208 | def setApiKey(self, api_key: str) -> None:
209 | self._api_key = api_key.encode()
210 |
211 | # Name of the instance (as returned from the zeroConf properties)
212 | @pyqtProperty(str, constant=True)
213 | def name(self) -> str:
214 | return self._name
215 |
216 | # Name of the printer in repetier
217 | additionalDataChanged = pyqtSignal()
218 | @pyqtProperty(str, notify=additionalDataChanged)
219 | def RepetierVersion(self) -> str:
220 | return self._repetier_version
221 |
222 | @pyqtProperty(str, constant = True)
223 | def repetier_id(self) -> str:
224 | return self._repetier_id
225 |
226 | def setRepetierid(self, strid: str) -> None:
227 | Logger.log("d", strid)
228 | self._repetier_id=strid
229 |
230 | # Version (as returned from the zeroConf properties)
231 | @pyqtProperty(str, constant=True)
232 | def repetierVersion(self) -> str:
233 | return self._properties.get(b"version", b"").decode("utf-8")
234 |
235 | # IPadress of this instance
236 | @pyqtProperty(str, constant=True)
237 | def ipAddress(self) -> str:
238 | return self._address
239 |
240 | # IP address of this instance
241 | @pyqtProperty(str, notify=additionalDataChanged)
242 | def address(self) -> str:
243 | return self._address
244 |
245 | # port of this instance
246 | @pyqtProperty(int, constant=True)
247 | def port(self) -> int:
248 | return self._port
249 |
250 | # path of this instance
251 | @pyqtProperty(str, constant=True)
252 | def path(self) -> str:
253 | return self._path
254 |
255 | # absolute url of this instance
256 | @pyqtProperty(str, constant=True)
257 | def baseURL(self) -> str:
258 | return self._base_url
259 |
260 | cameraOrientationChanged = pyqtSignal()
261 |
262 | @pyqtProperty("QVariantMap", notify = cameraOrientationChanged)
263 | def cameraOrientation(self) -> Dict[str, Any]:
264 | return {
265 | "mirror": self._camera_mirror,
266 | "rotation": self._camera_rotation,
267 | }
268 |
269 | cameraUrlChanged = pyqtSignal()
270 |
271 | @pyqtProperty("QUrl", notify = cameraUrlChanged)
272 | def cameraUrl(self) -> QUrl:
273 | return QUrl(self._camera_url)
274 |
275 | def setShowCamera(self, show_camera: bool) -> None:
276 | if show_camera != self._show_camera:
277 | self._show_camera = show_camera
278 | self.showCameraChanged.emit()
279 |
280 | showCameraChanged = pyqtSignal()
281 |
282 | @pyqtProperty(bool, notify = showCameraChanged)
283 | def showCamera(self) -> bool:
284 | return self._show_camera
285 |
286 | def _update(self) -> None:
287 | # Request 'general' printer data
288 | self.get("stateList", self._onRequestFinished)
289 | # Request print_job data
290 | self.get("listPrinter", self._onRequestFinished)
291 | # Request print_job data
292 | #self.get("getPrinterConfig", self._onRequestFinished)
293 |
294 |
295 |
296 | def close(self) -> None:
297 | self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Closed))
298 | if self._progress_message:
299 | self._progress_message.hide()
300 | if self._error_message:
301 | self._error_message.hide()
302 | self._update_timer.stop()
303 |
304 | def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False, file_handler: Optional["FileHandler"] = None, **kwargs: str) -> None:
305 | self.writeStarted.emit(self)
306 |
307 | # Get the g-code through the GCodeWriter plugin
308 | # This produces the same output as "Save to File", adding the print settings to the bottom of the file
309 | gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
310 | if not gcode_writer.write(self._gcode_stream, None):
311 | Logger.log("e", "GCodeWrite failed: %s" % gcode_writer.getInformation())
312 | return
313 | global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
314 | if not global_container_stack or not self.activePrinter:
315 | Logger.log("e", "There is no active printer to send the print")
316 | return
317 | self.startPrint()
318 |
319 | ## Start requesting data from the instance
320 | def connect(self) -> None:
321 | self._createNetworkManager()
322 |
323 | self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Connecting))
324 | self._update() # Manually trigger the first update, as we don't want to wait a few secs before it starts.
325 | Logger.log("d", "Connection with instance %s with url %s started", self._repetier_id, self._base_url)
326 | self._update_timer.start()
327 |
328 | self._last_response_time = None
329 | self._setAcceptsCommands(False)
330 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connecting to Repetier on {0}").format(self._base_url))
331 |
332 | ## Request 'settings' dump
333 | self.get("getPrinterConfig", self._onRequestFinished)
334 | self._settings_reply = self._manager.get(self._createEmptyRequest("getPrinterConfig"))
335 | self._settings_reply = self._manager.get(self._createEmptyRequest("stateList"))
336 |
337 | ## Stop requesting data from the instance
338 | def disconnect(self) -> None:
339 | Logger.log("d", "Connection with instance %s with url %s stopped", self._repetier_id, self._base_url)
340 | self.close()
341 |
342 | def pausePrint(self) -> None:
343 | self._sendJobCommand("pause")
344 |
345 | def resumePrint(self) -> None:
346 | if not self._printers[0].activePrintJob:
347 | return
348 | #Logger.log("d", "Resume attempted: %s ", self._printers[0].activePrintJob.state)
349 | if self._printers[0].activePrintJob.state == "paused":
350 | self._sendJobCommand("start")
351 | else:
352 | self._sendJobCommand("pause")
353 |
354 | def cancelPrint(self) -> None:
355 | self._sendJobCommand("cancel")
356 |
357 | def startPrint(self) -> None:
358 | global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
359 | if not global_container_stack:
360 | return
361 |
362 | if self._error_message:
363 | self._error_message.hide()
364 | self._error_message = None
365 |
366 | if self._progress_message:
367 | self._progress_message.hide()
368 | self._progress_message = None
369 |
370 | self._auto_print = parseBool(global_container_stack.getMetaDataEntry("repetier_auto_print", True))
371 | self._store_print = parseBool(global_container_stack.getMetaDataEntry("repetier_store_print", False))
372 | self._store_group = global_container_stack.getMetaDataEntry("repetier_store_group","#")
373 | self._forced_queue = False
374 |
375 | if self.activePrinter.state not in ["idle", ""]:
376 | Logger.log("d", "Tried starting a print, but current state is %s" % self.activePrinter.state)
377 | error_string = ""
378 | if not self._auto_print:
379 | # allow queueing the job even if Repetier is currently busy if autoprinting is disabled
380 | self._error_message = None
381 | elif self.activePrinter.state == "offline":
382 | error_string = Message(i18n_catalog.i18nc("@info:status", "The printer is offline. Unable to start a new job."))
383 | else:
384 | error_string = Message(i18n_catalog.i18nc("@info:status", "Repetier is busy. Unable to start a new job."))
385 |
386 | if error_string:
387 | if self._error_message:
388 | self._error_message.hide()
389 | self._error_message = Message(error_string, title=i18n_catalog.i18nc("@label", "Repetier error"))
390 | self._error_message.addAction(
391 | "queue", i18n_catalog.i18nc("@action:button", "Queue job"), "",
392 | i18n_catalog.i18nc("@action:tooltip", "Queue this print job so it can be printed later")
393 | )
394 | self._error_message.actionTriggered.connect(self._queuePrint)
395 | self._error_message.show()
396 | return
397 |
398 | self._startPrint()
399 |
400 | def _stopWaitingForAnalysis(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
401 | if self._waiting_message:
402 | self._waiting_message.hide()
403 | self._waiting_for_analysis = False
404 |
405 | for end_point in self._polling_end_points:
406 | if "files/" in end_point:
407 | break
408 | if "files/" not in end_point:
409 | Logger.log("e", "Could not find files/ endpoint")
410 | return
411 |
412 | self._polling_end_points = [point for point in self._polling_end_points if not point.startswith("files/")]
413 |
414 | if action_id == "print":
415 | self._selectAndPrint(end_point)
416 | elif action_id == "cancel":
417 | pass
418 |
419 | def _stopWaitingForPrinter(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
420 | if self._waiting_message:
421 | self._waiting_message.hide()
422 | self._waiting_for_printer = False
423 |
424 | if action_id == "queue":
425 | self._queuePrint()
426 | elif action_id == "cancel":
427 | self._gcode_stream = StringIO() # type: Union[StringIO, BytesIO]
428 |
429 | def _queuePrint(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
430 | if self._error_message:
431 | self._error_message.hide()
432 | self._forced_queue = True
433 | self._startPrint()
434 |
435 | def _startPrint(self) -> None:
436 | global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
437 | if not global_container_stack:
438 | return
439 |
440 | if self._auto_print and not self._forced_queue:
441 | CuraApplication.getInstance().getController().setActiveStage("MonitorStage")
442 |
443 | # cancel any ongoing preheat timer before starting a print
444 | try:
445 | self._printers[0].stopPreheatTimers()
446 | except AttributeError:
447 | # stopPreheatTimers was added after Cura 3.3 beta
448 | pass
449 |
450 | self._progress_message = Message(
451 | i18n_catalog.i18nc("@info:status", "Sending data to Repetier"),
452 | title=i18n_catalog.i18nc("@label", "Repetier"),
453 | progress=-1, lifetime=0, dismissable=False, use_inactivity_timer=False
454 | )
455 | self._progress_message.addAction(
456 | "cancel", i18n_catalog.i18nc("@action:button", "Cancel"), "",
457 | i18n_catalog.i18nc("@action:tooltip", "Abort the printjob")
458 | )
459 | self._progress_message.actionTriggered.connect(self._cancelSendGcode)
460 | self._progress_message.show()
461 |
462 | job_name = CuraApplication.getInstance().getPrintInformation().jobName.strip()
463 | Logger.log("d", "Print job: [%s]", job_name)
464 | if job_name == "":
465 | job_name = "untitled_print"
466 | file_name = "%s.gcode" % job_name
467 |
468 | ## Create multi_part request
469 | post_parts = [] # type: List[QHttpPart]
470 |
471 | ## Create parts (to be placed inside multipart)
472 | post_part = QHttpPart()
473 | # post_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"a\"")
474 | post_part.setHeader(QNetworkRequestKnownHeaders.ContentDispositionHeader, "form-data; name=\"a\"")
475 | post_part.setBody(b"upload")
476 | post_parts.append(post_part)
477 |
478 | if self._auto_print and not self._forced_queue:
479 | post_part = QHttpPart()
480 | # post_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"%s\"" % file_name)
481 | post_part.setHeader(QNetworkRequestKnownHeaders.ContentDispositionHeader, "form-data; name=\"%s\"" % file_name)
482 | post_part.setBody(b"upload")
483 | post_parts.append(post_part)
484 |
485 | post_part = QHttpPart()
486 | # post_part.setHeader(QNetworkRequest.ContentDispositionHeader, "form-data; name=\"file\"; filename=\"%s\"" % file_name)
487 | post_part.setHeader(QNetworkRequestKnownHeaders.ContentDispositionHeader, "form-data; name=\"file\"; filename=\"%s\"" % file_name)
488 | post_part.setBody(self._gcode_stream.getvalue().encode())
489 | post_parts.append(post_part)
490 |
491 | destination = "local"
492 | if self._sd_supported and parseBool(global_container_stack.getMetaDataEntry("Repetier_store_sd", False)):
493 | destination = "sdcard"
494 |
495 | try:
496 | # Post request + data
497 | #post_request = self._createApiRequest("files/" + destination)
498 | #post_request = self._createEmptyRequest("upload&name=%s" % file_name)
499 | Logger.log("d", "_store_print: %s" % self._store_print)
500 | Logger.log("d", "_store_group: %s" % self._store_group)
501 | if self._store_print:
502 | Logger.log("d", "upload&name=%s&group=%s" % (file_name,self._store_group))
503 | self._post_reply = self.postFormWithParts("upload&name=%s&group=%s" % (file_name,self._store_group), post_parts, on_finished=self._onUploadFinished, on_progress=self._onUploadProgress)
504 | else:
505 | Logger.log("d", "upload&name=%s" % file_name)
506 | self._post_reply = self.postFormWithParts("upload&name=%s" % file_name, post_parts, on_finished=self._onUploadFinished, on_progress=self._onUploadProgress)
507 |
508 | #self._post_reply = self._manager.post(post_request, self._post_multi_part)
509 | #self._post_reply.uploadProgress.connect(self._onUploadProgress)
510 |
511 |
512 | except Exception as e:
513 | self._progress_message.hide()
514 | self._error_message = Message(
515 | i18n_catalog.i18nc("@info:status", "Unable to send data to Repetier."),
516 | title=i18n_catalog.i18nc("@label", "Repetier error")
517 | )
518 | self._error_message.show()
519 | Logger.log("e", "An exception occurred in network connection: %s" % str(e))
520 |
521 | self._gcode_stream = StringIO()
522 |
523 | def _cancelSendGcode(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
524 | if self._post_reply:
525 | Logger.log("d", "Stopping upload because the user pressed cancel.")
526 | try:
527 | self._post_reply.uploadProgress.disconnect(self._onUploadProgress)
528 | except TypeError:
529 | pass # The disconnection can fail on mac in some cases. Ignore that.
530 |
531 | self._post_reply.abort()
532 | self._post_reply = None
533 | if self._progress_message:
534 | self._progress_message.hide()
535 |
536 | def sendCommand(self, command: str) -> None:
537 | self._queued_gcode_commands.append(command)
538 | CuraApplication.getInstance().callLater(self._sendQueuedGcode)
539 |
540 | # Send gcode commands that are queued in quick succession as a single batch
541 | def _sendQueuedGcode(self) -> None:
542 | if self._queued_gcode_commands:
543 | for gcode in self._queued_gcode_commands:
544 | self._sendCommandToApi("send", "&data={\"cmd\":\"" + gcode + "\"}")
545 | Logger.log("d", "Sent gcode command to Repetier instance: %s", gcode)
546 | self._queued_gcode_commands = []
547 |
548 | def _sendJobCommand(self, command: str) -> None:
549 | #Logger.log("d", "sendJobCommand: %s", command)
550 | if (command=="pause"):
551 | self._sendCommandToApi("send", "&data={\"cmd\":\"@pause\"}")
552 | if (command=="start"):
553 | self._manager.get(self._createEmptyRequest("continueJob"))
554 | if (command=="cancel"):
555 | self._manager.get(self._createEmptyRequest("stopJob"))
556 | #Logger.log("d", "Sent job command to Repetier instance: %s %s" % (command,self.jobState))
557 |
558 | def _sendCommandToApi(self, end_point, commands):
559 | command_request = QNetworkRequest(QUrl(self._api_url + "?a=" + end_point))
560 | command_request.setRawHeader(self._user_agent_header, self._user_agent.encode())
561 | command_request.setRawHeader(self._api_header, self._api_key)
562 | if self._basic_auth_data:
563 | command_request.setRawHeader(self._basic_auth_header, self._basic_auth_data)
564 | command_request.setHeader(QNetworkRequest.KnownHeaders.ContentTypeHeader, "application/json")
565 | if isinstance(commands, list):
566 | data = json.dumps({"commands": commands})
567 | else:
568 | data = commands
569 | #Logger.log("d", "_sendCommandToAPI: %s", data)
570 | self._command_reply = self._manager.post(command_request, data.encode())
571 |
572 | # Handler for all requests that have finished.
573 | def _onRequestFinished(self, reply: QNetworkReply) -> None:
574 | global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
575 | if not global_container_stack:
576 | return
577 | # if reply.error() == QNetworkReply.TimeoutError:
578 | if reply.error() == QNetworkReplyNetworkErrors.TimeoutError:
579 | Logger.log("w", "Received a timeout on a request to the instance")
580 | self._connection_state_before_timeout = self._connection_state
581 | self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Error))
582 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Repetier Connection to printer failed"))
583 | return
584 |
585 | # if self._connection_state_before_timeout and reply.error() == QNetworkReply.NoError:
586 | if self._connection_state_before_timeout and reply.error() == QNetworkReplyNetworkErrors.NoError:
587 | # There was a timeout, but we got a correct answer again.
588 | if self._last_response_time:
589 | Logger.log("d", "We got a response from the instance after %s of silence", time() - self._last_response_time)
590 | self.setConnectionState(self._connection_state_before_timeout)
591 | self._connection_state_before_timeout = None
592 |
593 | # if reply.error() == QNetworkReply.NoError:
594 | if reply.error() == QNetworkReplyNetworkErrors.NoError:
595 | self._last_response_time = time()
596 |
597 | # http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
598 | http_status_code = reply.attribute(QNetworkRequestAttributes.HttpStatusCodeAttribute)
599 | if not http_status_code:
600 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Repetier Connection recevied no data"))
601 | return
602 |
603 | error_handled = False
604 | # if reply.operation() == QNetworkAccessManager.GetOperation:
605 | if reply.operation() == QNetworkAccessManagerOperations.GetOperation:
606 | Logger.log("d", "reply.url() = %s", reply.url().toString())
607 | if self._api_prefix + "?a=stateList" in reply.url().toString(): # Status update from /printer.
608 | if not self._printers:
609 | self._createPrinterList()
610 | printer = self._printers[0]
611 | if http_status_code == 200:
612 | if not self.acceptsCommands:
613 | self._setAcceptsCommands(True)
614 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected to Repetier on {0}").format(self._repetier_id))
615 |
616 | if self._connection_state == UnifiedConnectionState.Connecting:
617 | self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Connected))
618 | try:
619 | json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
620 | except json.decoder.JSONDecodeError:
621 | Logger.log("w", "Received invalid JSON from Repetier instance.1")
622 | json_data = {}
623 | #if "temperature" in json_data:
624 | try:
625 | if self._repetier_id in json_data:
626 | Logger.log("d", "stateList JSON: %s",json_data[self._repetier_id])
627 | if "numExtruder" in json_data[self._repetier_id]:
628 | self._number_of_extruders = 0
629 | printer_state = "idle"
630 | #while "tool%d" % self._num_extruders in json_data["temperature"]:
631 | self._number_of_extruders=json_data[self._repetier_id]["numExtruder"]
632 | if self._number_of_extruders > 1:
633 | # Recreate list of printers to match the new _number_of_extruders
634 | self._createPrinterList()
635 | printer = self._printers[0]
636 |
637 | if self._number_of_extruders > 0:
638 | self._number_of_extruders_set = True
639 |
640 | # Check for hotend temperatures
641 | for index in range(0, self._number_of_extruders):
642 | extruder = printer.extruders[index]
643 | if "extruder" in json_data[self._repetier_id]:
644 | hotend_temperatures = json_data[self._repetier_id]["extruder"]
645 | #Logger.log("d", "target end temp %s", hotend_temperatures[index]["tempSet"])
646 | #Logger.log("d", "target end temp %s", hotend_temperatures[index]["tempRead"])
647 | extruder.updateTargetHotendTemperature(round(hotend_temperatures[index]["tempSet"],2))
648 | extruder.updateHotendTemperature(round(hotend_temperatures[index]["tempRead"],2))
649 | else:
650 | extruder.updateTargetHotendTemperature(0)
651 | extruder.updateHotendTemperature(0)
652 | #Logger.log("d", "json_data %s", json_data[self._key])
653 | if "heatedBed" in json_data[self._repetier_id]:
654 | bed_temperatures = json_data[self._repetier_id]["heatedBed"]
655 | actual_temperature = bed_temperatures["tempRead"] if bed_temperatures["tempRead"] is not None else -1
656 | printer.updateBedTemperature(round(actual_temperature,2))
657 | target_temperature = bed_temperatures["tempSet"] if bed_temperatures["tempSet"] is not None else -1
658 | printer.updateTargetBedTemperature(round(target_temperature,2))
659 | #Logger.log("d", "target bed temp %s", target_temperature)
660 | #Logger.log("d", "actual bed temp %s", actual_temperature)
661 | else:
662 | if "heatedBeds" in json_data[self._repetier_id]:
663 | bed_temperatures = json_data[self._repetier_id]["heatedBeds"][0]
664 | actual_temperature = bed_temperatures["tempRead"] if bed_temperatures["tempRead"] is not None else -1
665 | printer.updateBedTemperature(round(actual_temperature,2))
666 | target_temperature = bed_temperatures["tempSet"] if bed_temperatures["tempSet"] is not None else -1
667 | printer.updateTargetBedTemperature(round(target_temperature,2))
668 | #Logger.log("d", "target bed temp %s", target_temperature)
669 | #Logger.log("d", "actual bed temp %s", actual_temperature)
670 | else:
671 | printer.updateBedTemperature(-1)
672 | printer.updateTargetBedTemperature(0)
673 | printer.updateState(printer_state)
674 | except:
675 | Logger.log("w", "Received invalid JSON from Repetier instance.2")
676 | json_data = {}
677 | printer.activePrintJob.updateState("offline")
678 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Repetier on {0} configuration is invalid").format(self._repetier_id))
679 |
680 | elif http_status_code == 401:
681 | printer.updateState("offline")
682 | if printer.activePrintJob:
683 | printer.activePrintJob.updateState("offline")
684 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Repetier on {0} does not allow access to print").format(self._repetier_id))
685 | error_handled = True
686 | elif http_status_code == 409:
687 | if self._connection_state == ConnectionState.Connecting:
688 | self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Connected))
689 | printer.updateState("offline")
690 | if printer.activePrintJob:
691 | printer.activePrintJob.updateState("offline")
692 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "The printer connected to Repetier on {0} is not operational").format(self._repetier_id))
693 | error_handled = True
694 | else:
695 | printer.updateState("offline")
696 | if printer.activePrintJob:
697 | printer.activePrintJob.updateState("offline")
698 | Logger.log("w", "Received an unexpected returncode: %d", http_status_code)
699 |
700 | elif self._api_prefix + "?a=listPrinter" in reply.url().toString(): # Status update from /job:
701 | if not self._printers:
702 | return
703 | #self._createPrinterList()
704 |
705 | printer = self._printers[0]
706 |
707 | if http_status_code == 200:
708 | try:
709 | json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
710 | except json.decoder.JSONDecodeError:
711 | Logger.log("w", "Received invalid JSON from Repetier instance.")
712 | json_data = {}
713 | try:
714 | if self._printerindex(json_data,self._repetier_id)>-1:
715 | Logger.log("d", "listPrinter JSON: %s",json_data[self._printerindex(json_data,self._repetier_id)])
716 | print_job_state = "idle"
717 | printer.updateState("idle")
718 | Logger.log("d","JSON Dump: %s",json_data[self._printerindex(json_data,self._repetier_id)])
719 | if printer.activePrintJob is None:
720 | print_job = PrintJobOutputModel(output_controller=self._output_controller)
721 | printer.updateActivePrintJob(print_job)
722 | else:
723 | print_job = printer.activePrintJob
724 | if "job" in json_data[self._printerindex(json_data,self._repetier_id)]:
725 | if json_data[self._printerindex(json_data,self._repetier_id)]["job"] != "none":
726 | print_job.updateName(json_data[self._printerindex(json_data,self._repetier_id)]["job"])
727 | print_job_state = "printing"
728 | if json_data[self._printerindex(json_data,self._repetier_id)]["job"] == "none":
729 | print_job_state = "idle"
730 | printer.updateState("idle")
731 | print_job = PrintJobOutputModel(output_controller=self._output_controller)
732 | printer.updateActivePrintJob(print_job)
733 | if "paused" in json_data[self._printerindex(json_data,self._repetier_id)]:
734 | if json_data[self._printerindex(json_data,self._repetier_id)]["paused"] != False:
735 | print_job_state = "paused"
736 | print_job.updateState(print_job_state)
737 | if "done" in json_data[self._printerindex(json_data,self._repetier_id)]:
738 | progress = json_data[self._printerindex(json_data,self._repetier_id)]["done"]
739 | if "start" in json_data[self._printerindex(json_data,self._repetier_id)]:
740 | if json_data[self._printerindex(json_data,self._repetier_id)]["start"]:
741 | if json_data[self._printerindex(json_data,self._repetier_id)]["printTime"]:
742 | print_job.updateTimeTotal(json_data[self._printerindex(json_data,self._repetier_id)]["printTime"])
743 | if json_data[self._printerindex(json_data,self._repetier_id)]["printedTimeComp"]:
744 | print_job.updateTimeElapsed(json_data[self._printerindex(json_data,self._repetier_id)]["printedTimeComp"])
745 | elif progress > 0:
746 | print_job.updateTimeTotal(json_data[self._printerindex(json_data,self._repetier_id)]["printTime"] * (progress / 100))
747 | else:
748 | print_job.updateTimeTotal(0)
749 | else:
750 | print_job.updateTimeElapsed(0)
751 | print_job.updateTimeTotal(0)
752 | print_job.updateName(json_data[self._printerindex(json_data,self._repetier_id)]["job"])
753 | except:
754 | if printer.activePrintJob is not None:
755 | printer.activePrintJob.updateState("offline")
756 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Repetier on {0} configuration is invalid").format(self._key))
757 | else:
758 | if printer.activePrintJob is not None:
759 | printer.activePrintJob.updateState("offline")
760 | self.setConnectionText(i18n_catalog.i18nc("@info:status", "Repetier on {0} bad response").format(self._repetier_id))
761 | elif self._api_prefix + "?a=getPrinterConfig" in reply.url().toString(): # Repetier settings dump from /settings:
762 | if http_status_code == 200:
763 | try:
764 | json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
765 | except json.decoder.JSONDecodeError:
766 | Logger.log("w", "Received invalid JSON from Repetier instance.")
767 | json_data = {}
768 |
769 | if "general" in json_data and "sdcard" in json_data["general"]:
770 | self._sd_supported = json_data["general"]["sdcard"]
771 |
772 | if "webcam" in json_data and "dynamicUrl" in json_data["webcam"]:
773 | Logger.log("d", "RepetierOutputDevice: Detected Repetier 89.X")
774 | self._camera_shares_proxy = False
775 | Logger.log("d", "RepetierOutputDevice: Checking streamurl")
776 | stream_url = json_data["webcam"]["dynamicUrl"]
777 | if not stream_url: #empty string or None
778 | self._camera_url = ""
779 | else:
780 | stream_url = stream_url.replace("127.0.0.1",self._address)
781 | if not stream_url: #empty string or None
782 | self._camera_url = ""
783 | elif stream_url[:4].lower() == "http": # absolute uri Logger.log("d", "RepetierOutputDevice: stream_url: %s",stream_url)
784 | self._camera_url=stream_url
785 | elif stream_url[:2] == "//": # protocol-relative
786 | self._camera_url = "%s:%s" % (self._protocol, stream_url)
787 | elif stream_url[:1] == ":": # domain-relative (on another port)
788 | self._camera_url = "%s://%s%s" % (self._protocol, self._address, stream_url)
789 | elif stream_url[:1] == "/": # domain-relative (on same port)
790 | self._camera_url = "%s://%s:%d%s" % (self._protocol, self._address, self._port, stream_url)
791 | self._camera_shares_proxy = True
792 | else:
793 | Logger.log("w", "Unusable stream url received: %s", stream_url)
794 | self._camera_url = ""
795 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamflip_y", False)):
796 | self._camera_mirror = True
797 | else:
798 | self._camera_mirror = False
799 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamflip_x", False)):
800 | self._camera_rotation = 180
801 | self._camera_mirror = True
802 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamrot_90", False)):
803 | self._camera_rotation = 90
804 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamrot_180", False)):
805 | self._camera_rotation = 180
806 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamrot_270", False)):
807 | self._camera_rotation = 270
808 | Logger.log("d", "Set Repetier camera url to %s", self._camera_url)
809 | self.cameraUrlChanged.emit()
810 | self._camera_mirror = False
811 | #self.cameraOrientationChanged.emit()
812 | if "webcams" in json_data:
813 | Logger.log("d", "RepetierOutputDevice: Detected Repetier 90.X")
814 | if len(json_data["webcams"])>0:
815 | if "dynamicUrl" in json_data["webcams"][0]:
816 | self._camera_shares_proxy = False
817 | Logger.log("d", "RepetierOutputDevice: Checking streamurl")
818 | stream_url = json_data["webcams"][0]["dynamicUrl"].replace("127.0.0.1",self._address)
819 | if not stream_url: #empty string or None
820 | self._camera_url = ""
821 | elif stream_url[:4].lower() == "http": # absolute uri Logger.log("d", "RepetierOutputDevice: stream_url: %s",stream_url)
822 | self._camera_url=stream_url
823 | elif stream_url[:2] == "//": # protocol-relative
824 | self._camera_url = "%s:%s" % (self._protocol, stream_url)
825 | elif stream_url[:1] == ":": # domain-relative (on another port)
826 | self._camera_url = "%s://%s%s" % (self._protocol, self._address, stream_url)
827 | elif stream_url[:1] == "/": # domain-relative (on same port)
828 | self._camera_url = "%s://%s:%d%s" % (self._protocol, self._address, self._port, stream_url)
829 | self._camera_shares_proxy = True
830 | else:
831 | Logger.log("w", "Unusable stream url received: %s", stream_url)
832 | self._camera_url = ""
833 | Logger.log("d", "Set Repetier camera url to %s", self._camera_url)
834 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamflip_y", False)):
835 | self._camera_mirror = True
836 | else:
837 | self._camera_mirror = False
838 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamflip_x", False)):
839 | self._camera_rotation = 180
840 | self._camera_mirror = True
841 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamrot_90", False)):
842 | self._camera_rotation = 90
843 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamrot_180", False)):
844 | self._camera_rotation = 180
845 | if parseBool(global_container_stack.getMetaDataEntry("repetier_webcamrot_270", False)):
846 | self._camera_rotation = 270
847 | self.cameraUrlChanged.emit()
848 | elif reply.operation() == QNetworkAccessManager.PostOperation:
849 | if self._api_prefix + "?a=listModels" in reply.url().toString(): # Result from /files command:
850 | if http_status_code == 201:
851 | Logger.log("d", "Resource created on Repetier instance: %s", reply.header(QNetworkRequest.LocationHeader).toString())
852 | else:
853 | pass # TODO: Handle errors
854 |
855 | reply.uploadProgress.disconnect(self._onUploadProgress)
856 | if self._progress_message:
857 | self._progress_message.hide()
858 | global_container_stack = Application.getInstance().getGlobalContainerStack()
859 | if self._forced_queue or not self._auto_print:
860 | location = reply.header(QNetworkRequest.LocationHeader)
861 | if location:
862 | file_name = QUrl(reply.header(QNetworkRequest.LocationHeader).toString()).fileName()
863 | message = Message(i18n_catalog.i18nc("@info:status", "Saved to Repetier as {0}").format(file_name))
864 | else:
865 | message = Message(i18n_catalog.i18nc("@info:status", "Saved to Repetier"))
866 | message.addAction("open_browser", i18n_catalog.i18nc("@action:button", "Open Repetier..."), "globe",
867 | i18n_catalog.i18nc("@info:tooltip", "Open the Repetier web interface"))
868 | message.actionTriggered.connect(self._openRepetierPrint)
869 | message.show()
870 |
871 | elif self._api_prefix + "?a=send" in reply.url().toString(): # Result from /job command:
872 | if http_status_code == 204:
873 | Logger.log("d", "Repetier command accepted")
874 | else:
875 | pass # TODO: Handle errors
876 |
877 |
878 | else:
879 | Logger.log("d", "RepetierOutputDevice got an unhandled operation %s", reply.operation())
880 |
881 | if not error_handled and http_status_code >= 400:
882 | # Received an error reply
883 | error_string = bytes(reply.readAll()).decode("utf-8")
884 | if not error_string:
885 | error_string = reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)
886 | if self._error_message:
887 | self._error_message.hide()
888 | #self._error_message = Message(i18n_catalog.i18nc("@info:status", "Repetier returned an error: {0}.").format(error_string))
889 | self._error_message = Message(error_string, title=i18n_catalog.i18nc("@label", "Repetier error"))
890 | self._error_message.show()
891 | return
892 | def _onUploadProgress(self, bytes_sent: int, bytes_total: int) -> None:
893 | if not self._progress_message:
894 | return
895 |
896 | if bytes_total > 0:
897 | # Treat upload progress as response. Uploading can take more than 10 seconds, so if we don't, we can get
898 | # timeout responses if this happens.
899 | self._last_response_time = time()
900 |
901 | progress = bytes_sent / bytes_total * 100
902 | previous_progress = self._progress_message.getProgress()
903 | if progress < 100:
904 | if previous_progress is not None and progress > previous_progress:
905 | self._progress_message.setProgress(progress)
906 | else:
907 | self._progress_message.hide()
908 | self._progress_message = Message(
909 | i18n_catalog.i18nc("@info:status", "Storing data on Repetier"), 0, False, -1, title=i18n_catalog.i18nc("@label", "Repetier")
910 | )
911 | self._progress_message.show()
912 | else:
913 | self._progress_message.setProgress(0)
914 |
915 | def _printerindex(self, jsonstr:str, repetier_id:str) -> int:
916 | count = 0
917 | rv=-1
918 | for i in jsonstr:
919 | if "slug" in i:
920 | if i["slug"]==repetier_id:
921 | return count
922 | count=count+1
923 | return rv
924 | def _onUploadFinished(self, reply: QNetworkReply) -> None:
925 | reply.uploadProgress.disconnect(self._onUploadProgress)
926 |
927 | Logger.log("d", "_onUploadFinished %s", reply.url().toString())
928 | if self._progress_message:
929 | self._progress_message.hide()
930 |
931 | # http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
932 | http_status_code = reply.attribute(QNetworkRequestAttributes.HttpStatusCodeAttribute)
933 | Logger.log("d", "_onUploadFinished http_status_code=%d", http_status_code)
934 | error_string = ""
935 | if http_status_code == 401:
936 | error_string = i18n_catalog.i18nc("@info:error", "You are not allowed to upload files to Repetier with the configured API key.")
937 |
938 | elif http_status_code == 409:
939 | if "files/sdcard/" in reply.url().toString():
940 | error_string = i18n_catalog.i18nc("@info:error", "Can't store the printjob on the printer sd card.")
941 | else:
942 | error_string = i18n_catalog.i18nc("@info:error", "Can't store the printjob with the same name as the one that is currently printing.")
943 |
944 | elif ((http_status_code != 201) and (http_status_code != 200)):
945 | error_string = bytes(reply.readAll()).decode("utf-8")
946 | if not error_string:
947 | error_string = reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)
948 |
949 | if error_string:
950 | self._showErrorMessage(error_string)
951 | Logger.log("e", "RepetierOutputDevice got an error uploading %s", reply.url().toString())
952 | Logger.log("e", error_string)
953 | return
954 |
955 | #location_url = reply.header(QNetworkRequest.LocationHeader)
956 | location_url = reply.header(QNetworkRequestKnownHeaders.LocationHeader)
957 | if location_url:
958 | Logger.log("d", "Resource created on Repetier instance: %s", location_url.toString())
959 |
960 | if self._forced_queue or not self._auto_print:
961 | if location_url:
962 | file_name = location_url.fileName()
963 | message = Message(i18n_catalog.i18nc("@info:status", "Saved to Repetier as {0}").format(file_name))
964 | else:
965 | message = Message(i18n_catalog.i18nc("@info:status", "Saved to Repetier"))
966 | message.setTitle(i18n_catalog.i18nc("@label", "Repetier"))
967 | message.addAction(
968 | "open_browser", i18n_catalog.i18nc("@action:button", "Repetier..."), "globe",
969 | i18n_catalog.i18nc("@info:tooltip", "Open the Repetier web interface")
970 | )
971 | message.actionTriggered.connect(self._openRepetierPrint)
972 | message.show()
973 | elif self._auto_print:
974 | end_point = location_url.toString().split(self._api_prefix, 1)[1]
975 | if self._ufp_supported and end_point.endswith(".ufp"):
976 | end_point += ".gcode"
977 |
978 | if not self._wait_for_analysis:
979 | self._selectAndPrint(end_point)
980 | return
981 |
982 | self._waiting_message = Message(
983 | i18n_catalog.i18nc("@info:status", "Waiting for Repetier to complete Gcode analysis..."),
984 | title=i18n_catalog.i18nc("@label", "Repetier"),
985 | progress=-1, lifetime=0, dismissable=False, use_inactivity_timer=False
986 | )
987 | self._waiting_message.addAction(
988 | "print", i18n_catalog.i18nc("@action:button", "Print now"), "",
989 | i18n_catalog.i18nc("@action:tooltip", "Stop waiting for the Gcode analysis and start printing immediately"),
990 | button_style=Message.ActionButtonStyle.SECONDARY
991 | )
992 | self._waiting_message.addAction(
993 | "cancel", i18n_catalog.i18nc("@action:button", "Cancel"), "",
994 | i18n_catalog.i18nc("@action:tooltip", "Abort the printjob")
995 | )
996 | self._waiting_message.actionTriggered.connect(self._stopWaitingForAnalysis)
997 | self._waiting_message.show()
998 |
999 | self._waiting_for_analysis = True
1000 | self._polling_end_points.append(end_point) # start polling the API for information about this file
1001 |
1002 | def _createPrinterList(self) -> None:
1003 | printer = PrinterOutputModel(output_controller=self._output_controller, number_of_extruders=self._number_of_extruders)
1004 | printer.updateName(self.name)
1005 | self._printers = [printer]
1006 | self.printersChanged.emit()
1007 |
1008 | def _selectAndPrint(self, end_point: str) -> None:
1009 | command = {
1010 | "command": "select",
1011 | "print": True
1012 | }
1013 | self._sendCommandToApi(end_point, command)
1014 |
1015 | def _showErrorMessage(self, error_string: str) -> None:
1016 | if self._error_message:
1017 | self._error_message.hide()
1018 | self._error_message = Message(error_string, title=i18n_catalog.i18nc("@label", "Repetier error"))
1019 | self._error_message.show()
1020 |
1021 | def _openRepetierPrint(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
1022 | QDesktopServices.openUrl(QUrl(self._base_url))
1023 |
1024 | def _createEmptyRequest(self, target: str, content_type: Optional[str] = "application/json") -> QNetworkRequest:
1025 | if "upload" in target:
1026 | if self._forced_queue or not self._auto_print:
1027 | request = QNetworkRequest(QUrl(self._save_url + "?a=" + target))
1028 | else:
1029 | request = QNetworkRequest(QUrl(self._job_url + "?a=" + target))
1030 | else:
1031 | request = QNetworkRequest(QUrl(self._api_url + "?a=" + target))
1032 | # Removed per QT6
1033 | # request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
1034 |
1035 | request.setRawHeader(b"X-Api-Key", self._api_key)
1036 | request.setRawHeader(b"User-Agent", self._user_agent.encode())
1037 |
1038 | if content_type is not None:
1039 | request.setHeader(QNetworkRequest.KnownHeaders.ContentTypeHeader, content_type)
1040 | # request.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
1041 |
1042 | # ignore SSL errors (eg for self-signed certificates)
1043 | ssl_configuration = QSslConfiguration.defaultConfiguration()
1044 | # ssl_configuration.setPeerVerifyMode(QSslSocket.VerifyNone)
1045 | ssl_configuration.setPeerVerifyMode(QSslSocketPeerVerifyModes.VerifyNone)
1046 | request.setSslConfiguration(ssl_configuration)
1047 |
1048 | if self._basic_auth_data:
1049 | request.setRawHeader(b"Authorization", self._basic_auth_data)
1050 |
1051 | return request
1052 |
1053 | # This is a patched version from NetworkedPrinterOutputdevice, which adds "form_data" instead of "form-data"
1054 | def _createFormPart(self, content_header: str, data: bytes, content_type: Optional[str] = None) -> QHttpPart:
1055 | part = QHttpPart()
1056 |
1057 | if not content_header.startswith("form-data;"):
1058 | content_header = "form-data; " + content_header
1059 | # part.setHeader(QNetworkRequest.ContentDispositionHeader, content_header)
1060 | part.setHeader(QNetworkRequestKnownHeaders.ContentDispositionHeader, content_header)
1061 | if content_type is not None:
1062 | # part.setHeader(QNetworkRequest.ContentTypeHeader, content_type)
1063 | part.setHeader(QNetworkRequest.KnownHeaders.ContentTypeHeader, content_type)
1064 |
1065 | part.setBody(data)
1066 | return part
1067 |
1068 | ## Overloaded from NetworkedPrinterOutputDevice.get() to be permissive of
1069 | # self-signed certificates
1070 | def get(self, url: str, on_finished: Optional[Callable[[QNetworkReply], None]]) -> None:
1071 | Logger.log("d", "get request: %s", url)
1072 | self._validateManager()
1073 |
1074 | request = self._createEmptyRequest(url)
1075 | self._last_request_time = time()
1076 |
1077 | if not self._manager:
1078 | Logger.log("e", "No network manager was created to execute the GET call with.")
1079 | return
1080 |
1081 | reply = self._manager.get(request)
1082 | self._registerOnFinishedCallback(reply, on_finished)
1083 |
1084 | ## Overloaded from NetworkedPrinterOutputDevice.post() to backport https://github.com/Ultimaker/Cura/pull/4678
1085 | # and allow self-signed certificates
1086 | def post(self, url: str, data: Union[str, bytes],
1087 | on_finished: Optional[Callable[[QNetworkReply], None]],
1088 | on_progress: Optional[Callable[[int, int], None]] = None) -> None:
1089 | self._validateManager()
1090 |
1091 | request = self._createEmptyRequest(url)
1092 | self._last_request_time = time()
1093 |
1094 | if not self._manager:
1095 | Logger.log("e", "Could not find manager.")
1096 | return
1097 |
1098 | body = data if isinstance(data, bytes) else data.encode() # type: bytes
1099 | reply = self._manager.post(request, body)
1100 | if on_progress is not None:
1101 | reply.uploadProgress.connect(on_progress)
1102 | self._registerOnFinishedCallback(reply, on_finished)
--------------------------------------------------------------------------------
/RepetierOutputDevicePlugin.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView & Shane Bumpurs
2 | # OctoPrintPlugin is released under the terms of the AGPLv3 or higher.
3 |
4 | from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
5 | from .RepetierOutputDevice import RepetierOutputDevice
6 |
7 | from UM.Signal import Signal, signalemitter
8 | from UM.Application import Application
9 | from UM.Logger import Logger
10 | from UM.Util import parseBool
11 |
12 | from PyQt6.QtCore import QTimer
13 | import time
14 | import json
15 | import re
16 | import base64
17 | import os.path
18 | import ipaddress
19 |
20 | from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING
21 | if TYPE_CHECKING:
22 | from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
23 |
24 | ## This plugin handles the connection detection & creation of output device objects for Repetier-connected printers.
25 | # Zero-Conf is used to detect printers, which are saved in a dict.
26 | # If we discover an instance that has the same key as the active machine instance a connection is made.
27 | @signalemitter
28 | class RepetierOutputDevicePlugin(OutputDevicePlugin):
29 | def __init__(self) -> None:
30 | super().__init__()
31 | self._zero_conf = None
32 | self._browser = None
33 | self._instances = {}
34 |
35 | # Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
36 | self.addInstanceSignal.connect(self.addInstance)
37 | self.removeInstanceSignal.connect(self.removeInstance)
38 | Application.getInstance().globalContainerStackChanged.connect(self.reCheckConnections)
39 |
40 | # Load custom instances from preferences
41 | self._preferences = Application.getInstance().getPreferences()
42 | self._preferences.addPreference("Repetier/manual_instances", "{}")
43 |
44 | try:
45 | self._manual_instances = json.loads(self._preferences.getValue("Repetier/manual_instances"))
46 | except ValueError:
47 | self._manual_instances = {}
48 | if not isinstance(self._manual_instances, dict):
49 | self._manual_instances = {}
50 |
51 | self._name_regex = re.compile("Repetier instance (\".*\"\.|on )(.*)\.")
52 |
53 | self._keep_alive_timer = QTimer()
54 | self._keep_alive_timer.setInterval(2000)
55 | self._keep_alive_timer.setSingleShot(True)
56 | self._keep_alive_timer.timeout.connect(self._keepDiscoveryAlive)
57 |
58 | addInstanceSignal = Signal()
59 | removeInstanceSignal = Signal()
60 | instanceListChanged = Signal()
61 |
62 | ## Start looking for devices on network.
63 | def start(self) -> None:
64 | self.startDiscovery()
65 |
66 | def startDiscovery(self):
67 | if self._browser:
68 | self._browser.cancel()
69 | self._browser = None
70 | self._printers = {}
71 | instance_keys = list(self._instances.keys())
72 | for key in instance_keys:
73 | self.removeInstance(key)
74 |
75 | # Add manual instances from preference
76 | for name, properties in self._manual_instances.items():
77 | additional_properties = {
78 | b"path": properties["path"].encode("utf-8"),
79 | b"useHttps": b"true" if properties.get("useHttps", False) else b"false",
80 | b'userName': properties.get("userName", "").encode("utf-8"),
81 | b'password': properties.get("password", "").encode("utf-8"),
82 | b'repetier_id': properties.get("repetier_id", "").encode("utf-8"),
83 | b"manual": b"true"
84 | } # These additional properties use bytearrays to mimick the output of zeroconf
85 | self.addInstance(name, properties["address"], properties["port"], additional_properties)
86 |
87 | self.instanceListChanged.emit()
88 | def _keepDiscoveryAlive(self) -> None:
89 | if not self._browser or not self._browser.is_alive():
90 | Logger.log("w", "Zeroconf discovery has died, restarting discovery of Repetier instances.")
91 | self.startDiscovery()
92 |
93 | def addManualInstance(self, name: str, address: str, port: int, path: str, useHttps: bool = False, userName: str = "", password: str = "", repetierid: str = "")-> None:
94 | self._manual_instances[name] = {"address": address, "port": port, "path": path, "useHttps": useHttps, "userName": userName, "password": password, "repetier_id":repetierid}
95 | self._preferences.setValue("Repetier/manual_instances", json.dumps(self._manual_instances))
96 |
97 | properties = { b"path": path.encode("utf-8"), b"useHttps": b"true" if useHttps else b"false", b'userName': userName.encode("utf-8"), b'password': password.encode("utf-8"), b"manual": b"true",b'repetier_id':repetierid.encode("utf-8")}
98 |
99 | if name in self._instances:
100 | self.removeInstance(name)
101 |
102 | self.addInstance(name, address, port, properties)
103 | self.instanceListChanged.emit()
104 |
105 | def removeManualInstance(self, name: str) -> None:
106 | if name in self._instances:
107 | self.removeInstance(name)
108 | self.instanceListChanged.emit()
109 |
110 | if name in self._manual_instances:
111 | self._manual_instances.pop(name, None)
112 | self._preferences.setValue("Repetier/manual_instances", json.dumps(self._manual_instances))
113 |
114 | ## Stop looking for devices on network.
115 | def stop(self) -> None:
116 | self._keep_alive_timer.stop()
117 | if self._browser:
118 | self._browser.cancel()
119 | self._browser = None # type: Optional[ServiceBrowser]
120 | if self._zero_conf:
121 | self._zero_conf.close()
122 |
123 | def getInstances(self) -> Dict[str, Any]:
124 | return self._instances
125 |
126 | def getInstanceById(self, instance_id: str) -> Optional[RepetierOutputDevice]:
127 | instance = self._instances.get(instance_id, None)
128 | if instance:
129 | return instance
130 | Logger.log("w", "No instance found with id %s", instance_id)
131 | return None
132 |
133 | def reCheckConnections(self) -> None:
134 | global_container_stack = Application.getInstance().getGlobalContainerStack()
135 | if not global_container_stack:
136 | return
137 |
138 | for key in self._instances:
139 | if key == global_container_stack.getMetaDataEntry("id"):
140 | api_key = global_container_stack.getMetaDataEntry("repetier_api_key", "")
141 | self._instances[key].setApiKey(api_key)
142 | self._instances[key].setShowCamera(parseBool(global_container_stack.getMetaDataEntry("repetier_show_camera", "true")))
143 | self._instances[key].connectionStateChanged.connect(self._onInstanceConnectionStateChanged)
144 | self._instances[key].connect()
145 | else:
146 | if self._instances[key].isConnected():
147 | self._instances[key].close()
148 |
149 | ## Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
150 | def addInstance(self, name: str, address: str, port: int, properties: Dict[bytes, bytes]) -> None:
151 | instance = RepetierOutputDevice(name, address, port, properties)
152 | self._instances[instance.getId()] = instance
153 | global_container_stack = Application.getInstance().getGlobalContainerStack()
154 | if global_container_stack and instance.getId() == global_container_stack.getMetaDataEntry("id"):
155 | api_key = global_container_stack.getMetaDataEntry("repetier_api_key", "")
156 | instance.setApiKey(api_key)
157 | instance.setShowCamera(parseBool(global_container_stack.getMetaDataEntry("repetier_show_camera", "true")))
158 | instance.connectionStateChanged.connect(self._onInstanceConnectionStateChanged)
159 | instance.connect()
160 |
161 | def removeInstance(self, name: str) -> None:
162 | instance = self._instances.pop(name, None)
163 | if instance:
164 | if instance.isConnected():
165 | instance.connectionStateChanged.disconnect(self._onInstanceConnectionStateChanged)
166 | instance.disconnect()
167 |
168 | ## Handler for when the connection state of one of the detected instances changes
169 | def _onInstanceConnectionStateChanged(self, key: str) -> None:
170 | if key not in self._instances:
171 | return
172 |
173 | if self._instances[key].isConnected():
174 | self.getOutputDeviceManager().addOutputDevice(self._instances[key])
175 | else:
176 | self.getOutputDeviceManager().removeOutputDevice(key)
177 |
178 |
179 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView & Shane Bumpurs
2 | # RepetierIntegration is released under the terms of the AGPLv3 or higher.
3 | import os, json
4 |
5 | from . import RepetierOutputDevicePlugin
6 | from . import DiscoverRepetierAction
7 | from . import NetworkMJPGImage
8 |
9 | from UM.Version import Version
10 | from UM.Application import Application
11 | from UM.Logger import Logger
12 |
13 | from PyQt6.QtQml import qmlRegisterType
14 |
15 | def getMetaData():
16 | return {}
17 |
18 | def register(app):
19 | qmlRegisterType(NetworkMJPGImage.NetworkMJPGImage, "RepetierIntegration", 1, 0, "NetworkMJPGImage")
20 |
21 | return {
22 | "output_device": RepetierOutputDevicePlugin.RepetierOutputDevicePlugin(),
23 | "machine_action": DiscoverRepetierAction.DiscoverRepetierAction()
24 | }
25 |
--------------------------------------------------------------------------------
/config.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/VMaxx/RepetierIntegration/de0dbe77d5aa870c44f65234a488240f0c509512/config.jpg
--------------------------------------------------------------------------------
/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/VMaxx/RepetierIntegration/de0dbe77d5aa870c44f65234a488240f0c509512/icon.png
--------------------------------------------------------------------------------
/plugin.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Repetier Integration",
3 | "author": "Shane Bumpurs - c/o fieldOfView",
4 | "version": "5.0",
5 | "minimum_cura_version": "5.0",
6 | "description": "Enables network printing and monitoring to Repetier",
7 | "api": 5,
8 | "supported_sdk_versions": ["5.0.0", "6.0.0", "7.0.0", "8.0.0"],
9 | "i18n-catalog": "cura"
10 | }
11 |
--------------------------------------------------------------------------------
/qml/MonitorItem.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 2.2
2 | import QtQuick.Controls 2.3
3 | import UM 1.5 as UM
4 | import Cura 1.1 as Cura
5 | import RepetierIntegration 1.0 as RepetierIntegration
6 |
7 | Component
8 | {
9 | id: monitorItem
10 |
11 | Item
12 | {
13 | RepetierIntegration.NetworkMJPGImage
14 | {
15 | id: cameraImage
16 | visible: OutputDevice != null ? OutputDevice.showCamera : false
17 |
18 | property real maximumWidthMinusSidebar: maximumWidth - sidebar.width - 2 * UM.Theme.getSize("default_margin").width
19 | property real maximumZoom: 2
20 | property bool rotatedImage: (OutputDevice.cameraOrientation.rotation / 90) % 2
21 | property bool proportionalHeight:
22 | {
23 | if (imageHeight == 0 || maximumHeight == 0)
24 | {
25 | return true;
26 | }
27 | if (!rotatedImage)
28 | {
29 | return (imageWidth / imageHeight) > (maximumWidthMinusSidebar / maximumHeight);
30 | }
31 | else
32 | {
33 | return (imageWidth / imageHeight) > (maximumHeight / maximumWidthMinusSidebar);
34 | }
35 | }
36 | property real _width:
37 | {
38 | if (!rotatedImage)
39 | {
40 | return Math.min(maximumWidthMinusSidebar, imageWidth * screenScaleFactor * maximumZoom);
41 | }
42 | else
43 | {
44 | return Math.min(maximumHeight, imageWidth * screenScaleFactor * maximumZoom);
45 | }
46 | }
47 | property real _height:
48 | {
49 | if (!rotatedImage)
50 | {
51 | return Math.min(maximumHeight, imageHeight * screenScaleFactor * maximumZoom);
52 | }
53 | else
54 | {
55 | return Math.min(maximumWidth, imageHeight * screenScaleFactor * maximumZoom);
56 | }
57 | }
58 | width: proportionalHeight ? _width : imageWidth * _height / imageHeight
59 | height: !proportionalHeight ? _height : imageHeight * _width / imageWidth
60 | anchors.horizontalCenter: horizontalCenterItem.horizontalCenter
61 | anchors.verticalCenter: parent.verticalCenter
62 |
63 | Component.onCompleted:
64 | {
65 | if (visible)
66 | {
67 | start();
68 | }
69 | }
70 | onVisibleChanged:
71 | {
72 | if (visible)
73 | {
74 | start();
75 | } else
76 | {
77 | stop();
78 | }
79 | }
80 | source: OutputDevice.cameraUrl
81 |
82 | rotation: OutputDevice.cameraOrientation.rotation
83 | mirror: OutputDevice.cameraOrientation.mirror
84 | }
85 |
86 | Item
87 | {
88 | id: horizontalCenterItem
89 | anchors.left: parent.left
90 | anchors.right: sidebar.left
91 | }
92 |
93 | Cura.RoundedRectangle
94 | {
95 | id: sidebarBackground
96 |
97 | width: UM.Theme.getSize("print_setup_widget").width
98 | anchors
99 | {
100 | right: parent.right
101 | top: parent.top
102 | topMargin: UM.Theme.getSize("default_margin").height
103 | bottom: actionsPanel.top
104 | bottomMargin: UM.Theme.getSize("default_margin").height
105 | }
106 |
107 | border.width: UM.Theme.getSize("default_lining").width
108 | border.color: UM.Theme.getColor("lining")
109 | color: UM.Theme.getColor("main_background")
110 |
111 | cornerSide: Cura.RoundedRectangle.Direction.Left
112 | radius: UM.Theme.getSize("default_radius").width
113 | }
114 |
115 | Cura.PrintMonitor {
116 | id: sidebar
117 |
118 | width: UM.Theme.getSize("print_setup_widget").width - UM.Theme.getSize("default_margin").height * 2
119 | anchors
120 | {
121 | top: parent.top
122 | bottom: actionsPanel.top
123 | leftMargin: UM.Theme.getSize("default_margin").width
124 | right: parent.right
125 | rightMargin: UM.Theme.getSize("default_margin").width
126 | }
127 | }
128 |
129 | Cura.RoundedRectangle
130 | {
131 | id: actionsPanel
132 |
133 | border.width: UM.Theme.getSize("default_lining").width
134 | border.color: UM.Theme.getColor("lining")
135 | color: UM.Theme.getColor("main_background")
136 |
137 | cornerSide: Cura.RoundedRectangle.Direction.Left
138 | radius: UM.Theme.getSize("default_radius").width
139 |
140 | anchors.bottom: parent.bottom
141 | anchors.right: parent.right
142 |
143 | anchors.bottomMargin: UM.Theme.getSize("default_margin").width
144 | anchors.topMargin: UM.Theme.getSize("default_margin").height
145 |
146 | width: UM.Theme.getSize("print_setup_widget").width
147 | height: monitorButton.height
148 |
149 | // MonitorButton is actually the bottom footer panel.
150 | Cura.MonitorButton
151 | {
152 | id: monitorButton
153 | width: parent.width
154 | anchors.top: parent.top
155 | }
156 | }
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/webcam.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/VMaxx/RepetierIntegration/de0dbe77d5aa870c44f65234a488240f0c509512/webcam.jpg
--------------------------------------------------------------------------------