forked from fieldOfView/Cura-OctoPrintPlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OctoPrintOutputDevice.py
1302 lines (1057 loc) · 60.5 KB
/
OctoPrintOutputDevice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2020 Aldo Hoeben / fieldOfView
# OctoPrintPlugin is released under the terms of the AGPLv3 or higher.
from UM.i18n import i18nCatalog
from UM.Logger import Logger
from UM.Signal import signalemitter
from UM.Message import Message
from UM.Util import parseBool
from UM.Version import Version
from UM.Mesh.MeshWriter import MeshWriter
from UM.PluginRegistry import PluginRegistry
from UM.PluginError import PluginNotFoundError
from cura.CuraApplication import CuraApplication
from .OctoPrintOutputController import OctoPrintOutputController
from .PowerPlugins import PowerPlugins
from .WebcamsModel import WebcamsModel
try:
# Cura 4.1 and newer
from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
from cura.PrinterOutput.Models.PrintJobOutputModel import PrintJobOutputModel
except ImportError:
# Cura 3.5 - Cura 4.0
from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
from cura.PrinterOutput.PrintJobOutputModel import PrintJobOutputModel
from cura.PrinterOutput.NetworkedPrinterOutputDevice import NetworkedPrinterOutputDevice
from PyQt5.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager
from PyQt5.QtNetwork import QNetworkReply, QSslConfiguration, QSslSocket
from PyQt5.QtCore import QUrl, QTimer, pyqtSignal, pyqtProperty, pyqtSlot, QCoreApplication
from PyQt5.QtGui import QImage, QDesktopServices
import json
import os.path
import re
from time import time
import base64
from io import StringIO, BytesIO
from enum import IntEnum
from collections import namedtuple
from typing import cast, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from UM.Scene.SceneNode import SceneNode #For typing.
from UM.FileHandler.FileHandler import FileHandler #For typing.
i18n_catalog = i18nCatalog("cura")
## The current processing state of the backend.
# This shadows PrinterOutputDevice.ConnectionState because its spelling changed
# between Cura 4.0 beta 1 and beta 2
class UnifiedConnectionState(IntEnum):
try:
Closed = ConnectionState.Closed
Connecting = ConnectionState.Connecting
Connected = ConnectionState.Connected
Busy = ConnectionState.Busy
Error = ConnectionState.Error
except AttributeError:
Closed = ConnectionState.closed # type: ignore
Connecting = ConnectionState.connecting # type: ignore
Connected = ConnectionState.connected # type: ignore
Busy = ConnectionState.busy # type: ignore
Error = ConnectionState.error # type: ignore
AxisInformation = namedtuple("AxisInformation", ["speed", "inverted"])
## OctoPrint connected (wifi / lan) printer using the OctoPrint API
@signalemitter
class OctoPrintOutputDevice(NetworkedPrinterOutputDevice):
def __init__(self, instance_id: str, address: str, port: int, properties: dict, **kwargs) -> None:
super().__init__(device_id = instance_id, address = address, properties = properties, **kwargs)
self._address = address
self._port = port
self._path = properties.get(b"path", b"/").decode("utf-8")
if self._path[-1:] != "/":
self._path += "/"
self._id = instance_id
self._properties = properties # Properties dict as provided by zero conf
self._printer_model = ""
self._printer_name = ""
self._octoprint_version = self._properties.get(b"version", b"").decode("utf-8")
self._octoprint_user_name = ""
self._axis_information = {axis: AxisInformation(speed=6000 if axis != "e" else 300, inverted=False) for axis in ["x", "y", "z", "e"]}
self._gcode_stream = StringIO() # type: Union[StringIO, BytesIO]
self._auto_print = True
self._auto_select = False
self._forced_queue = False
self._select_and_print_handled_in_upload = False
# We start with a single extruder, but update this when we get data from octoprint
self._number_of_extruders_set = False
self._number_of_extruders = 1
# Try to get version information from plugin.json
plugin_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugin.json")
try:
with open(plugin_file_path) as plugin_file:
plugin_info = json.load(plugin_file)
plugin_version = plugin_info["version"]
except:
# The actual version info is not critical to have so we can continue
plugin_version = "Unknown"
Logger.logException("w", "Could not get version information for the plugin")
self._user_agent = ("%s/%s %s/%s" % (
CuraApplication.getInstance().getApplicationName(),
CuraApplication.getInstance().getVersion(),
"OctoPrintPlugin",
plugin_version
)) # NetworkedPrinterOutputDevice defines this as string, so we encode this later
self._api_prefix = "api/"
self._api_key = b""
self._protocol = "https" if properties.get(b'useHttps') == b"true" else "http"
self._base_url = "%s://%s:%d%s" % (self._protocol, self._address, self._port, self._path)
self._api_url = self._base_url + self._api_prefix
self._basic_auth_data = None
self._basic_auth_string = ""
basic_auth_username = properties.get(b"userName", b"").decode("utf-8")
basic_auth_password = properties.get(b"password", b"").decode("utf-8")
if basic_auth_username and basic_auth_password:
data = base64.b64encode(("%s:%s" % (basic_auth_username, basic_auth_password)).encode()).decode("utf-8")
self._basic_auth_data = ("basic %s" % data).encode()
self._basic_auth_string = "%s:%s" % (basic_auth_username, basic_auth_password)
try:
major_api_version = CuraApplication.getInstance().getAPIVersion().getMajor()
except AttributeError:
# UM.Application.getAPIVersion was added for API > 6 (Cura 4)
# Since this plugin version is only compatible with Cura 3.5 and newer, it is safe to assume API 5
major_api_version = 5
if major_api_version <= 5:
# In Cura 3.x, the monitor item only shows the camera stream
self._monitor_view_qml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qml", "MonitorItem3x.qml")
else:
# In Cura 4.x, the monitor item shows the camera stream as well as the monitor sidebar
self._monitor_view_qml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qml", "MonitorItem4x.qml")
name = self._id
matches = re.search(r"^\"(.*)\"\._octoprint\._tcp.local$", name)
if matches:
name = matches.group(1)
self.setPriority(2) # Make sure the output device gets selected above local file output
self.setName(name)
self.setShortDescription(i18n_catalog.i18nc("@action:button", "Print with OctoPrint"))
self.setDescription(i18n_catalog.i18nc("@properties:tooltip", "Print with OctoPrint"))
self.setIconName("print")
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected to OctoPrint on {0}").format(self._id))
self._post_gcode_reply = None
self._progress_message = None # type: Optional[Message]
self._error_message = None # type: Optional[Message]
self._waiting_message = None # type: Optional[Message]
self._queued_gcode_commands = [] # type: List[str]
# TODO; Add preference for update intervals
self._update_fast_interval = 2000
self._update_slow_interval = 10000
self._update_timer = QTimer()
self._update_timer.setInterval(self._update_fast_interval)
self._update_timer.setSingleShot(False)
self._update_timer.timeout.connect(self._update)
self._webcams_model = WebcamsModel(self._protocol, self._address, self.port, self._basic_auth_string)
self._show_camera = True
self._power_plugins_manager = PowerPlugins()
self._store_on_sd_supported = False # store gcode on sd card in printer instead of locally
self._ufp_transfer_supported = False # transfer gcode as .ufp files including thumbnail image
self._gcode_analysis_supported = False # wait for analysis to complete before starting a print
self._ufp_plugin_version = Version(0) # used to determine how gcode files are extracted from .ufp
self._waiting_for_analysis = False
self._waiting_for_printer = False
self._output_controller = OctoPrintOutputController(self)
self._polling_end_points = ["printer", "job"]
@property
def _store_on_sd(self) -> bool:
global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
if global_container_stack:
return self._store_on_sd_supported and parseBool(global_container_stack.getMetaDataEntry("octoprint_store_sd", False))
return False
@property
def _transfer_as_ufp(self) -> bool:
return self._ufp_transfer_supported and not self._store_on_sd
@property
def _wait_for_analysis(self) -> bool:
return self._gcode_analysis_supported and not self._store_on_sd
def getProperties(self) -> Dict[bytes, bytes]:
return self._properties
@pyqtSlot(str, result = str)
def getProperty(self, key: str) -> str:
key_b = key.encode("utf-8")
if key_b in self._properties:
return self._properties.get(key_b, b"").decode("utf-8")
else:
return ""
## Get the unique key of this machine
# \return key String containing the key of the machine.
@pyqtSlot(result = str)
def getId(self) -> str:
return self._id
## Set the API key of this OctoPrint instance
def setApiKey(self, api_key: str) -> None:
self._api_key = api_key.encode()
## Name of the instance (as returned from the zeroConf properties)
@pyqtProperty(str, constant = True)
def name(self) -> str:
return self._name
additionalDataChanged = pyqtSignal()
## Version (as returned from the zeroConf properties or from /api/version)
@pyqtProperty(str, notify=additionalDataChanged)
def octoPrintVersion(self) -> str:
return self._octoprint_version
@pyqtProperty(str, notify=additionalDataChanged)
def octoPrintUserName(self) -> str:
return self._octoprint_user_name
def resetOctoPrintUserName(self) -> None:
self._octoprint_user_name = ""
@pyqtProperty(str, notify=additionalDataChanged)
def printerName(self) -> str:
return self._printer_name
@pyqtProperty(str, notify=additionalDataChanged)
def printerModel(self) -> str:
return self._printer_model
def getAxisInformation(self) -> Dict[str, AxisInformation]:
return self._axis_information
## IPadress of this instance
@pyqtProperty(str, constant=True)
def ipAddress(self) -> str:
return self._address
## IPadress of this instance
# Overridden from NetworkedPrinterOutputDevice because OctoPrint does not
# send the ip address with zeroconf
@pyqtProperty(str, notify=additionalDataChanged)
def address(self) -> str:
if self._octoprint_user_name:
return "%s@%s" % (self._octoprint_user_name, self._address)
else:
return self._address
## port of this instance
@pyqtProperty(int, constant=True)
def port(self) -> int:
return self._port
## path of this instance
@pyqtProperty(str, constant=True)
def path(self) -> str:
return self._path
## absolute url of this instance
@pyqtProperty(str, constant=True)
def baseURL(self) -> str:
return self._base_url
@pyqtProperty("QVariant", constant=True)
def webcamsModel(self) -> WebcamsModel:
return self._webcams_model
def setShowCamera(self, show_camera: bool) -> None:
if show_camera != self._show_camera:
self._show_camera = show_camera
self.showCameraChanged.emit()
showCameraChanged = pyqtSignal()
@pyqtProperty(bool, notify=showCameraChanged)
def showCamera(self) -> bool:
return self._show_camera
def _update(self) -> None:
for end_point in self._polling_end_points:
self.get(end_point, self._onRequestFinished)
def close(self) -> None:
self._update_timer.stop()
self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Closed))
if self._progress_message:
self._progress_message.hide()
self._progress_message = None #type: Optional[Message]
if self._error_message:
self._error_message.hide()
self._error_message = None #type: Optional[Message]
if self._waiting_message:
self._waiting_message.hide()
self._waiting_message = None #type: Optional[Message]
self._waiting_for_printer = False
self._waiting_for_analysis = False
self._polling_end_points = [point for point in self._polling_end_points if not point.startswith("files/")]
## Start requesting data from the instance
def connect(self) -> None:
self._createNetworkManager()
self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Connecting))
self._update() # Manually trigger the first update, as we don't want to wait a few secs before it starts.
Logger.log("d", "Connection with instance %s with url %s started", self._id, self._base_url)
self._update_timer.start()
self._last_response_time = None # type: Optional[float]
self._setAcceptsCommands(False)
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connecting to OctoPrint on {0}").format(self._id))
## Request 'settings' dump
self.get("settings", self._onRequestFinished)
self.getAdditionalData()
def getAdditionalData(self) -> None:
if not self._octoprint_version:
self.get("version", self._onRequestFinished)
if not self._octoprint_user_name and self._api_key:
self._sendCommandToApi("login", {"passive":True})
self.get("printerprofiles", self._onRequestFinished)
## Stop requesting data from the instance
def disconnect(self) -> None:
Logger.log("d", "Connection with instance %s with url %s stopped", self._id, self._base_url)
self.close()
def pausePrint(self) -> None:
self._sendJobCommand("pause")
def resumePrint(self) -> None:
if not self._printers[0].activePrintJob:
return
if self._printers[0].activePrintJob.state == "paused":
self._sendJobCommand("pause")
else:
self._sendJobCommand("start")
def cancelPrint(self) -> None:
self._sendJobCommand("cancel")
def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False,
file_handler: Optional["FileHandler"] = None, filter_by_machine: bool = False, **kwargs) -> None:
global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
if not global_container_stack:
return
# Make sure post-processing plugin are run on the gcode
self.writeStarted.emit(self)
# Get the g-code through the GCodeWriter plugin
# This produces the same output as "Save to File", adding the print settings to the bottom of the file
if not self._transfer_as_ufp:
gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
self._gcode_stream = StringIO()
else:
gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("UFPWriter"))
self._gcode_stream = BytesIO()
if not gcode_writer.write(self._gcode_stream, None):
Logger.log("e", "GCodeWrite failed: %s" % gcode_writer.getInformation())
return
if self._error_message:
self._error_message.hide()
self._error_message = None # type: Optional[Message]
if self._progress_message:
self._progress_message.hide()
self._progress_message = None # type: Optional[Message]
self._auto_print = parseBool(global_container_stack.getMetaDataEntry("octoprint_auto_print", True))
self._auto_select = parseBool(global_container_stack.getMetaDataEntry("octoprint_select_print", False))
self._forced_queue = False
use_power_plugin = parseBool(global_container_stack.getMetaDataEntry("octoprint_power_control", False))
auto_connect = parseBool(global_container_stack.getMetaDataEntry("octoprint_auto_connect", False))
if self.activePrinter.state == "offline" and self._auto_print and (use_power_plugin or auto_connect):
wait_for_printer = False
if use_power_plugin:
available_plugs = self._power_plugins_manager.getAvailablePowerPlugs()
power_plug_id = global_container_stack.getMetaDataEntry("octoprint_power_plug", "")
if power_plug_id == "" and len(available_plugs) > 0:
power_plug_id = list(self._power_plugins_manager.getAvailablePowerPlugs().keys())[0]
if power_plug_id in available_plugs:
(end_point, command) = self._power_plugins_manager.getSetStateCommand(power_plug_id, True)
if end_point and command:
self._sendCommandToApi(end_point, command)
Logger.log("d", "Sent %s command to endpoint %s" % (command["command"], end_point))
wait_for_printer = True
else:
Logger.log("e", "No command to power on plug %s", power_plug_id)
else:
Logger.log("e", "Specified power plug %s is not available", power_plug_id)
else: # auto_connect
self._sendCommandToApi("connection", "connect")
Logger.log("d", "Sent command to connect printer to OctoPrint with current settings")
wait_for_printer = True
if wait_for_printer:
self._waiting_message = Message(
i18n_catalog.i18nc("@info:status", "Waiting for OctoPrint to connect to the printer..."),
title=i18n_catalog.i18nc("@label", "OctoPrint"),
progress=-1, lifetime=0, dismissable=False, use_inactivity_timer=False
)
self._waiting_message.addAction(
"queue", i18n_catalog.i18nc("@action:button", "Queue"), "",
i18n_catalog.i18nc("@action:tooltip", "Stop waiting for the printer and queue the printjob instead"),
button_style=Message.ActionButtonStyle.SECONDARY
)
self._waiting_message.addAction(
"cancel", i18n_catalog.i18nc("@action:button", "Cancel"), "",
i18n_catalog.i18nc("@action:tooltip", "Abort the printjob")
)
self._waiting_message.actionTriggered.connect(self._stopWaitingForPrinter)
self._waiting_message.show()
self._waiting_for_printer = True
return
elif self.activePrinter.state not in ["idle", ""]:
Logger.log("d", "Tried starting a print, but current state is %s" % self.activePrinter.state)
error_string = ""
if not self._auto_print:
# Allow queueing the job even if OctoPrint is currently busy if autoprinting is disabled
pass
elif self.activePrinter.state == "offline":
error_string = i18n_catalog.i18nc("@info:status", "The printer is offline. Unable to start a new job.")
else:
error_string = i18n_catalog.i18nc("@info:status", "OctoPrint is busy. Unable to start a new job.")
if error_string:
if self._error_message:
self._error_message.hide()
self._error_message = Message(error_string, title=i18n_catalog.i18nc("@label", "OctoPrint error"))
self._error_message.addAction(
"queue", i18n_catalog.i18nc("@action:button", "Queue job"), "",
i18n_catalog.i18nc("@action:tooltip", "Queue this print job so it can be printed later")
)
self._error_message.actionTriggered.connect(self._queuePrintJob)
self._error_message.show()
return
self._sendPrintJob()
def _stopWaitingForAnalysis(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
if self._waiting_message:
self._waiting_message.hide()
self._waiting_for_analysis = False
for end_point in self._polling_end_points:
if "files/" in end_point:
break
if "files/" not in end_point:
Logger.log("e", "Could not find files/ endpoint")
return
self._polling_end_points = [point for point in self._polling_end_points if not point.startswith("files/")]
if action_id == "print":
self._selectAndPrint(end_point)
elif action_id == "cancel":
pass
def _stopWaitingForPrinter(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
if self._waiting_message:
self._waiting_message.hide()
self._waiting_for_printer = False
if action_id == "queue":
self._queuePrintJob()
elif action_id == "cancel":
self._gcode_stream = StringIO() # type: Union[StringIO, BytesIO]
def _queuePrintJob(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
if self._error_message:
self._error_message.hide()
self._forced_queue = True
self._sendPrintJob()
def _sendPrintJob(self) -> None:
global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
if not global_container_stack:
return
if self._auto_print and not self._forced_queue:
CuraApplication.getInstance().getController().setActiveStage("MonitorStage")
# cancel any ongoing preheat timer before starting a print
try:
self._printers[0].stopPreheatTimers()
except AttributeError:
# stopPreheatTimers was added after Cura 3.3 beta
pass
self._progress_message = Message(
i18n_catalog.i18nc("@info:status", "Sending data to OctoPrint"),
title=i18n_catalog.i18nc("@label", "OctoPrint"),
progress=-1, lifetime=0, dismissable=False, use_inactivity_timer=False
)
self._progress_message.addAction(
"cancel", i18n_catalog.i18nc("@action:button", "Cancel"), "",
i18n_catalog.i18nc("@action:tooltip", "Abort the printjob")
)
self._progress_message.actionTriggered.connect(self._cancelSendGcode)
self._progress_message.show()
job_name = CuraApplication.getInstance().getPrintInformation().jobName.strip()
if job_name is "":
job_name = "untitled_print"
extension = "gcode" if not self._transfer_as_ufp else "ufp"
file_name = "%s.%s" % (os.path.basename(job_name), extension)
## Create multi_part request
post_parts = [] # type: List[QHttpPart]
## Create parts (to be placed inside multipart)
gcode_body = self._gcode_stream.getvalue()
if isinstance(gcode_body, str):
# encode StringIO result to bytes
gcode_body = gcode_body.encode()
post_parts.append(self._createFormPart("name=\"path\"", os.path.dirname(job_name).encode(), "text/plain"))
post_parts.append(self._createFormPart("name=\"file\"; filename=\"%s\"" % file_name, gcode_body, "application/octet-stream"))
if self._store_on_sd or (not self._wait_for_analysis and not self._transfer_as_ufp):
self._select_and_print_handled_in_upload = True
if self._auto_print and not self._forced_queue:
# tell OctoPrint to start the print when there is no reason to delay doing so
post_parts.append(self._createFormPart("name=\"print\"", b"true", "text/plain"))
if self._auto_select:
post_parts.append(self._createFormPart("name=\"select\"", b"true", "text/plain"))
else:
self._select_and_print_handled_in_upload = False
# otherwise selecting and printing the job is delayed until after the upload
# see self._onUploadFinished
destination = "local"
if self._store_on_sd:
destination = "sdcard"
try:
## Post request + data
post_gcode_request = self._createEmptyRequest("files/" + destination)
self._post_gcode_reply = self.postFormWithParts(
"files/" + destination,
post_parts,
on_finished=self._onUploadFinished,
on_progress=self._onUploadProgress
)
except Exception as e:
self._progress_message.hide()
self._error_message = Message(
i18n_catalog.i18nc("@info:status", "Unable to send data to OctoPrint."),
title=i18n_catalog.i18nc("@label", "OctoPrint error")
)
self._error_message.show()
Logger.log("e", "An exception occurred in network connection: %s" % str(e))
self._gcode_stream = StringIO() # type: Union[StringIO, BytesIO]
def _cancelSendGcode(self, message_id: Optional[str] = None, action_id: Optional[str] = None) -> None:
if self._post_gcode_reply:
Logger.log("d", "Stopping upload because the user pressed cancel.")
try:
self._post_gcode_reply.uploadProgress.disconnect(self._onUploadProgress)
except TypeError:
pass # The disconnection can fail on mac in some cases. Ignore that.
self._post_gcode_reply.abort()
self._post_gcode_reply = None # type:Optional[QNetworkReply]
if self._progress_message:
self._progress_message.hide()
self._progress_message = None # type:Optional[Message]
def sendCommand(self, command: str) -> None:
self._queued_gcode_commands.append(command)
CuraApplication.getInstance().callLater(self._sendQueuedGcode)
# Send gcode commands that are queued in quick succession as a single batch
def _sendQueuedGcode(self) -> None:
if self._queued_gcode_commands:
self._sendCommandToApi("printer/command", self._queued_gcode_commands)
Logger.log("d", "Sent gcode command to OctoPrint instance: %s", self._queued_gcode_commands)
self._queued_gcode_commands = [] # type: List[str]
def _sendJobCommand(self, command: str) -> None:
self._sendCommandToApi("job", command)
Logger.log("d", "Sent job command to OctoPrint instance: %s", command)
def _sendCommandToApi(self, end_point: str, commands: Union[Dict[str, Any], str, List[str]]) -> None:
if isinstance(commands, dict):
data = json.dumps(commands)
elif isinstance(commands, list):
data = json.dumps({"commands": commands})
else:
data = json.dumps({"command": commands})
self.post(end_point, data, self._onRequestFinished)
## Handler for all requests that have finished.
def _onRequestFinished(self, reply: QNetworkReply) -> None:
if reply.error() == QNetworkReply.TimeoutError:
Logger.log("w", "Received a timeout on a request to the instance")
self._connection_state_before_timeout = self._connection_state
self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Error))
return
if self._connection_state_before_timeout and reply.error() == QNetworkReply.NoError:
# There was a timeout, but we got a correct answer again.
if self._last_response_time:
Logger.log("d", "We got a response from the instance after %s of silence", time() - self._last_response_time)
self.setConnectionState(self._connection_state_before_timeout)
self._connection_state_before_timeout = None
if reply.error() == QNetworkReply.NoError:
self._last_response_time = time()
http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
if not http_status_code:
# Received no or empty reply
return
if reply.operation() == QNetworkAccessManager.GetOperation:
if self._api_prefix + "printerprofiles" in reply.url().toString():
if http_status_code == 200:
try:
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.log("w", "Received invalid JSON from octoprint instance.")
json_data = {}
for profile_id in json_data["profiles"]:
printer_profile = json_data["profiles"][profile_id]
if printer_profile["current"]:
self._printer_name = printer_profile["name"]
self._printer_model = printer_profile["model"]
for axis in ["x", "y", "z", "e"]:
self._axis_information[axis] = AxisInformation(
speed=printer_profile["axes"][axis]["speed"],
inverted=printer_profile["axes"][axis]["inverted"]
)
self.additionalDataChanged.emit()
return
else:
Logger.log("w", "Instance does not report printerprofiles with provided API key")
return
elif self._api_prefix + "printer" in reply.url().toString(): # Status update from /printer.
if not self._printers:
self._createPrinterList()
# An OctoPrint instance has a single printer.
printer = self._printers[0]
update_pace = self._update_slow_interval
if http_status_code == 200:
update_pace = self._update_fast_interval
if not self.acceptsCommands:
self._setAcceptsCommands(True)
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected to OctoPrint on {0}").format(self._id))
if self._connection_state == UnifiedConnectionState.Connecting:
self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Connected))
try:
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.log("w", "Received invalid JSON from octoprint instance.")
json_data = {}
if "temperature" in json_data:
if not self._number_of_extruders_set:
self._number_of_extruders = 0
while "tool%d" % self._number_of_extruders in json_data["temperature"]:
self._number_of_extruders += 1
if self._number_of_extruders > 1:
# Recreate list of printers to match the new _number_of_extruders
self._createPrinterList()
printer = self._printers[0]
if self._number_of_extruders > 0:
self._number_of_extruders_set = True
# Check for hotend temperatures
for index in range(0, self._number_of_extruders):
extruder = printer.extruders[index]
if ("tool%d" % index) in json_data["temperature"]:
hotend_temperatures = json_data["temperature"]["tool%d" % index]
target_temperature = hotend_temperatures["target"] if hotend_temperatures["target"] is not None else -1
actual_temperature = hotend_temperatures["actual"] if hotend_temperatures["actual"] is not None else -1
extruder.updateTargetHotendTemperature(target_temperature)
extruder.updateHotendTemperature(actual_temperature)
else:
extruder.updateTargetHotendTemperature(0)
extruder.updateHotendTemperature(0)
if "bed" in json_data["temperature"]:
bed_temperatures = json_data["temperature"]["bed"]
actual_temperature = bed_temperatures["actual"] if bed_temperatures["actual"] is not None else -1
printer.updateBedTemperature(actual_temperature)
target_temperature = bed_temperatures["target"] if bed_temperatures["target"] is not None else -1
printer.updateTargetBedTemperature(target_temperature)
else:
printer.updateBedTemperature(-1)
printer.updateTargetBedTemperature(0)
printer_state = "offline"
if "state" in json_data:
flags = json_data["state"]["flags"]
if flags["error"] or flags["closedOrError"]:
printer_state = "error"
elif flags["paused"] or flags["pausing"]:
printer_state = "paused"
elif flags["printing"]:
printer_state = "printing"
elif flags["cancelling"]:
printer_state = "aborted"
elif flags["ready"] or flags["operational"]:
printer_state = "idle"
else:
Logger.log("w", "Encountered unexpected printer state flags: %s" % flags)
printer.updateState(printer_state)
elif http_status_code == 401 or http_status_code == 403:
self._setOffline(printer, i18n_catalog.i18nc(
"@info:status", "OctoPrint on {0} does not allow access to the printer state").format(self._id)
)
return
elif http_status_code == 409:
if self._connection_state == UnifiedConnectionState.Connecting:
self.setConnectionState(cast(ConnectionState, UnifiedConnectionState.Connected))
self._setOffline(printer, i18n_catalog.i18nc(
"@info:status", "The printer connected to OctoPrint on {0} is not operational").format(self._id)
)
return
elif http_status_code == 502 or http_status_code == 503:
Logger.log("w", "Received an error status code: %d", http_status_code)
self._setOffline(printer, i18n_catalog.i18nc(
"@info:status", "OctoPrint on {0} is not running").format(self._id)
)
return
else:
self._setOffline(printer)
Logger.log("w", "Received an unexpected status code: %d", http_status_code)
if update_pace != self._update_timer.interval():
self._update_timer.setInterval(update_pace)
elif self._api_prefix + "job" in reply.url().toString(): # Status update from /job:
if not self._printers:
return # Ignore the data for now, we don't have info about a printer yet.
printer = self._printers[0]
if http_status_code == 200:
try:
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.log("w", "Received invalid JSON from octoprint instance.")
json_data = {}
if printer.activePrintJob is None:
print_job = PrintJobOutputModel(output_controller=self._output_controller)
printer.updateActivePrintJob(print_job)
else:
print_job = printer.activePrintJob
print_job_state = "offline"
if "state" in json_data:
state = json_data["state"]
if not isinstance(state, str):
Logger.log("e", "Encountered non-string printjob state: %s" % state)
elif state.startswith("Error"):
print_job_state = "error"
elif state == "Pausing":
print_job_state = "pausing"
elif state == "Paused":
print_job_state = "paused"
elif state.startswith("Printing"):
print_job_state = "printing"
elif state == "Cancelling":
print_job_state = "abort"
elif state == "Operational":
print_job_state = "ready"
printer.updateState("idle")
elif state.startswith("Starting") or state == "Connecting" or state == "Sending file to SD":
print_job_state = "pre_print"
elif state.startswith("Offline"):
print_job_state = "offline"
else:
Logger.log("w", "Encountered unexpected printjob state: %s" % state)
print_job.updateState(print_job_state)
print_time = json_data["progress"]["printTime"]
completion = json_data["progress"]["completion"]
if print_time:
print_job.updateTimeElapsed(print_time)
print_time_left = json_data["progress"]["printTimeLeft"]
if print_time_left: # not 0 or None or ""
print_job.updateTimeTotal(print_time + print_time_left)
elif completion: # not 0 or None or ""
print_job.updateTimeTotal(print_time / (completion / 100))
else:
print_job.updateTimeTotal(0)
else:
print_job.updateTimeElapsed(0)
print_job.updateTimeTotal(0)
if completion and print_job_state == "pre_print": # completion not not 0 or None or "", state "Sending file to SD"
if not self._progress_message:
self._progress_message = Message(
i18n_catalog.i18nc("@info:status", "Streaming file to the printer SD card"),
0, False, -1, title=i18n_catalog.i18nc("@label", "OctoPrint")
)
self._progress_message.show()
if completion < 100:
self._progress_message.setProgress(completion)
else:
if self._progress_message and self._progress_message.getText().startswith(
i18n_catalog.i18nc("@info:status", "Streaming file to the printer SD card")
):
self._progress_message.hide()
self._progress_message = None # type:Optional[Message]
print_job.updateName(json_data["job"]["file"]["name"])
if self._waiting_for_printer and printer.state == "idle":
self._waiting_for_printer = False
if self._waiting_message:
self._waiting_message.hide()
self._waiting_message = None
self._sendPrintJob()
elif http_status_code == 401 or http_status_code == 403:
self._setOffline(printer, i18n_catalog.i18nc(
"@info:status", "OctoPrint on {0} does not allow access to the job state").format(self._id)
)
return
elif http_status_code == 502 or http_status_code == 503:
Logger.log("w", "Received an error status code: %d", http_status_code)
self._setOffline(printer, i18n_catalog.i18nc(
"@info:status", "OctoPrint on {0} is not running").format(self._id)
)
return
else:
pass # See generic error handler below
elif self._api_prefix + "settings" in reply.url().toString(): # OctoPrint settings dump from /settings:
if http_status_code == 200:
try:
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.log("w", "Received invalid JSON from octoprint instance.")
json_data = {}
self.parseSettingsData(json_data)
elif self._api_prefix + "version" in reply.url().toString(): # OctoPrint & API version
if http_status_code == 200:
try:
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.log("w", "Received invalid JSON from octoprint instance.")
json_data = {}
if "server" in json_data:
self._octoprint_version = json_data["server"]
self.additionalDataChanged.emit()
elif http_status_code == 404:
Logger.log("w", "Instance does not support reporting its version")
return
elif self._api_prefix + "files/" in reply.url().toString(): # Information about a file
if http_status_code == 200:
if not self._waiting_for_analysis:
return
end_point = reply.url().toString().split(self._api_prefix, 1)[1]
try:
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
except json.decoder.JSONDecodeError:
Logger.log("w", "Received invalid JSON from octoprint instance.")
json_data = {}
if "gcodeAnalysis" in json_data and "progress" in json_data["gcodeAnalysis"]:
Logger.log("d", "PrintTimeGenius analysis of %s is done" % end_point)
self._waiting_for_analysis = False
if self._waiting_message:
self._waiting_message.hide()
self._waiting_message = None
self._polling_end_points = [point for point in self._polling_end_points if not point.startswith("files/")]
self._selectAndPrint(end_point)
else:
Logger.log("d", "Still waiting for PrintTimeGenius analysis of %s" % end_point)
elif reply.operation() == QNetworkAccessManager.PostOperation:
if self._api_prefix + "files" in reply.url().toString(): # Result from /files command to start a printjob:
if http_status_code == 204:
Logger.log("d", "OctoPrint file command accepted")
elif http_status_code == 401 or http_status_code == 403:
error_string = i18n_catalog.i18nc("@info:error", "You are not allowed to start print jobs on OctoPrint with the configured API key.")
self._showErrorMessage(error_string)
return
elif http_status_code == 404 and "files/sdcard/" in reply.url().toString():
Logger.log("d", "OctoPrint reports an 404 not found error after uploading to SD-card, but we ignore that")
return
else:
pass # See generic error handler below
elif self._api_prefix + "job" in reply.url().toString(): # Result from /job command (eg start/pause):
if http_status_code == 204:
Logger.log("d", "OctoPrint job command accepted")
elif http_status_code == 401 or http_status_code == 403:
error_string = i18n_catalog.i18nc("@info:error", "You are not allowed to control print jobs on OctoPrint with the configured API key.")
self._showErrorMessage(error_string)
return
else:
pass # See generic error handler below
elif self._api_prefix + "printer/command" in reply.url().toString(): # Result from /printer/command (gcode statements):
if http_status_code == 204:
Logger.log("d", "OctoPrint gcode command(s) accepted")
elif http_status_code == 401 or http_status_code == 403:
error_string = i18n_catalog.i18nc("@info:error", "You are not allowed to send gcode commands to OctoPrint with the configured API key.")
self._showErrorMessage(error_string)
return
else:
pass # See generic error handler below
elif self._api_prefix + "login" in reply.url().toString():
if http_status_code == 200: