-
Notifications
You must be signed in to change notification settings - Fork 998
/
pronsole.py
1778 lines (1611 loc) · 71.9 KB
/
pronsole.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
# This file is part of the Printrun suite.
#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import cmd
import glob
import os
import platform
import time
import threading
import sys
import shutil
import subprocess
import codecs
import argparse
import locale
import logging
import traceback
import re
from platformdirs import user_cache_dir, user_config_dir, user_data_dir
from serial import SerialException
from . import printcore
from .utils import install_locale, run_command, get_command_output, \
format_time, format_duration, RemainingTimeEstimator, \
get_home_pos, parse_build_dimensions, parse_temperature_report, \
setup_logging
install_locale('pronterface')
from .settings import Settings, BuildDimensionsSetting
from .power import powerset_print_start, powerset_print_stop
from printrun import gcoder
from .rpc import ProntRPC
from printrun.spoolmanager import spoolmanager
if os.name == "nt":
try:
import winreg
except:
pass
READLINE = True
try:
import readline
if os.name == "nt": # config pyreadline on Windows
readline.rl.mode.show_all_if_ambiguous = "on"
except ImportError:
READLINE = False # neither readline module is available
tempreading_exp = re.compile('\\bT\d*:')
REPORT_NONE = 0
REPORT_POS = 1
REPORT_TEMP = 2
REPORT_MANUAL = 4
DEG = "\N{DEGREE SIGN}"
class Status:
def __init__(self):
self.extruder_temp = 0
self.extruder_temp_target = 0
self.bed_temp = 0
self.bed_temp_target = 0
self.print_job = None
self.print_job_progress = 1.0
def update_tempreading(self, tempstr):
temps = parse_temperature_report(tempstr)
if "T0" in temps and temps["T0"][0]: hotend_temp = float(temps["T0"][0])
elif "T" in temps and temps["T"][0]: hotend_temp = float(temps["T"][0])
else: hotend_temp = None
if "T0" in temps and temps["T0"][1]: hotend_setpoint = float(temps["T0"][1])
elif "T" in temps and temps["T"][1]: hotend_setpoint = float(temps["T"][1])
else: hotend_setpoint = None
if hotend_temp is not None:
self.extruder_temp = hotend_temp
if hotend_setpoint is not None:
self.extruder_temp_target = hotend_setpoint
bed_temp = float(temps["B"][0]) if "B" in temps and temps["B"][0] else None
if bed_temp is not None:
self.bed_temp = bed_temp
setpoint = temps["B"][1]
if setpoint:
self.bed_temp_target = float(setpoint)
@property
def bed_enabled(self):
return self.bed_temp != 0
@property
def extruder_enabled(self):
return self.extruder_temp != 0
class RGSGCoder():
"""Bare alternative to gcoder.LightGCode which does not preload all lines in memory,
but still allows run_gcode_script (hence the RGS) to be processed by do_print (checksum,threading,ok waiting)"""
def __init__(self, line):
self.lines = True
self.filament_length = 0.
self.filament_length_multi = [0]
self.proc = run_command(line, {"$s": 'str(self.filename)'}, stdout = subprocess.PIPE, universal_newlines = True)
lr = gcoder.Layer([])
lr.duration = 0.
self.all_layers = [lr]
self.read() #empty layer causes division by zero during progress calculation
def read(self):
ln = self.proc.stdout.readline()
if not ln:
self.proc.stdout.close()
return None
ln = ln.strip()
if not ln:
return None
pyLn = gcoder.PyLightLine(ln)
self.all_layers[0].append(pyLn)
return pyLn
def has_index(self, i):
while i >= len(self.all_layers[0]) and not self.proc.stdout.closed:
self.read()
return i < len(self.all_layers[0])
def __len__(self):
return len(self.all_layers[0])
def idxs(self, i):
return 0, i #layer, line
class pronsole(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
if not READLINE:
self.completekey = None
self.status = Status()
self.dynamic_temp = False
self.compute_eta = None
self.statuscheck = False
self.status_thread = None
self.monitor_interval = 3
self.p = printcore.printcore()
self.p.recvcb = self.recvcb
self.p.startcb = self.startcb
self.p.endcb = self.endcb
self.p.layerchangecb = self.layer_change_cb
self.p.process_host_command = self.process_host_command
self.recvlisteners = []
self.in_macro = False
self.p.onlinecb = self.online
self.p.errorcb = self.logError
self.fgcode = None
self.filename = None
self.rpc_server = None
self.curlayer = 0
self.sdlisting = 0
self.sdlisting_echo = 0
self.sdfiles = []
self.paused = False
self.sdprinting = 0
self.uploading = 0 # Unused, just for pronterface generalization
self.temps = {"PLA": "185", "ABS": "230", "Off": "0"}
self.bedtemps = {"PLA": "60", "ABS": "110", "Off": "0"}
self.percentdone = 0
self.posreport = ""
self.tempreadings = ""
self.userm114 = 0
self.userm105 = 0
self.m105_waitcycles = 0
self.macros = {}
self.rc_loaded = False
self.processing_rc = False
self.processing_args = False
self.settings = Settings(self)
self.settings._add(BuildDimensionsSetting("build_dimensions", "200x200x100+0+0+0+0+0+0", _("Build Dimensions:"), _("Dimensions of Build Platform\n & optional offset of origin\n & optional switch position\n\nExamples:\n XXXxYYY\n XXX,YYY,ZZZ\n XXXxYYYxZZZ+OffX+OffY+OffZ\nXXXxYYYxZZZ+OffX+OffY+OffZ+HomeX+HomeY+HomeZ"), "Printer"), self.update_build_dimensions)
self.settings._port_list = self.scanserial
self.update_build_dimensions(None, self.settings.build_dimensions)
self.update_tcp_streaming_mode(None, self.settings.tcp_streaming_mode)
self.monitoring = 0
self.starttime = 0
self.extra_print_time = 0
self.silent = False
self.commandprefixes = 'MGTD$'
self.promptstrs = {"offline": "%(bold)soffline>%(normal)s ",
"fallback": "%(bold)s%(red)s%(port)s%(white)s PC>%(normal)s ",
"macro": "%(bold)s..>%(normal)s ",
"online": "%(bold)s%(green)s%(port)s%(white)s %(extruder_temp_fancy)s%(progress_fancy)s>%(normal)s "}
self.spool_manager = spoolmanager.SpoolManager(self)
self.current_tool = 0 # Keep track of the extruder being used
self.cache_dir = os.path.join(user_cache_dir("Printrun"))
self.history_file = os.path.join(self.cache_dir,"history")
self.config_dir = os.path.join(user_config_dir("Printrun"))
self.data_dir = os.path.join(user_data_dir("Printrun"))
self.lineignorepattern=re.compile("ok ?\d*$|.*busy: ?processing|.*busy: ?heating|.*Active Extruder: ?\d*$")
# --------------------------------------------------------------
# General console handling
# --------------------------------------------------------------
def postloop(self):
self.p.disconnect()
cmd.Cmd.postloop(self)
def preloop(self):
self.log(_("Welcome to the printer console! Type \"help\" for a list of available commands."))
self.prompt = self.promptf()
cmd.Cmd.preloop(self)
# We replace this function, defined in cmd.py .
# It's default behavior with regards to Ctr-C
# and Ctr-D doesn't make much sense...
def cmdloop(self, intro=None):
"""Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
"""
self.preloop()
if self.use_rawinput and self.completekey:
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey + ": complete")
history = (self.history_file)
if not os.path.exists(history):
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
history = os.path.join(self.cache_dir, "history")
if os.path.exists(history):
readline.read_history_file(history)
try:
if intro is not None:
self.intro = intro
if self.intro:
self.stdout.write(str(self.intro) + "\n")
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
if self.use_rawinput:
try:
line = input(self.prompt)
except EOFError:
self.log("")
self.do_exit("")
except KeyboardInterrupt:
self.log("")
line = ""
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = ""
else:
line = line.rstrip('\r\n')
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
finally:
if self.use_rawinput and self.completekey:
readline.set_completer(self.old_completer)
readline.write_history_file(self.history_file)
def confirm(self):
y_or_n = input("y/n: ")
if y_or_n == "y":
return True
elif y_or_n != "n":
return self.confirm()
return False
def log(self, *msg):
msg = "".join(str(i) for i in msg)
logging.info(msg)
def logError(self, *msg):
msg = "".join(str(i) for i in msg)
logging.error(msg)
if not self.settings.error_command:
return
output = get_command_output(self.settings.error_command, {"$m": msg})
if output:
self.log(_("Error command output:"))
self.log(output.rstrip())
def promptf(self):
"""A function to generate prompts so that we can do dynamic prompts. """
if self.in_macro:
promptstr = self.promptstrs["macro"]
elif not self.p.online:
promptstr = self.promptstrs["offline"]
elif self.status.extruder_enabled:
promptstr = self.promptstrs["online"]
else:
promptstr = self.promptstrs["fallback"]
if "%" not in promptstr:
return promptstr
else:
specials = {}
specials["extruder_temp"] = str(int(self.status.extruder_temp))
specials["extruder_temp_target"] = str(int(self.status.extruder_temp_target))
# port: /dev/tty* | netaddress:port
specials["port"] = self.settings.port.replace('/dev/', '')
if self.status.extruder_temp_target == 0:
specials["extruder_temp_fancy"] = str(int(self.status.extruder_temp)) + DEG
else:
specials["extruder_temp_fancy"] = "%s%s/%s%s" % (str(int(self.status.extruder_temp)), DEG, str(int(self.status.extruder_temp_target)), DEG)
if self.p.printing:
progress = int(1000 * float(self.p.queueindex) / len(self.p.mainqueue)) / 10
elif self.sdprinting:
progress = self.percentdone
else:
progress = 0.0
specials["progress"] = str(progress)
if self.p.printing or self.sdprinting:
specials["progress_fancy"] = " " + str(round(progress, 2)) + "%"
else:
specials["progress_fancy"] = ""
specials["red"] = "\033[31m"
specials["green"] = "\033[32m"
specials["white"] = "\033[37m"
specials["bold"] = "\033[01m"
specials["normal"] = "\033[00m"
return promptstr % specials
def postcmd(self, stop, line):
""" A hook we override to generate prompts after
each command is executed, for the next prompt.
We also use it to send M105 commands so that
temp info gets updated for the prompt."""
if self.p.online and self.dynamic_temp:
self.p.send_now("M105")
self.prompt = self.promptf()
return stop
def kill(self):
self.statuscheck = False
if self.status_thread:
self.status_thread.join()
self.status_thread = None
if self.rpc_server is not None:
self.rpc_server.shutdown()
def write_prompt(self):
sys.stdout.write(self.promptf())
sys.stdout.flush()
def help_help(self, l = ""):
self.do_help("")
def do_gcodes(self, l = ""):
self.help_gcodes()
def help_gcodes(self):
self.log(_("Gcodes are passed through to the printer as they are"))
def precmd(self, line):
if line.upper().startswith("M114"):
self.userm114 += 1
elif line.upper().startswith("M105"):
self.userm105 += 1
return line
def help_shell(self):
self.log(_("Executes a python command. Example:"))
self.log("! os.listdir('.')")
def do_shell(self, l):
exec(l)
def emptyline(self):
"""Called when an empty line is entered - do not remove"""
pass
def default(self, l):
if l[0].upper() in self.commandprefixes.upper():
if self.p and self.p.online:
if not self.p.loud:
self.log(_("SENDING:") + l.upper())
self.p.send_now(l.upper())
else:
self.logError(_("Printer is not online."))
return
elif l[0] == "@":
if self.p and self.p.online:
if not self.p.loud:
self.log(_("SENDING:") + l[1:])
self.p.send_now(l[1:])
else:
self.logError(_("Printer is not online."))
return
else:
cmd.Cmd.default(self, l)
def do_exit(self, l):
if self.p.printing and l != "force":
self.log(_("Are you sure you want to exit while printing?\n\
Disables all heaters upon exit."))
if not self.confirm():
return
if self.status.extruder_temp_target != 0:
self.log(_("Setting extruder temp to 0"))
self.p.send_now("M104 S0.0")
if self.status.bed_enabled:
if self.status.bed_temp_target != 0:
self.log(_("Setting bed temp to 0"))
self.p.send_now("M140 S0.0")
self.log(_("Disconnecting from printer..."))
self.log(_("Exiting program. Goodbye!"))
self.p.disconnect()
self.kill()
sys.exit()
def help_exit(self):
self.log(_("Disconnects from the printer and exits the program."))
# --------------------------------------------------------------
# Macro handling
# --------------------------------------------------------------
def complete_macro(self, text, line, begidx, endidx):
if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1] == " "):
return [i for i in self.macros.keys() if i.startswith(text)]
elif len(line.split()) == 3 or (len(line.split()) == 2 and line[-1] == " "):
return [i for i in ["/D", "/S"] + self.completenames(text) if i.startswith(text)]
else:
return []
def hook_macro(self, l):
l = l.rstrip()
ls = l.lstrip()
ws = l[:len(l) - len(ls)] # just leading whitespace
if len(ws) == 0:
self.end_macro()
# pass the unprocessed line to regular command processor to not require empty line in .pronsolerc
return self.onecmd(l)
self.cur_macro_def += l + "\n"
def end_macro(self):
if "onecmd" in self.__dict__: del self.onecmd # remove override
self.in_macro = False
self.prompt = self.promptf()
if self.cur_macro_def != "":
self.macros[self.cur_macro_name] = self.cur_macro_def
macro = self.compile_macro(self.cur_macro_name, self.cur_macro_def)
setattr(self.__class__, "do_" + self.cur_macro_name, lambda self, largs, macro = macro: macro(self, *largs.split()))
setattr(self.__class__, "help_" + self.cur_macro_name, lambda self, macro_name = self.cur_macro_name: self.subhelp_macro(macro_name))
if not self.processing_rc:
self.log(_("Macro '") + self.cur_macro_name + _("' defined"))
# save it
if not self.processing_args:
macro_key = "macro " + self.cur_macro_name
macro_def = macro_key
if "\n" in self.cur_macro_def:
macro_def += "\n"
else:
macro_def += " "
macro_def += self.cur_macro_def
self.save_in_rc(macro_key, macro_def)
else:
self.logError(_("Empty macro - cancelled"))
del self.cur_macro_name, self.cur_macro_def
def compile_macro_line(self, line):
line = line.rstrip()
ls = line.lstrip()
ws = line[:len(line) - len(ls)] # just leading whitespace
if ls == "" or ls.startswith('#'): return "" # no code
if ls.startswith('!'):
return ws + ls[1:] + "\n" # python mode
else:
ls = ls.replace('"', '\\"') # need to escape double quotes
ret = ws + 'self.precmd("' + ls + '".format(*arg))\n' # parametric command mode
return ret + ws + 'self.onecmd("' + ls + '".format(*arg))\n'
def compile_macro(self, macro_name, macro_def):
if macro_def.strip() == "":
self.logError(_("Empty macro - cancelled"))
return
macro = None
namespace={}
pycode = "def macro(self,*arg):\n"
if "\n" not in macro_def.strip():
pycode += self.compile_macro_line(" " + macro_def.strip())
else:
lines = macro_def.split("\n")
for l in lines:
pycode += self.compile_macro_line(l)
exec(pycode,namespace)
try:
macro=namespace['macro']
except:
pass
return macro
def start_macro(self, macro_name, prev_definition = "", suppress_instructions = False):
if not self.processing_rc and not suppress_instructions:
self.logError(_("Enter macro using indented lines, end with empty line"))
self.cur_macro_name = macro_name
self.cur_macro_def = ""
self.onecmd = self.hook_macro # override onecmd temporarily
self.in_macro = False
self.prompt = self.promptf()
def delete_macro(self, macro_name):
if macro_name in self.macros.keys():
delattr(self.__class__, "do_" + macro_name)
del self.macros[macro_name]
self.log(_("Macro '") + macro_name + _("' removed"))
if not self.processing_rc and not self.processing_args:
self.save_in_rc("macro " + macro_name, "")
else:
self.logError(_("Macro '") + macro_name + _("' is not defined"))
def do_macro(self, args):
if args.strip() == "":
self.print_topics("User-defined macros", [str(k) for k in self.macros.keys()], 15, 80)
return
arglist = args.split(None, 1)
macro_name = arglist[0]
if macro_name not in self.macros and hasattr(self.__class__, "do_" + macro_name):
self.logError(_("Name '") + macro_name + _("' is being used by built-in command"))
return
if len(arglist) == 2:
macro_def = arglist[1]
if macro_def.lower() == "/d":
self.delete_macro(macro_name)
return
if macro_def.lower() == "/s":
self.subhelp_macro(macro_name)
return
self.cur_macro_def = macro_def
self.cur_macro_name = macro_name
self.end_macro()
return
if macro_name in self.macros:
self.start_macro(macro_name, self.macros[macro_name])
else:
self.start_macro(macro_name)
def help_macro(self):
self.log(_("Define single-line macro: macro <name> <definition>"))
self.log(_("Define multi-line macro: macro <name>"))
self.log(_("Enter macro definition in indented lines. Use {0} .. {N} to substitute macro arguments"))
self.log(_("Enter python code, prefixed with ! Use arg[0] .. arg[N] to substitute macro arguments"))
self.log(_("Delete macro: macro <name> /d"))
self.log(_("Show macro definition: macro <name> /s"))
self.log(_("'macro' without arguments displays list of defined macros"))
def subhelp_macro(self, macro_name):
if macro_name in self.macros.keys():
macro_def = self.macros[macro_name]
if "\n" in macro_def:
self.log(_("Macro '") + macro_name + _("' defined as:"))
self.log(self.macros[macro_name] + "----------------")
else:
self.log(_("Macro '") + macro_name + _("' defined as: '") + macro_def + "'")
else:
self.logError(_("Macro '") + macro_name + _("' is not defined"))
# --------------------------------------------------------------
# Configuration handling
# --------------------------------------------------------------
def set(self, var, str):
try:
t = type(getattr(self.settings, var))
value = self.settings._set(var, str)
if not self.processing_rc and not self.processing_args:
self.save_in_rc("set " + var, "set %s %s" % (var, value))
except AttributeError:
logging.debug(_("Unknown variable '%s'") % var)
except ValueError as ve:
if hasattr(ve, "from_validator"):
self.logError(_("Bad value %s for variable '%s': %s") % (str, var, ve.args[0]))
else:
self.logError(_("Bad value for variable '%s', expecting %s (%s)") % (var, repr(t)[1:-1], ve.args[0]))
def do_set(self, argl):
args = argl.split(None, 1)
if len(args) < 1:
for k in [kk for kk in dir(self.settings) if not kk.startswith("_")]:
self.log("%s = %s" % (k, str(getattr(self.settings, k))))
return
if len(args) < 2:
# Try getting the default value of the setting to check whether it
# actually exists
try:
getattr(self.settings, args[0])
except AttributeError:
logging.warning(_("Unknown variable '%s'") % args[0])
return
self.set(args[0], args[1])
def help_set(self):
self.log(_("Set variable: set <variable> <value>"))
self.log(_("Show variable: set <variable>"))
self.log(_("'set' without arguments displays all variables"))
def complete_set(self, text, line, begidx, endidx):
if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1] == " "):
return [i for i in dir(self.settings) if not i.startswith("_") and i.startswith(text)]
elif len(line.split()) == 3 or (len(line.split()) == 2 and line[-1] == " "):
return [i for i in self.settings._tabcomplete(line.split()[1]) if i.startswith(text)]
else:
return []
def load_rc(self, rc_filename):
self.processing_rc = True
try:
rc = codecs.open(rc_filename, "r", "utf-8")
self.rc_filename = os.path.abspath(rc_filename)
for rc_cmd in rc:
if not rc_cmd.lstrip().startswith("#"):
logging.debug(rc_cmd.rstrip())
self.onecmd(rc_cmd)
rc.close()
if hasattr(self, "cur_macro_def"):
self.end_macro()
self.rc_loaded = True
finally:
self.processing_rc = False
def load_default_rc(self):
# Check if a configuration file exists in an "old" location,
# if not, use the "new" location provided by appdirs
for f in '~/.pronsolerc', '~/printrunconf.ini':
expanded = os.path.expanduser(f)
if os.path.exists(expanded):
config = expanded
break
else:
if not os.path.exists(self.config_dir):
os.makedirs(self.config_dir)
config_name = ('printrunconf.ini'
if platform.system() == 'Windows'
else 'pronsolerc')
config = os.path.join(self.config_dir, config_name)
logging.info('Loading config file ' + config)
# Load the default configuration file
try:
self.load_rc(config)
except FileNotFoundError:
# Make sure the filename is initialized,
# and create the file if it doesn't exist
self.rc_filename = config
open(self.rc_filename, 'a').close()
def save_in_rc(self, key, definition):
"""
Saves or updates macro or other definitions in .pronsolerc
key is prefix that determines what is being defined/updated (e.g. 'macro foo')
definition is the full definition (that is written to file). (e.g. 'macro foo move x 10')
Set key as empty string to just add (and not overwrite)
Set definition as empty string to remove it from .pronsolerc
To delete line from .pronsolerc, set key as the line contents, and definition as empty string
Only first definition with given key is overwritten.
Updates are made in the same file position.
Additions are made to the end of the file.
"""
rci, rco = None, None
if definition != "" and not definition.endswith("\n"):
definition += "\n"
try:
written = False
if os.path.exists(self.rc_filename):
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
configcache = os.path.join(self.cache_dir, os.path.basename(self.rc_filename))
configcachebak = configcache + "~bak"
configcachenew = configcache + "~new"
shutil.copy(self.rc_filename, configcachebak)
rci = codecs.open(configcachebak, "r", "utf-8")
rco = codecs.open(configcachenew, "w", "utf-8")
if rci is not None:
overwriting = False
for rc_cmd in rci:
l = rc_cmd.rstrip()
ls = l.lstrip()
ws = l[:len(l) - len(ls)] # just leading whitespace
if overwriting and len(ws) == 0:
overwriting = False
if not written and key != "" and rc_cmd.startswith(key) and (rc_cmd + "\n")[len(key)].isspace():
overwriting = True
written = True
rco.write(definition)
if not overwriting:
rco.write(rc_cmd)
if not rc_cmd.endswith("\n"): rco.write("\n")
if not written:
rco.write(definition)
if rci is not None:
rci.close()
rco.close()
shutil.move(configcachenew, self.rc_filename)
# if definition != "":
# self.log("Saved '"+key+"' to '"+self.rc_filename+"'")
# else:
# self.log("Removed '"+key+"' from '"+self.rc_filename+"'")
except Exception as e:
self.logError(_("Saving failed for "), key + ":", str(e))
finally:
del rci, rco
# --------------------------------------------------------------
# Configuration update callbacks
# --------------------------------------------------------------
def update_build_dimensions(self, param, value):
self.build_dimensions_list = parse_build_dimensions(value)
self.p.analyzer.home_pos = get_home_pos(self.build_dimensions_list)
def update_tcp_streaming_mode(self, param, value):
self.p.tcp_streaming_mode = self.settings.tcp_streaming_mode
def update_rpc_server(self, param, value):
if value:
if self.rpc_server is None:
self.rpc_server = ProntRPC(self)
else:
if self.rpc_server is not None:
self.rpc_server.shutdown()
self.rpc_server = None
# --------------------------------------------------------------
# Command line options handling
# --------------------------------------------------------------
def add_cmdline_arguments(self, parser):
parser.add_argument('-v', '--verbose', help = _("increase verbosity"), action = "store_true")
parser.add_argument('-c', '--conf', '--config', help = _("load this file on startup instead of .pronsolerc ; you may chain config files, if so settings auto-save will use the last specified file"), action = "append", default = [])
parser.add_argument('-e', '--execute', help = _("executes command after configuration/.pronsolerc is loaded ; macros/settings from these commands are not autosaved"), action = "append", default = [])
parser.add_argument('filename', nargs='?', help = _("file to load"))
def process_cmdline_arguments(self, args):
if args.verbose:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
for config in args.conf:
try:
self.load_rc(config)
except EnvironmentError as err:
print((_("ERROR: Unable to load configuration file: %s") %
str(err)[10:]))
sys.exit(1)
if not self.rc_loaded:
self.load_default_rc()
self.processing_args = True
for command in args.execute:
self.onecmd(command)
self.processing_args = False
self.update_rpc_server(None, self.settings.rpc_server)
if args.filename:
self.cmdline_filename_callback(args.filename)
def cmdline_filename_callback(self, filename):
self.do_load(filename)
def parse_cmdline(self, args):
parser = argparse.ArgumentParser(description = 'Printrun 3D printer interface')
self.add_cmdline_arguments(parser)
args = [arg for arg in args if not arg.startswith("-psn")]
args = parser.parse_args(args = args)
self.process_cmdline_arguments(args)
setup_logging(sys.stdout, self.settings.log_path, True)
# --------------------------------------------------------------
# Printer connection handling
# --------------------------------------------------------------
def connect_to_printer(self, port, baud, dtr):
try:
self.p.connect(port, baud, dtr)
except SerialException as e:
# Currently, there is no errno, but it should be there in the future
if e.errno == 2:
self.logError(_("Error: You are trying to connect to a non-existing port."))
elif e.errno == 8:
self.logError(_("Error: You don't have permission to open %s.") % port)
self.logError(_("You might need to add yourself to the dialout group."))
else:
self.logError(traceback.format_exc())
# Kill the scope anyway
return False
except OSError as e:
if e.errno == 2:
self.logError(_("Error: You are trying to connect to a non-existing port."))
else:
self.logError(traceback.format_exc())
return False
self.statuscheck = True
self.status_thread = threading.Thread(target = self.statuschecker,
name = 'status thread')
self.status_thread.start()
return True
def do_connect(self, l):
a = l.split()
p = self.scanserial()
port = self.settings.port
if (port == "" or port not in p) and len(p) > 0:
port = p[0]
baud = self.settings.baudrate or 115200
if len(a) > 0:
port = a[0]
if len(a) > 1:
try:
baud = int(a[1])
except:
self.log(_("Bad baud value '") + a[1] + _("' ignored"))
if len(p) == 0 and not port:
self.log(_("No serial ports detected - please specify a port"))
return
if len(a) == 0:
self.log(_("No port specified - connecting to %s at %dbps") % (port, baud))
if port != self.settings.port:
self.settings.port = port
self.save_in_rc("set port", "set port %s" % port)
if baud != self.settings.baudrate:
self.settings.baudrate = baud
self.save_in_rc("set baudrate", "set baudrate %d" % baud)
self.connect_to_printer(port, baud, self.settings.dtr)
def help_connect(self):
self.log(_("Connect to printer"))
self.log(_("connect <port> <baudrate>"))
self.log(_("If port and baudrate are not specified, connects to first detected port at 115200bps"))
ports = self.scanserial()
if ports:
self.log(_("Available ports: "), " ".join(ports))
else:
self.log(_("No serial ports were automatically found."))
def complete_connect(self, text, line, begidx, endidx):
if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1] == " "):
return [i for i in self.scanserial() if i.startswith(text)]
elif len(line.split()) == 3 or (len(line.split()) == 2 and line[-1] == " "):
return [i for i in ["2400", "9600", "19200", "38400", "57600", "115200", "250000"] if i.startswith(text)]
else:
return []
def scanserial(self):
"""scan for available ports. return a list of device names."""
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
for g in ['/dev/ttyUSB*', '/dev/ttyACM*', "/dev/tty.*", "/dev/cu.*", "/dev/rfcomm*"]:
baselist += glob.glob(g)
if(sys.platform!="win32" and self.settings.devicepath):
baselist += glob.glob(self.settings.devicepath)
return [p for p in baselist if self._bluetoothSerialFilter(p)]
def _bluetoothSerialFilter(self, serial):
return not ("Bluetooth" in serial or "FireFly" in serial)
def online(self):
self.log("\r" + _("Printer is now online"))
self.write_prompt()
def do_disconnect(self, l):
self.p.disconnect()
def help_disconnect(self):
self.log(_("Disconnects from the printer"))
def do_block_until_online(self, l):
while not self.p.online:
time.sleep(0.1)
def help_block_until_online(self, l):
self.log(_("Blocks until printer is online"))
self.log(_("Warning: if something goes wrong, this can block pronsole forever"))
# --------------------------------------------------------------
# Printer status monitoring
# --------------------------------------------------------------
def statuschecker_inner(self, do_monitoring = True):
if self.p.online:
if self.p.writefailures >= 4:
self.logError(_("Disconnecting after 4 failed writes."))
self.status_thread = None
self.p.disconnect()
return
if do_monitoring:
if self.sdprinting and not self.paused:
self.p.send_now("M27")
if self.m105_waitcycles % 10 == 0:
self.p.send_now("M105")
self.m105_waitcycles += 1
cur_time = time.time()
wait_time = 0
while time.time() < cur_time + self.monitor_interval - 0.25:
if not self.statuscheck:
break
time.sleep(0.25)
# Safeguard: if system time changes and goes back in the past,
# we could get stuck almost forever
wait_time += 0.25
if wait_time > self.monitor_interval - 0.25:
break
# Always sleep at least a bit, if something goes wrong with the
# system time we'll avoid freezing the whole app this way
time.sleep(0.25)
def statuschecker(self):
while self.statuscheck:
self.statuschecker_inner()
# --------------------------------------------------------------
# File loading handling
# --------------------------------------------------------------
def do_load(self, filename):
self._do_load(filename)
def _do_load(self, filename):
if not filename:
self.logError(_("No file name given."))
return
self.log(_("Loading file: %s") % filename)
if not os.path.exists(filename):
self.logError(_("File not found!"))
return
self.load_gcode(filename)
self.log(_("Loaded %s, %d lines.") % (filename, len(self.fgcode)))
self.log(_("Estimated duration: %d layers, %s") % self.fgcode.estimate_duration())
def load_gcode(self, filename, layer_callback = None, gcode = None):
if gcode is None:
self.fgcode = gcoder.LightGCode(deferred = True)
else:
self.fgcode = gcode
self.fgcode.prepare(open(filename, "r", encoding="utf-8"),
get_home_pos(self.build_dimensions_list),
layer_callback = layer_callback)
self.fgcode.estimate_duration()
self.filename = filename
def complete_load(self, text, line, begidx, endidx):
s = line.split()
if len(s) > 2:
return []
if (len(s) == 1 and line[-1] == " ") or (len(s) == 2 and line[-1] != " "):
if len(s) > 1:
return [i[len(s[1]) - len(text):] for i in glob.glob(s[1] + "*/") + glob.glob(s[1] + "*.g*")]
else:
return glob.glob("*/") + glob.glob("*.g*")
def help_load(self):
self.log(_("Loads a gcode file (with tab-completion)"))
def do_slice(self, l):
l = l.split()
if len(l) == 0:
self.logError(_("No file name given."))
return
settings = 0
if l[0] == "set":
settings = 1
else:
self.log(_("Slicing file: %s") % l[0])
if not(os.path.exists(l[0])):
self.logError(_("File not found!"))
return
try:
if settings:
command = self.settings.slicecommandpath+self.settings.sliceoptscommand
self.log(_("Entering slicer settings: %s") % command)
run_command(command, blocking = True)
else:
command = self.settings.slicecommandpath+self.settings.slicecommand
stl_name = l[0]
gcode_name = stl_name.replace(".stl", "_export.gcode").replace(".STL", "_export.gcode")
run_command(command,
{"$s": stl_name,
"$o": gcode_name},
blocking = True)