-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.py
1941 lines (1617 loc) · 68.7 KB
/
main.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
import kivy
from kivy.config import Config
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.widget import Widget
from kivy.uix.behaviors import ButtonBehavior, ToggleButtonBehavior, FocusBehavior
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.actionbar import ActionButton
from kivy.properties import NumericProperty, StringProperty, ObjectProperty, ListProperty, BooleanProperty
from kivy.vector import Vector
from kivy.clock import Clock, mainthread
from kivy.factory import Factory
from kivy.logger import Logger
from kivy.core.window import Window
from kivy.config import ConfigParser
from kivy.metrics import dp, Metrics
# needed to fix sys.excepthook errors, fixed in 2.x.x
from kivy.uix.recycleview.views import RecycleDataViewBehavior, _cached_views, _view_base_cache
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.core.clipboard import Clipboard
from native_file_chooser import NativeFileChooser
from mpg_knob import Knob
from libs.hat import Hat
from comms import Comms
from message_box import MessageBox
from input_box import InputBox
from selection_box import SelectionBox
from file_dialog import FileDialog
from viewer import GcodeViewerScreen
from web_server import ProgressServer
from camera_screen import CameraScreen
from spindle_camera import SpindleCamera
from config_editor import ConfigEditor
from configv2_editor import ConfigV2Editor
from gcode_help import GcodeHelp
from text_editor import TextEditor
from tool_scripts import ToolScripts
from notify import Notify
from calc_widget import CalcScreen
from uart_logger import UartLogger
from tmc_configurator import TMCConfigurator
from spindle_handler import SpindleHandler
import subprocess
import threading
import traceback
import queue
import math
import os
import sys
import datetime
import configparser
from functools import partial
import collections
import importlib
import signal
# we must have Python version between 3.7.3 and 3.11.x
assert (3, 11, 99) >= sys.version_info >= (3, 7, 3), f"Python version needs to be >= 3.7.3 and <= 3.11.x, you have {sys.version}"
kivy.require('2.1.0')
# Window.softinput_mode = 'below_target'
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''
touch_deselect_last = BooleanProperty(True)
is_focusable = BooleanProperty(False)
class LogLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(LogLabel, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(LogLabel, self).on_touch_down(touch):
return True
if touch.is_double_tap and self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
if is_selected:
App.get_running_app().last_command = rv.data[index]['text']
# also stick in clipboard if we are running X
Clipboard.copy(rv.data[index]['text'])
class NumericInput(TextInput):
"""Text input that shows a numeric keypad"""
def __init__(self, **kwargs):
super(NumericInput, self).__init__(**kwargs)
def on_focus(self, i, v):
if v:
self._last = self.text
self.text = ""
if App.get_running_app().is_touch:
self.show_keyboard()
if self.keyboard and self.keyboard.widget:
self.keyboard.widget.layout = "numeric.json"
self.m_keyboard = self.keyboard.widget
else:
if self.text == "":
self.text = self._last
if App.get_running_app().is_touch:
if self.keyboard and self.keyboard.widget:
self.m_keyboard.layout = "qwerty"
self.hide_keyboard()
def on_parent(self, widget, parent):
if App.get_running_app().is_touch:
self.keyboard_mode = 'managed'
class DROWidget(RelativeLayout):
"""DROWidget Shows realtime information in a DRO style"""
curwcs = StringProperty('')
def __init__(self, **kwargs):
super(DROWidget, self).__init__(**kwargs)
self.app = App.get_running_app()
def enter_wpos(self, axis, v):
i = ord(axis) - ord('x')
v = v.strip()
if v.startswith('/'):
# we divide current value by this
try:
d = float(v[1:])
v = str(self.app.wpos[i] / d)
except Exception:
Logger.warning(f"DROWidget: cannot divide by: {v}")
self.app.wpos[i] = self.app.wpos[i]
return
try:
# needed because the filter does not allow -ive numbers WTF!!!
f = float(v.strip())
except Exception:
Logger.warning(f"DROWidget: invalid float input: {v}")
# set the display back to what it was, this looks odd but it forces the display to update
self.app.wpos[i] = self.app.wpos[i]
return
Logger.debug(f"DROWidget: Set axis {axis} wpos to {f}")
self.app.comms.write(f'G10 L20 P0 {axis.upper()}{f}\n')
self.app.wpos[i] = f
def select_wcs(self, v):
self.app.comms.write(f'{v}\n')
def reset_axis(self, a):
# only used for ABC axis
self.app.comms.write(f'G92 {a}0\n')
def update_buttons(self):
return "$I\n"
def _on_curwcs(self):
# foreach WCS button see if it is active or not
for i in self.ids.wcs_buts.children:
if i.text == self.curwcs:
i.state = 'down'
else:
i.state = 'normal'
class MPGWidget(RelativeLayout):
last_pos = NumericProperty(0)
selected_axis = StringProperty('X')
selected_index = NumericProperty(0)
def __init__(self, **kwargs):
super(MPGWidget, self).__init__(**kwargs)
self.app = App.get_running_app()
def handle_action(self):
# Run button pressed
if self.selected_index == -1:
# change feed override
self.app.comms.write(f'M220 S{round(self.last_pos, 1)}\n')
return
if self.app.main_window.is_printing and not self.app.main_window.is_suspended:
return
# if in non MPG mode then issue G0 in abs or rel depending on settings
# if in MPG mode then issue $J commands when they occur
if not self.ids.mpg_mode_tb.state == 'down':
# normal mode
cmd = 'G90' if self.ids.abs_mode_tb.state == 'down' else 'G91'
# print('{} {}{} {}'.format(cmd1, self.selected_axis, round(self.last_pos, 3), cmd2))
self.app.comms.write(f'M120 {cmd} G0 {self.selected_axis}{round(self.last_pos, 3)} M121\n')
def handle_change(self, ticks):
if self.selected_index == -1:
# change feed override
self.last_pos += ticks
if self.last_pos < 1:
self.last_pos = 1
return
if self.app.main_window.is_printing and not self.app.main_window.is_suspended:
return
# change an axis
if self.ids.x01.active:
d = 0.01 * ticks
elif self.ids.x001.active:
d = 0.001 * ticks
else:
d = 0.1 * ticks
self.last_pos = self.last_pos + d
axis = self.selected_axis
# MPG mode
if self.ids.mpg_mode_tb.state == 'down':
self.app.comms.write(f'$J {self.selected_axis.upper()}{d}\n')
def index_changed(self, i):
if i == -1:
# Feedrate overide
self.last_pos = self.app.fro
elif self.ids.abs_mode_tb.state == 'down':
# show current axis position
self.last_pos = self.app.wpos[i]
else:
# relative mode zero it
self.last_pos = 0
def abs_mode_changed(self):
self.index_changed(self.selected_index)
class CircularButton(ButtonBehavior, Widget):
text = StringProperty()
font_size = NumericProperty('15sp')
def collide_point(self, x, y):
return Vector(x, y).distance(self.center) <= self.width / 2
class CircularToggleButton(ToggleButtonBehavior, Widget):
text = StringProperty()
def collide_point(self, x, y):
return Vector(x, y).distance(self.center) <= self.width / 2
class ArrowButton(ButtonBehavior, Widget):
text = StringProperty()
angle = NumericProperty()
# def collide_point(self, x, y):
# bmin = Vector(self.center) - Vector(25, 25)
# bmax = Vector(self.center) + Vector(25, 25)
# return Vector.in_bbox((x, y), bmin, bmax)
class LPArrowButton(ArrowButton):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.schedule = None
self.register_event_type('on_long_press')
self.register_event_type('on_long_release')
self.long_press = False
def on_long_press(self):
self.long_press = True
def on_long_release(self):
pass
def on_press(self):
self.schedule = Clock.schedule_once(self._long_press, 2)
def _long_press(self, _):
self.dispatch('on_long_press')
def on_release(self):
self.schedule.cancel()
if self.long_press:
self.dispatch('on_long_release')
self.long_press = False
class JogRoseWidget(BoxLayout):
abc_sel = StringProperty('Z')
def __init__(self, **kwargs):
super(JogRoseWidget, self).__init__(**kwargs)
self.app = App.get_running_app()
self.cont_moving = False
def on_kv_post(self, args):
self.hat.bind(pad=self.on_hat)
def _get_speed(self):
if self.ids.js100.state == 'down':
return 1.0
elif self.ids.js50.state == 'down':
return 0.5
elif self.ids.js25.state == 'down':
return 0.25
elif self.ids.js10.state == 'down':
return 0.1
else:
return 0.5
def on_hat(self, w, value):
x, y = value
axis = None
if x != 0:
axis = 'X'
v = x
elif y != 0:
axis = 'Y'
v = y
if axis is not None:
s = self._get_speed()
# starts continuous jog
# must not send another $J -c until ok is recieved from previous one
if not self.cont_moving:
self.cont_moving = True
self.app.comms.ok_notify_cb = lambda x: self.got_ok(x)
self.app.comms.write(f'$J -c {axis}{v} S{s}\n')
def got_ok(self, f):
self.cont_moving = False
def hat_released(self):
if self.cont_moving:
self.app.comms.write('\x19')
def handle_action(self, axis, v):
if self.app.main_window.is_printing and not self.app.main_window.is_suspended:
self.app.main_window.display("NOTE: Cannot jog while printing")
return
if axis == 'O':
self.app.comms.write('M120 G21 G90 G0 X0 Y0 M121\n')
elif axis == 'H':
self.app.comms.write('$H\n')
else:
s = self._get_speed()
self.app.comms.write(f'$J {axis}{v} S{s}\n')
def handle_long_press(self, axis, v):
s = self._get_speed()
# starts continuous jog
# must not send another $J -c until ok is recieved from previous one
if not self.cont_moving:
self.cont_moving = True
self.app.comms.ok_notify_cb = lambda x: self.got_ok(x)
self.app.comms.write(f'$J -c {axis}{v} S{s}\n')
def handle_long_release(self):
if self.cont_moving:
self.app.comms.write('\x19')
def motors_off(self):
if self.app.main_window.is_printing:
self.app.main_window.display("NOTE: Cannot turn off motors while printing")
else:
self.app.comms.write('M18\n')
def safe_z(self):
self.app.comms.write(f'$J Z{self.app.safez} S{self._get_speed()}\n')
class KbdWidget(GridLayout):
def __init__(self, **kwargs):
super(KbdWidget, self).__init__(**kwargs)
self.app = App.get_running_app()
def _add_line_to_log(self, s):
self.app.main_window.display(s)
def do_action(self, key):
if key == 'Send':
# Logger.debug(f"KbdWidget: Sending {self.display.text}")
if self.display.text.strip():
self._add_line_to_log(f'<< {self.display.text}')
self.app.comms.write(f'{self.display.text}\n')
self.app.last_command = self.display.text
self.display.text = ''
elif key == 'Repeat':
self.display.text = self.app.last_command
elif key == 'BS':
self.display.text = self.display.text[:-1]
elif key == '?':
self.handle_input('?')
else:
self.display.text += key
def handle_input(self, s):
self.app.command_input(s)
if s != '?':
self.app.last_command = s
self.display.text = ''
class MainWindow(BoxLayout):
status = StringProperty('Idle')
wpos = ListProperty([0, 0, 0])
eta = StringProperty('Not Streaming')
is_printing = BooleanProperty(False)
is_suspended = BooleanProperty(False)
is_uart_log_enabled = BooleanProperty(False)
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
self.app = App.get_running_app()
self._trigger = Clock.create_trigger(self.async_get_display_data)
self._q = queue.Queue()
self.config = self.app.config
self.last_path = self.config.get('General', 'last_gcode_path')
self.paused = False
self.is_sdprint = False
self.save_console_data = None
self.uart_log_data = []
self.is_uart_log_in_view = False
self.uart_log = None
def get_last_line(self):
return self.app.comms.actual_line
def on_touch_down(self, touch):
if self.ids.log_window.collide_point(touch.x, touch.y):
if touch.is_triple_tap:
self.ids.log_window.data = []
return True
return super(MainWindow, self).on_touch_down(touch)
def add_line_to_log(self, s, overwrite=False):
''' Add lines to the log window, which is trimmed to the last 200 lines '''
if self.is_uart_log_in_view:
# not in view at the moment
self.save_console_data.append({'text': s})
return
max_lines = 200 # TODO needs to be configurable
n = len(self.ids.log_window.data)
if overwrite:
self.ids.log_window.data[n - 1] = ({'text': s})
return
self.ids.log_window.data.append({'text': s})
# we use some hysteresis here so we don't truncate every line added over max_lines
n = n - max_lines # how many lines over our max
if n > 10:
# truncate log to last max_lines, we delete the oldest 10 or so lines
del self.ids.log_window.data[0:n]
def connect(self):
if self.app.is_connected:
if self.is_printing:
mb = MessageBox(text='Cannot Disconnect while printing - Abort first, then wait', cancel_text='OK')
mb.open()
else:
self._disconnect()
else:
port = self.config.get('General', 'serial_port')
self.add_line_to_log(f"Connecting to {port}...")
self.app.comms.connect(port)
def _disconnect(self, b=True):
if b:
self.add_line_to_log("Disconnect...")
self.app.comms.disconnect()
def display(self, data):
self.add_line_to_log(data)
# we have to do this as @mainthread was getting stuff out of order
def async_display(self, data):
''' called from external thread to display incoming data '''
# puts the data onto queue and triggers an event to read it in the Kivy thread
self._q.put(data)
self._trigger()
def async_get_display_data(self, *largs):
''' fetches data from the Queue and displays it, triggered by incoming data '''
while not self._q.empty():
# we need this loop until q is empty as trigger only triggers once per frame
data = self._q.get(False)
if data.endswith('\r'):
self.add_line_to_log(data[0:-1], True)
else:
self.add_line_to_log(data)
@mainthread
def connected(self):
Logger.debug("MainWindow: Connected...")
self.add_line_to_log("...Connected")
self.app.is_connected = True
self.ids.connect_button.state = 'down'
self.ids.connect_button.text = "Disconnect"
self.ids.print_but.text = 'Run'
self.paused = False
self.is_printing = False
@mainthread
def disconnected(self):
Logger.debug("MainWindow: Disconnected...")
self.app.is_connected = False
self.is_printing = False
self.ids.connect_button.state = 'normal'
self.ids.connect_button.text = "Connect"
self.add_line_to_log("...Disconnected")
@mainthread
def update_status(self, stat, d):
self.status = stat
self.app.status = stat
if 'WPos' in d:
self.wpos = d['WPos']
self.app.wpos = self.wpos
if 'MPos' in d:
self.app.mpos = d['MPos']
if 'F' in d:
if len(d['F']) == 2:
self.app.fr = d['F'][0]
self.app.frr = d['F'][0]
self.app.fro = d['F'][1]
elif len(d['F']) == 3:
# NOTE fr is current actual feedrate and frr is requested feed rate (from the Fxxx)
self.app.fr = d['F'][0]
self.app.frr = d['F'][1]
self.app.fro = d['F'][2]
if 'S' in d:
self.app.sr = d['S'][0]
if self.app.spindle_handler is not None:
# convert from the PWM to RPM
self.app.rpm = self.app.spindle_handler.reverse_lookup(self.app.sr)
if 'L' in d:
self.app.lp = d['L'][0]
if 'SD' in d:
rt = datetime.timedelta(seconds=int(d['SD'][0]))
self.eta = f"SD: {rt} {d['SD'][1]}%"
if not self.is_sdprint:
self.is_sdprint = True
self.is_printing = True
self.paused = False
self.ids.print_but.text = 'Pause'
else:
if self.is_sdprint:
self.eta = 'Not Streaming'
self.is_sdprint = False
self.is_printing = False
self.ids.print_but.text = 'Run'
if not self.app.is_cnc:
# extract temperature readings and update the extruder property
# We only want to update once per query
t = {}
if 'T' in d:
t['hotend0'] = (d['T'][0], d['T'][1])
if 'T1' in d:
t['hotend1'] = (d['T1'][0], d['T1'][1])
if 'B' in d:
t['bed'] = (d['B'][0], d['B'][1])
if t:
self.ids.extruder.update_temp(t)
@mainthread
def update_state(self, a):
if not self.app.is_cnc:
self.ids.extruder.curtool = int(a[9][1])
self.ids.dro_widget.curwcs = a[1]
self.app.is_inch = a[3] == 'G20'
self.app.is_abs = a[4] == 'G90'
self.app.is_spindle_on = a[7] == 'M3'
def ask_exit(self, restart=False):
# are you sure?
if restart:
mb = MessageBox(text='Restart - Are you Sure?', cb=self._do_restart)
else:
mb = MessageBox(text='Exit - Are you Sure?', cb=self._do_exit)
mb.open()
def _do_exit(self, ok):
if ok:
self.app.stop()
def _do_restart(self, ok):
if ok:
self.app.stop()
os.execl(sys.executable, sys.executable, *sys.argv)
def ask_shutdown(self, *args):
# are you sure?
mb = MessageBox(text='Shutdown - Are you Sure?', cb=self._do_shutdown)
mb.open()
def _do_shutdown(self, ok):
if ok:
os.system('/sbin/shutdown -h now')
self._do_exit(True)
def change_port(self):
ll = self.app.comms.get_ports()
ports = [self.config.get('General', 'serial_port')] # current port is first in list
for p in ll:
ports.append(f'serial://{p.device}')
ports.append('network...')
sb = SelectionBox(title='Select port', text='Select the port to open from drop down', values=ports, cb=self._change_port)
sb.open()
def _change_port(self, s):
if s:
Logger.info(f'MainWindow: Selected port {s}')
if s.startswith('network'):
mb = InputBox(title='Network address', text='Enter network address as "ipaddress[:port]"', cb=self._new_network_port)
mb.open()
else:
self.config.set('General', 'serial_port', s)
self.config.write()
def _new_network_port(self, s):
if s:
self.config.set('General', 'serial_port', f'net://{s}')
self.config.write()
@mainthread
def alarm_state(self, msg):
''' called when smoothie is in Alarm state (flg == True) or gets an error message (flg == False)'''
s, was_printing, flg = msg
if flg:
self.add_line_to_log(f"! alarm state: {s}")
else:
self.add_line_to_log(f"! error message: {s}")
if self.is_suspended:
self.add_line_to_log("! NOTE: currently suspended so must Abort as resume will not work")
elif was_printing:
if self.app.notify_email:
notify = Notify()
notify.send(f'Run in ALARM state: {s}, last Z: {self.wpos[2]}, last line: {self.get_last_line()}')
def do_kill(self):
if self.status == 'Alarm':
self.app.comms.write('$X\n')
else:
# are you sure?
mb = MessageBox(text='KILL - Are you Sure?', cb=self._do_kill)
mb.open()
def _do_kill(self, ok):
if ok:
if self.is_suspended:
# we have to abort as well
self._abort_print(True)
else:
self.app.comms.write('\x18')
def abort_print(self):
# are you sure?
mb = MessageBox(text='Abort - Are you Sure?', cb=self._abort_print)
mb.open()
def _abort_print(self, ok):
if ok:
if self.is_suspended:
# we have to KILL to get smoothie out of suspend state
self.is_suspended = False
self.app.comms.write('\x18')
self.app.comms.stream_pause(False, True)
@mainthread
def action_paused(self, paused, suspended=False):
# comms layer is telling us we paused or unpaused
self.ids.print_but.text = 'Resume' if paused else 'Pause'
self.paused = paused
self.is_suspended = suspended
if paused:
if suspended:
self.add_line_to_log(">>> Streaming Suspended, Resume or Abort as needed")
if self.app.notify_email:
Notify().send(f'Run has been suspended: last Z: {self.wpos[2]}, last line: {self.get_last_line()}')
else:
self.add_line_to_log(">>> Streaming Paused, Abort or Continue as needed")
else:
self.add_line_to_log(">>> Streaming Resumed")
def start_print(self, no_prompt=False):
if self.is_printing:
if not self.paused:
# we clicked the pause button
self.app.comms.stream_pause(True)
else:
# we clicked the resume button
if self.is_suspended:
# as we were suspended we need to resume the suspend first
# we let Smoothie tell us to resume from pause though
self.app.comms.write('resume\n')
else:
self.app.comms.stream_pause(False)
self.is_suspended = False
elif not no_prompt:
# get file to print
f = Factory.filechooser()
f.open(self.last_path, cb=self._start_print)
else:
self._start_print()
def _start_print(self, file_path=None, directory=None):
# start comms thread to stream the file
# set comms.ping_pong to False for fast stream mode
if file_path is None:
file_path = self.app.gcode_file
if directory is None:
directory = self.last_path
Logger.info(f'MainWindow: printing file: {file_path}')
try:
self.nlines = Comms.file_len(file_path, False) # get number of lines so we can do progress and ETA
Logger.debug(f'MainWindow: number of lines: {self.nlines}')
except Exception:
Logger.warning(f'MainWindow: exception in file_len: {traceback.format_exc()}')
self.nlines = None
self.start_print_time = datetime.datetime.now()
self.display(f'>>> Running file: {file_path}, {self.nlines} GCode lines')
if self.app.comms.stream_gcode(file_path, progress=lambda x: self.display_progress(x)):
self.display(f">>> Run started at: {self.start_print_time.strftime('%x %X')}")
else:
self.display('WARNING Unable to start print')
return
self.set_last_file(directory, file_path)
self.ids.print_but.text = 'Pause'
self.is_printing = True
self.paused = False
def set_last_file(self, directory, file_path):
if directory != self.last_path:
self.last_path = directory
self.config.set('General', 'last_gcode_path', directory)
self.app.gcode_file = file_path
self.config.set('General', 'last_print_file', file_path)
self.config.write()
def reprint(self):
# are you sure?
mb = MessageBox(text=f'ReRun\n{os.path.basename(self.app.gcode_file)}?', cb=self._reprint)
mb.open()
def _reprint(self, ok):
if ok:
self._start_print()
@mainthread
def start_last_file(self):
# Will also pause if already printing
if self.app.gcode_file:
self.start_print(no_prompt=True)
def review(self):
self._show_viewer(self.app.gcode_file, self.last_path)
def start_uart_log(self):
if self.is_uart_log_enabled:
# close it
if self.uart_log:
self.uart_log.close()
self.display('Uart log port closed')
if self.is_uart_log_in_view:
self.toggle_uart_view("up")
self.is_uart_log_enabled = False
self.uart_log = None
Logger.info('MainWindow: Closed Uart log port')
return
# open it
ll = self.app.comms.get_ports()
ports = []
for p in ll:
ports.append(f'{p.device}')
sb = SelectionBox(title='Select Uart log port', text='Select the uart log port to open from drop down', values=ports, cb=self._set_uart_port)
sb.open()
@mainthread
def _uart_log_input(self, dat):
txt = dat.rstrip()
Logger.info(f'BOOTLOG: {txt}')
if dat.startswith('ERROR:') or dat.startswith('FATAL:'):
txt = f"[color=ff0000]{txt}[/color]"
elif dat.startswith('WARNING:'):
txt = f"[color=ffff00]{txt}[/color]"
elif dat.startswith('INFO:'):
txt = f"[color=00ff00]{txt}[/color]"
elif dat.startswith('DEBUG:'):
txt = f"[color=0000ff]{txt}[/color]"
else:
txt = f"[color=ffffff]{txt}[/color]"
d = {'text': txt}
self.uart_log_data.append(d)
if self.is_uart_log_in_view:
# The uart log is in view
self.ids.log_window.data.append(d)
def _set_uart_port(self, s):
if s:
Logger.info(f'MainWindow: Selected Uart log port {s}')
self.uart_log = UartLogger(s)
if self.uart_log.open(self._uart_log_input):
self.is_uart_log_enabled = True
self.display(f'Uart log port {s} open')
else:
self.is_uart_log_enabled = False
self.uart_log = None
self.display(f'Error unable to open {s} as Uart log port')
def toggle_uart_view(self, state):
if state == "down":
self.save_console_data = []
for i in self.ids.log_window.data:
self.save_console_data.append(i)
self.ids.log_window.data = self.uart_log_data
self.is_uart_log_in_view = True
else:
self.is_uart_log_in_view = False
self.ids.log_window.data = self.save_console_data
self.save_console_data = None
@mainthread
def stream_finished(self, ok):
''' called when streaming gcode has finished, ok is True if it completed '''
self.ids.print_but.text = 'Run'
self.is_printing = False
now = datetime.datetime.now()
self.display(f">>> Run finished {'ok' if ok else 'abnormally'}")
self.display(f">>> Run ended at : {now.strftime('%x %X')}, last Z: {self.wpos[2]}, last line: {self.get_last_line()}")
et = datetime.timedelta(seconds=int((now - self.start_print_time).seconds))
self.display(f">>> Elapsed time: {et}")
self.eta = 'Not Streaming'
if self.app.notify_email:
notify = Notify()
notify.send(f"Run finished {'ok' if ok else 'abnormally'}, last Z: {self.wpos[2]}, last line: {self.get_last_line()}")
Logger.info(f"MainWindow: Run finished {'ok' if ok else 'abnormally'}, last Z: {self.wpos[2]}, last line: {self.get_last_line()}")
def upload_gcode(self):
# get file to upload
f = Factory.filechooser()
f.open(self.last_path, cb=self._upload_gcode)
@mainthread
def _upload_gcode_done(self, ok):
now = datetime.datetime.now()
self.display(f">>> Upload finished {'ok' if ok else 'abnormally'}")
et = datetime.timedelta(seconds=int((now - self.start_print_time).seconds))
self.display(f">>> Elapsed time: {et}")
self.eta = 'Not Streaming'
self.is_printing = False
self.app.comms.fast_stream = False
def _upload_gcode(self, file_path, dir_path):
if not file_path:
return
# use built-in fast stream for uploads
fast_stream = True
try:
self.nlines = Comms.file_len(file_path, fast_stream) # get number of lines so we can do progress and ETA
Logger.debug(f'MainWindow: number of lines: {self.nlines}')
except Exception:
Logger.warning(f'MainWindow: exception in file_len: {traceback.format_exc()}')
self.nlines = None
self.start_print_time = datetime.datetime.now()
self.display(f'>>> Uploading file: {file_path}, {self.nlines} lines')
# set fast stream mode if requested
self.app.comms.fast_stream = fast_stream
if not self.app.comms.upload_gcode(file_path, progress=lambda x: self.display_progress(x), done=self._upload_gcode_done):
self.display('WARNING Unable to upload file')
return
else:
self.is_printing = True
def fast_stream_gcode(self):
# get file to fast stream
f = Factory.filechooser()
f.open(self.last_path, cb=self._fast_stream_gcode)
def _fast_stream_gcode(self, file_path, dir_path):
if file_path and self.app.fast_stream_cmd:
cmd = self.app.fast_stream_cmd.replace("{file}", file_path)
t = threading.Thread(target=self._fast_stream_thread, daemon=True, args=(cmd,))
t.start()
def _fast_stream_thread(self, cmd):
# execute the command
self.async_display(f"External Fast stream > {cmd}")
self.start_print_time = datetime.datetime.now()
with subprocess.Popen(cmd, shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, universal_newlines=True) as p:
while True:
s = p.stdout.readline()
if not s:
break
s = s.rstrip()
if s.startswith('progress: '):
# progress: {},{}".format(n, nlines)
s = s[10:]
n, nlines = s.split(',')
self.nlines = int(nlines)
self.display_progress(int(n))
else:
self.async_display(s)
self.display_progress(0)
@mainthread
def display_progress(self, n):
if n == 0:
self.eta = 'Not Streaming'
return
if self.nlines and n <= self.nlines:
now = datetime.datetime.now()
d = (now - self.start_print_time).seconds
if n > 10 and d > 10:
# we have to wait a bit to get reasonable estimates
lps = n / d
eta = (self.nlines - n) / lps
else:
eta = 0
self.eta = f"ETA: {'Paused' if self.paused else datetime.timedelta(seconds=int(eta))} | {n / self.nlines:.1%}"
def list_sdcard(self):
if self.app.comms.list_sdcard(self._list_sdcard_results):
# TODO open waiting dialog
pass
@mainthread
def _list_sdcard_results(self, ll):
# dismiss waiting dialog
fl = {}
for f in ll:
f = f'/sd/{f}'