forked from OctoPrint/octoprint-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comm.py
4730 lines (3799 loc) · 161 KB
/
comm.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
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <[email protected]> based on work by David Braam"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
import os
import glob
import time
import re
import threading
import contextlib
import copy
try:
import queue
except ImportError:
import Queue as queue
from past.builtins import basestring
import logging
import serial
import wrapt
import octoprint.plugin
from collections import deque
from octoprint.util.avr_isp import stk500v2
from octoprint.util.avr_isp import ispBase
from octoprint.settings import settings, default_settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer
try:
import _winreg
except:
pass
_logger = logging.getLogger(__name__)
# a bunch of regexes we'll need for the communication parsing...
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+"
regex_command = re.compile("^\s*((?P<codeGM>[GM]\d+)(\\.(?P<subcode>\d+))?|(?P<codeT>T)\d+|(?P<codeF>F)\d+)")
"""Regex for a GCODE command."""
regex_float = re.compile(regex_float_pattern)
"""Regex for a float value."""
regexes_parameters = dict(
floatE=re.compile("(^|[^A-Za-z])[Ee](?P<value>%s)" % regex_float_pattern),
floatF=re.compile("(^|[^A-Za-z])[Ff](?P<value>%s)" % regex_float_pattern),
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
floatR=re.compile("(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
floatX=re.compile("(^|[^A-Za-z])[Xx](?P<value>%s)" % regex_float_pattern),
floatY=re.compile("(^|[^A-Za-z])[Yy](?P<value>%s)" % regex_float_pattern),
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
intS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_int_pattern),
intT=re.compile("(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
)
"""Regexes for parsing various GCODE command parameters."""
regex_minMaxError = re.compile("Error:[0-9]\n")
"""Regex matching first line of min/max errors from the firmware."""
regex_sdPrintingByte = re.compile("(?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
regex_sdFileOpened = re.compile("File opened:\s*(?P<name>.*?)\s+Size:\s*(?P<size>%s)" % regex_int_pattern)
"""Regex matching "File opened" messages from the firmware.
Groups will be as follows:
* ``name``: name of the file reported as having been opened (str)
* ``size``: size of the file in bytes (int)
"""
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_float_pattern, regex_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_float_pattern)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
regex_position = re.compile("X:(?P<x>{float})\s*Y:(?P<y>{float})\s*Z:(?P<z>{float})\s*((E:(?P<e>{float}))|(?P<es>(E\d+:{float}\s*)+))".format(float=regex_float_pattern))
"""Regex for matching position reporting.
Groups will be as follows:
* ``x``: X coordinate
* ``y``: Y coordinate
* ``z``: Z coordinate
* ``e``: E coordinate if present, or
* ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions
"""
regex_e_positions = re.compile("E(?P<id>\d+):(?P<value>{float})".format(float=regex_float_pattern))
"""Regex for matching multiple E coordinates in a position report.
Groups will be as follows:
* ``id``: id of the extruder or which the position is reported
* ``value``: reported position value
"""
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):\s*")
"""Regex to use for splitting M115 responses."""
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
def serialList():
baselist=[]
if os.name=="nt":
try:
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
i=0
while(1):
baselist+=[_winreg.EnumValue(key,i)[1]]
i+=1
except:
pass
baselist = baselist \
+ glob.glob("/dev/ttyUSB*") \
+ glob.glob("/dev/ttyACM*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/cuaU*") \
+ glob.glob("/dev/rfcomm*")
additionalPorts = settings().get(["serial", "additionalPorts"])
for additional in additionalPorts:
if '://' in additional: # Begin -----
baselist.append(additional) # -----------
else: # End -------
baselist += glob.glob(additional) # Indent this
prev = settings().get(["serial", "port"])
if prev in baselist:
baselist.remove(prev)
baselist.insert(0, prev)
if settings().getBoolean(["devel", "virtualPrinter", "enabled"]):
baselist.append("VIRTUAL")
return baselist
def baudrateList():
# sorted by likelihood
candidates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
# additional baudrates prepended, sorted descending
additionalBaudrates = settings().get(["serial", "additionalBaudrates"])
for additional in sorted(additionalBaudrates, reverse=True):
try:
candidates.insert(0, int(additional))
except:
_logger.warn("{} is not a valid additional baudrate, ignoring it".format(additional))
# last used baudrate = first to try, move to start
prev = settings().getInt(["serial", "baudrate"])
if prev in candidates:
candidates.remove(prev)
candidates.insert(0, prev)
return candidates
gcodeToEvent = {
# pause for user input
"M226": Events.WAITING,
"M0": Events.WAITING,
"M1": Events.WAITING,
# dwell command
"G4": Events.DWELL,
# part cooler
"M245": Events.COOLING,
# part conveyor
"M240": Events.CONVEYOR,
# part ejector
"M40": Events.EJECT,
# user alert
"M300": Events.ALERT,
# home print head
"G28": Events.HOME,
# emergency stop
"M112": Events.E_STOP,
# motors on/off
"M80": Events.POWER_ON,
"M81": Events.POWER_OFF,
}
class PositionRecord(object):
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
@classmethod
def valid_e(cls, attr):
if not attr.startswith("e"):
return False
try:
int(attr[1:])
except:
return False
return True
def __init__(self, *args, **kwargs):
attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, kwargs.get(attr))
def copy_from(self, other):
# make sure all standard attrs and attrs from other are set
attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, getattr(other, attr))
# delete attrs other doesn't have
attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs
for attr in attrs:
delattr(self, attr)
def as_dict(self):
attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)])
return dict((attr, getattr(self, attr)) for attr in attrs)
class TemperatureRecord(object):
def __init__(self):
self._tools = dict()
self._bed = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
def as_script_dict(self):
result = dict()
tools = self.tools
for tool, data in tools.items():
result[tool] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["b"] = dict(actual=bed[0],
target=bed[1])
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
class MachineCom(object):
STATE_NONE = 0
STATE_OPEN_SERIAL = 1
STATE_DETECT_SERIAL = 2
STATE_DETECT_BAUDRATE = 3
STATE_CONNECTING = 4
STATE_OPERATIONAL = 5
STATE_PRINTING = 6
STATE_PAUSED = 7
STATE_CLOSED = 8
STATE_ERROR = 9
STATE_CLOSED_WITH_ERROR = 10
STATE_TRANSFERING_FILE = 11
STATE_CANCELLING = 12
STATE_PAUSING = 13
STATE_RESUMING = 14
STATE_FINISHING = 15
# be sure to add anything here that signifies an operational state
OPERATIONAL_STATES = (STATE_PRINTING, STATE_OPERATIONAL, STATE_PAUSED, STATE_CANCELLING, STATE_PAUSING,
STATE_RESUMING, STATE_FINISHING, STATE_TRANSFERING_FILE)
# be sure to add anything here that signifies a printing state
PRINTING_STATES = (STATE_PRINTING, STATE_CANCELLING, STATE_PAUSING, STATE_RESUMING, STATE_FINISHING)
CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP"
CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS"
CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL"
CAPABILITY_SUPPORT_ENABLED = "enabled"
CAPABILITY_SUPPORT_DETECTED = "detected"
CAPABILITY_SUPPORT_DISABLED = "disabled"
def __init__(self, port = None, baudrate=None, callbackObject=None, printerProfileManager=None):
self._logger = logging.getLogger(__name__)
self._serialLogger = logging.getLogger("SERIAL")
self._phaseLogger = logging.getLogger(__name__ + ".command_phases")
if port == None:
port = settings().get(["serial", "port"])
if baudrate == None:
settingsBaudrate = settings().getInt(["serial", "baudrate"])
if settingsBaudrate is None:
baudrate = 0
else:
baudrate = settingsBaudrate
if callbackObject == None:
callbackObject = MachineComPrintCallback()
self._port = port
self._baudrate = baudrate
self._callback = callbackObject
self._printerProfileManager = printerProfileManager
self._state = self.STATE_NONE
self._serial = None
self._baudrateDetectList = []
self._baudrateDetectRetry = 0
self._temperatureTargetSetThreshold = 25
self._tempOffsets = dict()
self._command_queue = CommandQueue()
self._currentZ = None
self._currentF = None
self._heatupWaitStartTime = None
self._heatupWaitTimeLost = 0.0
self._pauseWaitStartTime = None
self._pauseWaitTimeLost = 0.0
self._currentTool = 0
self._toolBeforeChange = None
self._toolBeforeHeatup = None
self._knownInvalidTools = set()
self._long_running_command = False
self._heating = False
self._dwelling_until = False
self._connection_closing = False
self._timeout = None
self._ok_timeout = None
self._timeout_intervals = dict()
for key, value in settings().get(["serial", "timeout"], merged=True, asdict=True).items():
try:
self._timeout_intervals[key] = float(value)
except:
pass
self._consecutive_timeouts = 0
self._consecutive_timeout_maximums = dict()
for key, value in settings().get(["serial", "maxCommunicationTimeouts"], merged=True, asdict=True).items():
try:
self._consecutive_timeout_maximums[key] = int(value)
except:
pass
self._max_write_passes = settings().getInt(["serial", "maxWritePasses"])
self._hello_command = settings().get(["serial", "helloCommand"])
self._trigger_ok_for_m29 = settings().getBoolean(["serial", "triggerOkForM29"])
self._block_M0_M1 = settings().getBoolean(["serial", "blockM0M1"])
self._hello_command = settings().get(["serial", "helloCommand"])
self._alwaysSendChecksum = settings().getBoolean(["serial", "alwaysSendChecksum"])
self._neverSendChecksum = settings().getBoolean(["serial", "neverSendChecksum"])
self._sendChecksumWithUnknownCommands = settings().getBoolean(["serial", "sendChecksumWithUnknownCommands"])
self._unknownCommandsNeedAck = settings().getBoolean(["serial", "unknownCommandsNeedAck"])
self._sdAlwaysAvailable = settings().getBoolean(["serial", "sdAlwaysAvailable"])
self._sdRelativePath = settings().getBoolean(["serial", "sdRelativePath"])
self._blockWhileDwelling = settings().getBoolean(["serial", "blockWhileDwelling"])
self._currentLine = 1
self._line_mutex = threading.RLock()
self._resendDelta = None
self._capability_support = {
self.CAPABILITY_AUTOREPORT_TEMP: settings().getBoolean(["serial", "capabilities", "autoreport_temp"]),
self.CAPABILITY_AUTOREPORT_SD_STATUS: settings().getBoolean(["serial", "capabilities", "autoreport_sdstatus"]),
self.CAPABILITY_BUSY_PROTOCOL: settings().getBoolean(["serial", "capabilities", "busy_protocol"])
}
self._lastLines = deque([], 50)
self._lastCommError = None
self._lastResendNumber = None
self._currentResendCount = 0
self._firmware_detection = settings().getBoolean(["serial", "firmwareDetection"])
self._firmware_info_received = not self._firmware_detection
self._firmware_info = dict()
self._firmware_capabilities = dict()
self._temperature_autoreporting = False
self._sdstatus_autoreporting = False
self._busy_protocol_detected = False
self._trigger_ok_after_resend = settings().get(["serial", "supportResendsWithoutOk"])
self._resend_ok_timer = None
self._resendActive = False
self._terminal_log = deque([], 20)
self._disconnect_on_errors = settings().getBoolean(["serial", "disconnectOnErrors"])
self._ignore_errors = settings().getBoolean(["serial", "ignoreErrorsFromFirmware"])
self._log_resends = settings().getBoolean(["serial", "logResends"])
# don't log more resends than 5 / 60s
self._log_resends_rate_start = None
self._log_resends_rate_count = 0
self._log_resends_max = 5
self._log_resends_rate_frame = 60
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
self._send_queue = SendQueue()
self._temperature_timer = None
self._sd_status_timer = None
self._job_queue = JobQueue()
# hooks
self._pluginManager = octoprint.plugin.plugin_manager()
self._gcode_hooks = dict(
queuing=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queuing"),
queued=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queued"),
sending=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sending"),
sent=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sent")
)
self._received_message_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.received")
self._error_message_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.error")
self._atcommand_hooks = dict(
queuing=self._pluginManager.get_hooks("octoprint.comm.protocol.atcommand.queuing"),
sending=self._pluginManager.get_hooks("octoprint.comm.protocol.atcommand.sending")
)
self._firmware_info_hooks = dict(
info=self._pluginManager.get_hooks("octoprint.comm.protocol.firmware.info"),
capabilities=self._pluginManager.get_hooks("octoprint.comm.protocol.firmware.capabilities")
)
self._printer_action_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.action")
self._gcodescript_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
self._serial_factory_hooks = self._pluginManager.get_hooks("octoprint.comm.transport.serial.factory")
self._temperature_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.temperatures.received")
# SD status data
self._sdEnabled = settings().getBoolean(["feature", "sdSupport"])
self._sdAvailable = False
self._sdFileList = False
self._sdFiles = []
self._sdFileToSelect = None
self._sdFileToSelectUser = None
self._ignore_select = False
self._manualStreaming = False
self.last_temperature = TemperatureRecord()
self.pause_temperature = TemperatureRecord()
self.cancel_temperature = TemperatureRecord()
self.last_position = PositionRecord()
self.pause_position = PositionRecord()
self.cancel_position = PositionRecord()
self._record_pause_data = False
self._record_cancel_data = False
self._suppress_scripts = set()
self._suppress_scripts_mutex = threading.RLock()
self._pause_position_timer = None
self._pause_mutex = threading.RLock()
self._cancel_position_timer = None
self._cancel_mutex = threading.RLock()
self._log_position_on_pause = settings().getBoolean(["serial", "logPositionOnPause"])
self._log_position_on_cancel = settings().getBoolean(["serial", "logPositionOnCancel"])
# print job
self._currentFile = None
self._job_on_hold = CountedEvent()
# multithreading locks
self._jobLock = threading.RLock()
self._sendingLock = threading.RLock()
# monitoring thread
self._monitoring_active = True
self.monitoring_thread = threading.Thread(target=self._monitor, name="comm._monitor")
self.monitoring_thread.daemon = True
self.monitoring_thread.start()
# sending thread
self._send_queue_active = True
self.sending_thread = threading.Thread(target=self._send_loop, name="comm.sending_thread")
self.sending_thread.daemon = True
self.sending_thread.start()
def __del__(self):
self.close()
@property
def _active(self):
return self._monitoring_active and self._send_queue_active
##~~ internal state management
def _changeState(self, newState):
if self._state == newState:
return
if newState == self.STATE_CLOSED or newState == self.STATE_CLOSED_WITH_ERROR:
if settings().getBoolean(["feature", "sdSupport"]):
self._sdFileList = False
self._sdFiles = []
self._callback.on_comm_sd_files([])
if self._currentFile is not None:
if self.isBusy():
self._recordFilePosition()
self._currentFile.close()
oldState = self.getStateString()
self._state = newState
text = "Changing monitoring state from \"{}\" to \"{}\"".format(oldState, self.getStateString())
self._log(text)
self._logger.info(text)
self._callback.on_comm_state_change(newState)
def _dual_log(self, message, level=logging.ERROR):
self._logger.log(level, message)
self._log(message)
def _log(self, message):
self._terminal_log.append(message)
self._callback.on_comm_log(message)
self._serialLogger.debug(message)
def _to_logfile_with_terminal(self, message=None, level=logging.INFO):
log = u"Last lines in terminal:\n" + u"\n".join(map(lambda x: u"| {}".format(x), list(self._terminal_log)))
if message is not None:
log = message + u"\n| " + log
self._logger.log(level, log)
def _addToLastLines(self, cmd):
self._lastLines.append(cmd)
##~~ getters
def getState(self):
return self._state
def getStateId(self, state=None):
if state is None:
state = self._state
possible_states = filter(lambda x: x.startswith("STATE_"), self.__class__.__dict__.keys())
for possible_state in possible_states:
if getattr(self, possible_state) == state:
return possible_state[len("STATE_"):]
return "UNKNOWN"
def getStateString(self, state=None):
if state is None:
state = self._state
if state == self.STATE_NONE:
return "Offline"
elif state == self.STATE_OPEN_SERIAL:
return "Opening serial port"
elif state == self.STATE_DETECT_SERIAL:
return "Detecting serial port"
elif state == self.STATE_DETECT_BAUDRATE:
return "Detecting baudrate"
elif state == self.STATE_CONNECTING:
return "Connecting"
elif state == self.STATE_OPERATIONAL:
return "Operational"
elif state == self.STATE_PRINTING:
if self.isSdFileSelected():
return "Printing from SD"
elif self.isStreaming():
return "Sending file to SD"
else:
return "Printing"
elif state == self.STATE_CANCELLING:
return "Cancelling"
elif state == self.STATE_PAUSING:
return "Pausing"
elif state == self.STATE_PAUSED:
return "Paused"
elif state == self.STATE_RESUMING:
return "Resuming"
elif state == self.STATE_FINISHING:
return "Finishing"
elif state == self.STATE_CLOSED:
return "Offline"
elif state == self.STATE_ERROR:
return "Error: {}".format(self.getErrorString())
elif state == self.STATE_CLOSED_WITH_ERROR:
return "Offline (Error: {})".format(self.getErrorString())
elif state == self.STATE_TRANSFERING_FILE:
return "Transferring file to SD"
return "Unknown State ({})".format(self._state)
def getErrorString(self):
return self._errorValue
def isClosedOrError(self):
return self._state in (self.STATE_ERROR, self.STATE_CLOSED, self.STATE_CLOSED_WITH_ERROR)
def isError(self):
return self._state in (self.STATE_ERROR, self.STATE_CLOSED_WITH_ERROR)
def isOperational(self):
return self._state in self.OPERATIONAL_STATES
def isPrinting(self):
return self._state in self.PRINTING_STATES
def isCancelling(self):
return self._state == self.STATE_CANCELLING
def isPausing(self):
return self._state == self.STATE_PAUSING
def isResuming(self):
return self._state == self.STATE_RESUMING
def isFinishing(self):
return self._state == self.STATE_FINISHING
def isSdPrinting(self):
return self.isSdFileSelected() and self.isPrinting()
def isSdFileSelected(self):
return self._currentFile is not None and isinstance(self._currentFile, PrintingSdFileInformation)
def isStreaming(self):
return self._currentFile is not None and isinstance(self._currentFile, StreamingGcodeFileInformation) and not self._currentFile.done
def isPaused(self):
return self._state == self.STATE_PAUSED
def isBusy(self):
return self.isPrinting() or self.isPaused() or self._state in (self.STATE_CANCELLING, self.STATE_PAUSING)
def isSdReady(self):
return self._sdAvailable
def getPrintProgress(self):
if self._currentFile is None:
return None
return self._currentFile.getProgress()
def getPrintFilepos(self):
if self._currentFile is None:
return None
return self._currentFile.getFilepos()
def getPrintTime(self):
if self._currentFile is None or self._currentFile.getStartTime() is None:
return None
else:
return time.time() - self._currentFile.getStartTime() - self._pauseWaitTimeLost
def getCleanedPrintTime(self):
printTime = self.getPrintTime()
if printTime is None:
return None
cleanedPrintTime = printTime - self._heatupWaitTimeLost
if cleanedPrintTime < 0:
cleanedPrintTime = 0.0
return cleanedPrintTime
def getTemp(self):
return self.last_temperature.tools
def getBedTemp(self):
return self.last_temperature.bed
def getOffsets(self):
return dict(self._tempOffsets)
def getCurrentTool(self):
return self._currentTool
def getConnection(self):
return self._port, self._baudrate
def getTransport(self):
return self._serial
##~~ external interface
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
raise RuntimeError("Could not acquire job_on_hold lock")
self._job_on_hold.set()
try:
yield
finally:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._continue_sending()
self._job_on_hold.release()
@property
def job_on_hold(self):
return self._job_on_hold.counter > 0
def set_job_on_hold(self, value, blocking=True):
trigger = False
# don't run any locking code beyond this...
if not self._job_on_hold.acquire(blocking=blocking):
return False
try:
if value:
self._job_on_hold.set()
else:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
trigger = True
finally:
self._job_on_hold.release()
# locking code is now safe to run again
if trigger:
self._continue_sending()
return True
def close(self, is_error=False, wait=True, timeout=10.0, *args, **kwargs):
"""
Closes the connection to the printer.
If ``is_error`` is False, will attempt to send the ``beforePrinterDisconnected``
gcode script. If ``is_error`` is False and ``wait`` is True, will wait
until all messages in the send queue (including the ``beforePrinterDisconnected``
gcode script) have been sent to the printer.
Arguments:
is_error (bool): Whether the closing takes place due to an error (True)
or not (False, default)
wait (bool): Whether to wait for all messages in the send
queue to be processed before closing (True, default) or not (False)
"""
# legacy parameters
is_error = kwargs.get("isError", is_error)
if self._connection_closing:
return
self._connection_closing = True
if self._temperature_timer is not None:
try:
self._temperature_timer.cancel()
except:
pass
if self._sd_status_timer is not None:
try:
self._sd_status_timer.cancel()
except:
pass
def deactivate_monitoring_and_send_queue():
self._monitoring_active = False
self._send_queue_active = False
if self._serial is not None:
if not is_error:
self.sendGcodeScript("beforePrinterDisconnected")
if wait:
if timeout is not None:
stop = time.time() + timeout
while (self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks) and time.time() < stop:
time.sleep(0.1)
else:
self._command_queue.join()
self._send_queue.join()
deactivate_monitoring_and_send_queue()
try:
if hasattr(self._serial, "cancel_read") and callable(self._serial.cancel_read):
self._serial.cancel_read()
except:
self._logger.exception("Error while cancelling pending reads from the serial port")
try:
if hasattr(self._serial, "cancel_write") and callable(self._serial.cancel_write):
self._serial.cancel_write()
except:
self._logger.exception("Error while cancelling pending writes to the serial port")
try:
self._serial.close()
except:
self._logger.exception("Error while trying to close serial port")
is_error = True
# if we are printing, this will also make sure of firing PRINT_FAILED
if is_error:
self._changeState(self.STATE_CLOSED_WITH_ERROR)
else:
self._changeState(self.STATE_CLOSED)
else:
deactivate_monitoring_and_send_queue()
self._serial = None
if settings().getBoolean(["feature", "sdSupport"]):
self._sdFileList = []
def setTemperatureOffset(self, offsets):
self._tempOffsets.update(offsets)
def fakeOk(self):
self._handle_ok()
def sendCommand(self, cmd, cmd_type=None, part_of_job=False, processed=False, force=False, on_sent=None, tags=None):
if not isinstance(cmd, QueueMarker):
cmd = to_unicode(cmd, errors="replace")
if not processed:
cmd = process_gcode_line(cmd)
if not cmd:
return False
if tags is None:
tags = set()
if part_of_job:
self._job_queue.put((cmd, cmd_type, on_sent, tags | {"source:job"}))
return True
elif self.isPrinting() and not self.isSdFileSelected() and not self.job_on_hold and not force:
try:
self._command_queue.put((cmd, cmd_type, on_sent, tags), item_type=cmd_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in command queue: " + e.type)
return False
elif self.isOperational() or force:
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent, tags=tags)
def _getGcodeScript(self, scriptName, replacements=None):
context = dict()
if replacements is not None and isinstance(replacements, dict):
context.update(replacements)
context.update(dict(
printer_profile=self._printerProfileManager.get_current_or_default(),
last_position=self.last_position,
last_temperature=self.last_temperature.as_script_dict()
))
if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed":
context.update(dict(pause_position=self.pause_position,
pause_temperature=self.pause_temperature.as_script_dict()))
elif scriptName == "afterPrintCancelled":
context.update(dict(cancel_position=self.cancel_position,
cancel_temperature=self.cancel_temperature.as_script_dict()))
scriptLinesPrefix = []
scriptLinesSuffix = []
for name, hook in self._gcodescript_hooks.items():
try:
retval = hook(self, "gcode", scriptName)
except:
self._logger.exception("Error while processing hook {name}.".format(**locals()))
else:
if retval is None:
continue
if not isinstance(retval, (list, tuple)) or not len(retval) in [2, 3]:
continue
def to_list(data):
if isinstance(data, str):
data = map(str.strip, data.split("\n"))
elif isinstance(data, unicode):
data = map(unicode.strip, data.split("\n"))
if isinstance(data, (list, tuple)):
return list(data)
else:
return None
prefix, suffix = map(to_list, retval[0:2])
if prefix:
scriptLinesPrefix = list(prefix) + scriptLinesPrefix
if suffix:
scriptLinesSuffix += list(suffix)
if len(retval) == 3:
variables = retval[2]
context.update(dict(plugins={name:variables}))
template = settings().loadScript("gcode", scriptName, context=context)
if template is None:
scriptLines = []
else:
scriptLines = template.split("\n")
scriptLines = scriptLinesPrefix + scriptLines + scriptLinesSuffix
return filter(lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x, offsets=self._tempOffsets, current_tool=self._currentTool),
scriptLines))
def sendGcodeScript(self, scriptName, replacements=None, tags=None, part_of_job=False):
if tags is None:
tags = set()
scriptLines = self._getGcodeScript(scriptName, replacements=replacements)
tags_to_use = tags | {"trigger:comm.send_gcode_script", "source:script", "script:{}".format(scriptName)}
for line in scriptLines:
self.sendCommand(line, part_of_job=part_of_job, tags=tags_to_use)
return "\n".join(scriptLines)
def startPrint(self, pos=None, tags=None, external_sd=False):
if not self.isOperational() or self.isPrinting():
return
if self._currentFile is None: