-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3632 lines (3126 loc) · 161 KB
/
main.py
File metadata and controls
3632 lines (3126 loc) · 161 KB
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 os
import quicklz
import struct
def is_android():
return 'ANDROID_ARGUMENT' in os.environ or 'ANDROID_PRIVATE' in os.environ or 'ANDROID_APP_PATH' in os.environ
if is_android():
try:
from jnius import autoclass
DisplayMetrics = autoclass('android.util.DisplayMetrics')
WindowManager = autoclass('android.view.WindowManager')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
activity = PythonActivity.mActivity
metrics = DisplayMetrics()
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics)
screen_width_density = int(metrics.widthPixels * 10 / 960) / 10
screen_height_density = int(metrics.heightPixels * 10 / 550) / 10
os.environ["KIVY_METRICS_DENSITY"] = str(min(screen_width_density, screen_height_density))
except ImportError:
print("Pyjnius Import Fail.")
# import os
# os.environ["KIVY_METRICS_DENSITY"] = '1'
import gettext
import locale
from kivy.lang import Observable
from os.path import dirname, join
# os.environ['KIVY_GL_DEBUG'] = '1'
from kivy.utils import platform
import sys
import time
import datetime
import threading
import logging
VERSION = '0.9.8'
FW_UPD_ADDRESS = 'https://raw.githubusercontent.com/MakeraInc/CarveraFirmware/main/version.txt'
CTL_UPD_ADDRESS = 'https://raw.githubusercontent.com/MakeraInc/CarveraController/main/version.txt'
DOWNLOAD_ADDRESS = 'https://www.makera.com/pages/software'
LANGS = {
'en': 'English',
'zh-CN': '中文简体(Simplified Chinese)',
}
class Lang(Observable):
observers = []
lang = None
def __init__(self, defaultlang):
super(Lang, self).__init__()
self.ugettext = None
self.lang = defaultlang
self.switch_lang(self.lang)
def _(self, text):
return self.ugettext(text)
def fbind(self, name, func, args, **kwargs):
if name == "_":
self.observers.append((func, args, kwargs))
else:
return super(Lang, self).fbind(name, func, *args, **kwargs)
def funbind(self, name, func, args, **kwargs):
if name == "_":
key = (func, args, kwargs)
if key in self.observers:
self.observers.remove(key)
else:
return super(Lang, self).funbind(name, func, *args, **kwargs)
def switch_lang(self, lang):
# get the right locales directory, and instanciate a gettext
locale_dir = join(dirname(__file__), 'locales')
locales = None
try:
locales = gettext.translation(lang, locale_dir, languages=[lang])
except:
pass
if locales == None:
locales = gettext.NullTranslations()
self.ugettext = locales.gettext
self.lang = lang
# update all the kv rules attached to this text
for func, largs, kwargs in self.observers:
func(largs, None, None)
from kivy.config import Config
# init language
default_lang = 'en'
if Config.has_option('carvera', 'language'):
default_lang = Config.get('carvera', 'language')
else:
try:
default_locale = locale.getdefaultlocale()
if default_locale != None:
for lang_key in LANGS.keys():
if default_locale[0][0:2] in lang_key:
default_lang = lang_key
break
except:
pass
tr = Lang(default_lang)
if not Config.has_section('carvera') or not Config.has_option('carvera', 'version') or Config.get('carvera', 'version') != VERSION:
if not Config.has_section('carvera'):
Config.add_section('carvera')
Config.set('carvera', 'version', VERSION)
if not Config.has_option('carvera', 'show_update'): Config.set('carvera', 'show_update', '1')
if not Config.has_option('carvera', 'language'): Config.set('carvera', 'language', default_lang)
if not Config.has_option('carvera', 'local_folder_1'): Config.set('carvera', 'local_folder_1', '')
if not Config.has_option('carvera', 'local_folder_2'): Config.set('carvera', 'local_folder_2', '')
if not Config.has_option('carvera', 'local_folder_3'): Config.set('carvera', 'local_folder_3', '')
if not Config.has_option('carvera', 'local_folder_4'): Config.set('carvera', 'local_folder_4', '')
if not Config.has_option('carvera', 'local_folder_5'): Config.set('carvera', 'local_folder_5', '')
if not Config.has_option('carvera', 'remote_folder_1'): Config.set('carvera', 'remote_folder_1', '')
if not Config.has_option('carvera', 'remote_folder_2'): Config.set('carvera', 'remote_folder_2', '')
if not Config.has_option('carvera', 'remote_folder_3'): Config.set('carvera', 'remote_folder_3', '')
if not Config.has_option('carvera', 'remote_folder_4'): Config.set('carvera', 'remote_folder_4', '')
if not Config.has_option('carvera', 'remote_folder_5'): Config.set('carvera', 'remote_folder_5', '')
# Default params, set only once
Config.set('kivy', 'window_icon', 'data/icon.png')
Config.set('kivy', 'exit_on_escape', '0')
Config.set('kivy', 'pause_on_minimize', '0')
Config.set('graphics', 'width', '960')
Config.set('graphics', 'height', '600')
Config.set('graphics', 'allow_screensaver', '0')
#Config.set('input', 'mouse', 'mouse, multitouch_on_demand')
Config.write()
Config.set('kivy', 'exit_on_escape', '0')
import json
import re
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.settings import SettingsWithSidebar, SettingItem
from kivy.uix.stencilview import StencilView
from kivy.uix.slider import Slider
from kivy.uix.dropdown import DropDown
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.modalview import ModalView
from kivy.properties import StringProperty
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.graphics import Color, Rectangle, Ellipse, Line
from kivy.properties import ObjectProperty, NumericProperty, ListProperty
from kivy.metrics import dp
from serial.tools.list_ports import comports
from functools import partial
from WIFIStream import MachineDetector
from kivy.core.window import Window
from kivy.network.urlrequest import UrlRequest
import webbrowser
from pathlib import Path
# import os
import shutil
import string
import Utils
from kivy.config import ConfigParser
from CNC import CNC
from GcodeViewer import GCodeViewer
from Controller import Controller, NOT_CONNECTED, STATECOLOR, STATECOLORDEF,\
LOAD_DIR, LOAD_MV, LOAD_RM, LOAD_MKDIR, LOAD_WIFI, LOAD_CONN_WIFI, CONN_USB, CONN_WIFI, SEND_FILE
#Config.set('graphics', 'width', '960')
#Config.set('graphics', 'height', '432')
# Config.write()
Window.softinput_mode = "below_target"
# print('windowsize: {}'.format(Window.size))
_device = None
_baud = None
SHORT_LOAD_TIMEOUT = 3 # s
WIFI_LOAD_TIMEOUT = 30 # s
HEARTBEAT_TIMEOUT = 10
MAX_TOUCH_INTERVAL = 0.15
GCODE_VIEW_SPEED = 1
LOAD_INTERVAL = 10000 # must be divisible by MAX_LOAD_LINES
MAX_LOAD_LINES = 10000
1# 定义块大小
BLOCK_SIZE = 4096
BLOCK_HEADER_SIZE = 4
HALT_REASON = {
# Just need to unlock the mahchine
1: tr._("Halt Manually"),
2: tr._("Home Fail"),
3: tr._("Probe Fail"),
4: tr._("Calibrate Fail"),
5: tr._("ATC Home Fail"),
6: tr._("ATC Invalid Tool Number"),
7: tr._("ATC Drop Tool Fail"),
8: tr._("ATC Position Occupied"),
9: tr._("Spindle Overheated"),
10: tr._("Soft Limit Triggered"),
11: tr._("Cover opened when playing"),
12: tr._("Wireless probe dead or not set"),
13: tr._("Emergency stop button pressed"),
# Need to reset the machine
21: tr._("Hard Limit Triggered, reset needed"),
22: tr._("X Axis Motor Error, reset needed"),
23: tr._("Y Axis Motor Error, reset needed"),
24: tr._("Z Axis Motor Error, reset needed"),
25: tr._("Spindle Stall, reset needed"),
26: tr._("SD card read fail, reset needed"),
# Need to power off/on the machine
41: tr._("Spindle Alarm, power off/on needed"),
}
class GcodePlaySlider(Slider):
def on_touch_down(self, touch):
if self.disabled:
return
released = super(GcodePlaySlider, self).on_touch_down(touch)
if released and self.collide_point(*touch.pos):
app = App.get_running_app()
app.root.gcode_viewer.set_pos_by_distance(self.value * app.root.gcode_viewer_distance / 1000)
return True
return released
def on_touch_move(self, touch):
if self.disabled:
return
released = super(GcodePlaySlider, self).on_touch_move(touch)
if self.collide_point(*touch.pos):
app = App.get_running_app()
app.root.gcode_viewer.set_pos_by_distance(self.value * app.root.gcode_viewer_distance / 1000)
# float_number = self.value * app.root.selected_file_line_count / 1000
# app.root.gcode_viewer.set_distance_by_lineidx(int(float_number), float_number - int(float_number))
return True
return released
class FloatBox(FloatLayout):
touch_interval = 0
def on_touch_down(self, touch):
if super(FloatBox, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and not self.gcode_ctl_bar.collide_point(*touch.pos):
if ('button' in touch.profile and touch.button == 'left') or not 'button' in touch.profile:
self.touch_interval = time.time()
def on_touch_up(self, touch):
if super(FloatBox, self).on_touch_up(touch):
return True
app = App.get_running_app()
if self.collide_point(*touch.pos) and not self.gcode_ctl_bar.collide_point(*touch.pos):
if ('button' in touch.profile and touch.button == 'left') or not 'button' in touch.profile:
if time.time() - self.touch_interval < MAX_TOUCH_INTERVAL:
app.show_gcode_ctl_bar = not app.show_gcode_ctl_bar
class BoxStencil(BoxLayout, StencilView):
pass
class ConfirmPopup(ModalView):
showing = False
def __init__(self, **kwargs):
super(ConfirmPopup, self).__init__(**kwargs)
def on_open(self):
self.showing = True
def on_dismiss(self):
self.showing = False
class MessagePopup(ModalView):
def __init__(self, **kwargs):
super(MessagePopup, self).__init__(**kwargs)
class InputPopup(ModalView):
cache_var1 = StringProperty('')
cache_var2 = StringProperty('')
cache_var3 = StringProperty('')
def __init__(self, **kwargs):
super(InputPopup, self).__init__(**kwargs)
class ProgressPopup(ModalView):
progress_text = StringProperty('')
progress_value = NumericProperty('0')
def __init__(self, **kwargs):
super(ProgressPopup, self).__init__(**kwargs)
class OriginPopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(OriginPopup, self).__init__(**kwargs)
def selected_anchor(self):
if self.cbx_anchor2.active:
return 2
elif self.cbx_4axis_origin.active:
return 3
elif self.cbx_current_position.active:
return 4
return 1
class ZProbePopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(ZProbePopup, self).__init__(**kwargs)
class XYZProbePopup(ModalView):
def __init__(self, **kwargs):
super(XYZProbePopup, self).__init__(**kwargs)
class LanguagePopup(ModalView):
def __init__(self, **kwargs):
super(LanguagePopup, self).__init__(**kwargs)
class PairingPopup(ModalView):
pairing = BooleanProperty(0)
countdown = NumericProperty(0)
pairing_note = StringProperty('')
pairing_success = False
def __init__(self, **kwargs):
self.pairing_string = {'start': tr._('Press the Wireless Probe until the green LED blinks quickly.'),
'success': tr._('Pairing Success!'),
'timeout': tr._('Pairing Timeout!')}
super(PairingPopup, self).__init__(**kwargs)
def start_pairing(self):
self.pairing = True
self.pairing_success = False
self.countdown = 30
self.pairing_note = self.pairing_string['start']
self.countdown_event = Clock.schedule_interval(self.pairing_countdown, 1)
def pairing_countdown(self, *args):
self.countdown = self.countdown - 1
if self.pairing_success:
self.pairing = False
self.pairing_note = self.pairing_string['success']
self.countdown_event.cancel()
elif self.countdown < 1:
self.pairing = False
self.pairing_note = self.pairing_string['timeout']
self.countdown_event.cancel()
class UpgradePopup(ModalView):
def __init__(self, **kwargs):
super(UpgradePopup, self).__init__(**kwargs)
class AutoLevelPopup(ModalView):
execute = False
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(AutoLevelPopup, self).__init__(**kwargs)
def init(self):
x_steps = int(self.sp_x_points.text)
y_steps = int(self.sp_y_points.text)
self.lb_min_x.text = "{:.2f}".format(CNC.vars['xmin'])
self.lb_max_x.text = "{:.2f}".format(CNC.vars['xmax'])
self.lb_step_x.text = "{:.2f}".format((CNC.vars['xmax'] - CNC.vars['xmin']) * 1.0 / x_steps)
self.lb_min_y.text = "{:.2f}".format(CNC.vars['ymin'])
self.lb_max_y.text = "{:.2f}".format(CNC.vars['ymax'])
self.lb_step_y.text = "{:.2f}".format((CNC.vars['ymax'] - CNC.vars['ymin']) * 1.0 / y_steps)
def init_and_open(self, execute = False):
self.execute = execute
self.init()
self.open()
class UpgradePopup(ModalView):
def __init__(self, **kwargs):
super(UpgradePopup, self).__init__(**kwargs)
class FilePopup(ModalView):
firmware_mode = BooleanProperty(False)
def __init__(self, **kwargs):
super(FilePopup, self).__init__(**kwargs)
def load_remote_page(self):
self.popup_manager.transition.direction = 'right'
self.popup_manager.transition.duration = 0.3
self.popup_manager.current = 'remote_page'
app = App.get_running_app()
if app.state == 'Idle':
self.remote_rv.current_dir()
# -----------------------------------------------------------------------
def load_remote_root(self):
self.remote_rv.child_dir('')
# -----------------------------------------------------------------------
def update_local_buttons(self):
has_select = False
app = App.get_running_app()
for key in self.local_rv.view_adapter.views:
if self.local_rv.view_adapter.views[key].selected and not self.local_rv.view_adapter.views[key].selected_dir:
has_select = True
break
self.btn_open.disabled = (not self.firmware_mode and not has_select) or (self.firmware_mode and app.state != 'Idle')
self.btn_upload.disabled = not has_select or app.state != 'Idle'
# -----------------------------------------------------------------------
def update_remote_buttons(self):
has_select = False
select_dir = False
for key in self.remote_rv.view_adapter.views:
if self.remote_rv.view_adapter.views[key].selected:
has_select = True
if self.remote_rv.view_adapter.views[key].selected_dir:
select_dir = True
break
self.btn_delete.disabled = not has_select
self.btn_rename.disabled = not has_select
self.btn_select.disabled = (not has_select) or select_dir
class CoordPopup(ModalView):
config = {}
mode = StringProperty()
vacuummode = ObjectProperty()
origin_popup = ObjectProperty()
zprobe_popup = ObjectProperty()
auto_level_popup = ObjectProperty()
setx_popup = ObjectProperty()
sety_popup = ObjectProperty()
setz_popup = ObjectProperty()
seta_popup = ObjectProperty()
MoveA_popup = ObjectProperty()
def __init__(self, config, **kwargs):
self.config = config
self.origin_popup = OriginPopup(self)
self.zprobe_popup = ZProbePopup(self)
self.auto_level_popup = AutoLevelPopup(self)
self.setx_popup = SetXPopup(self)
self.sety_popup = SetYPopup(self)
self.setz_popup = SetZPopup(self)
self.seta_popup = SetAPopup(self)
self.MoveA_popup = MoveAPopup(self)
self.mode = 'Run' # 'Margin' / 'ZProbe' / 'Leveling'
super(CoordPopup, self).__init__(**kwargs)
def set_config(self, key1, key2, value):
self.config[key1][key2] = value
self.cnc_workspace.draw()
def load_config(self):
self.cnc_workspace.load_config(self.config)
Clock.schedule_once(self.cnc_workspace.draw, 0)
# init origin popup
self.origin_popup.cbx_anchor1.active = self.config['origin']['anchor'] == 1
self.origin_popup.cbx_anchor2.active = self.config['origin']['anchor'] == 2
self.origin_popup.cbx_4axis_origin.active = self.config['origin']['anchor'] == 3
self.origin_popup.cbx_current_position.active = self.config['origin']['anchor'] == 4
self.origin_popup.txt_x_offset.text = str(self.config['origin']['x_offset'])
self.origin_popup.txt_y_offset.text = str(self.config['origin']['y_offset'])
self.load_origin_label()
if CNC.vars["vacuummode"] == 1:
self.vacuummode = True
else:
self.vacuummode = False
# init margin widgets
self.cbx_margin.active = self.config['margin']['active']
# init zprobe widgets
self.cbx_zprobe.active = self.config['zprobe']['active']
# init zprobe popup
self.zprobe_popup.cbx_origin1.active = self.config['zprobe']['origin'] == 1
self.zprobe_popup.cbx_origin2.active = self.config['zprobe']['origin'] == 2
self.zprobe_popup.txt_x_offset.text = str(self.config['zprobe']['x_offset'])
self.zprobe_popup.txt_y_offset.text = str(self.config['zprobe']['y_offset'])
self.load_zprobe_label()
# init leveling widgets
self.cbx_leveling.active = self.config['leveling']['active']
self.auto_level_popup.sp_x_points.text = str(self.config['leveling']['x_points'])
self.auto_level_popup.sp_y_points.text = str(self.config['leveling']['y_points'])
self.auto_level_popup.sp_height.text = str(self.config['leveling']['height'])
self.load_leveling_label()
def load_origin_label(self):
app = App.get_running_app()
if app.has_4axis:
self.lb_origin.text = '(%g, %g) ' % (round(CNC.vars["wcox"] - CNC.vars['anchor1_x'] - CNC.vars['rotation_offset_x'], 4), \
round(CNC.vars['wcoy'] - CNC.vars['anchor1_y'] - CNC.vars['rotation_offset_y'], 4)) + tr._('from Headstock')
else:
laser_x = CNC.vars['laser_module_offset_x'] if CNC.vars['lasermode'] else 0.0
laser_y = CNC.vars['laser_module_offset_y'] if CNC.vars['lasermode'] else 0.0
if self.config['origin']['anchor'] == 2:
self.lb_origin.text = '(%g, %g) ' % (round(CNC.vars['wcox'] + laser_x - CNC.vars["anchor1_x"] - CNC.vars["anchor2_offset_x"], 4), \
round(CNC.vars['wcoy'] + laser_y - CNC.vars["anchor1_y"] - CNC.vars["anchor2_offset_y"], 4)) + tr._('from Anchor2')
else:
self.lb_origin.text = '(%g, %g) ' % (round(CNC.vars['wcox'] + laser_x - CNC.vars["anchor1_x"], 4), round(CNC.vars['wcoy'] + laser_y - CNC.vars["anchor1_y"], 4)) + tr._('from Anchor1')
def load_zprobe_label(self):
app = App.get_running_app()
if app.has_4axis:
self.lb_zprobe.text = '(%g, %g) ' % (round(CNC.vars["anchor1_x"] + CNC.vars['rotation_offset_x'] - 3, 4), round(CNC.vars["anchor1_y"] + CNC.vars['rotation_offset_y'], 4)) + tr._('Fixed Pos')
else:
self.lb_zprobe.text = '(%g, %g) ' % (round(self.config['zprobe']['x_offset'], 4), round(self.config['zprobe']['y_offset'], 4)) + tr._('from') \
+ ' %s' % (tr._('Work Origin') if self.config['zprobe']['origin'] == 1 else tr._('Path Origin'))
def load_leveling_label(self):
self.lb_leveling.text = tr._('X Points: ') + '%d ' % (self.config['leveling']['x_points']) \
+ tr._('Y Points: ') + '%d ' % (self.config['leveling']['y_points']) \
+ tr._('Height: ') + '%d' % (self.config['leveling']['height'])
def toggle_config(self):
# upldate main status
app = App.get_running_app()
app.root.update_coord_config()
class DiagnosePopup(ModalView):
showing = False
def __init__(self, **kwargs):
super(DiagnosePopup, self).__init__(**kwargs)
def on_open(self):
self.showing = True
def on_dismiss(self):
self.showing = False
class ConfigPopup(ModalView):
def __init__(self, **kwargs):
super(ConfigPopup, self).__init__(**kwargs)
def on_open(self):
pass
def on_dismiss(self):
pass
class SetXPopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(SetXPopup, self).__init__(**kwargs)
class SetYPopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(SetYPopup, self).__init__(**kwargs)
class SetZPopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(SetZPopup, self).__init__(**kwargs)
class SetAPopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(SetAPopup, self).__init__(**kwargs)
class MoveAPopup(ModalView):
def __init__(self, coord_popup, **kwargs):
self.coord_popup = coord_popup
super(MoveAPopup, self).__init__(**kwargs)
class MakeraConfigPanel(SettingsWithSidebar):
def on_config_change(self, config, section, key, value):
app = App.get_running_app()
if not app.root.config_loading:
if section != 'Restore':
app.root.setting_change_list[key] = Utils.to_config(app.root.setting_type_list[key], value).strip()
app.root.config_popup.btn_apply.disabled = False
elif key == 'restore' and value == 'RESTORE':
app.root.open_setting_restore_confirm_popup()
elif key == 'default' and value == 'DEFAULT':
app.root.open_setting_default_confirm_popup()
class XDropDown(DropDown):
pass
class YDropDown(DropDown):
pass
class ZDropDown(DropDown):
pass
class ADropDown(DropDown):
pass
class FeedDropDown(DropDown):
opened = False
def on_dismiss(self):
self.opened = False
class SpindleDropDown(DropDown):
opened = False
def on_dismiss(self):
self.opened = False
class ToolDropDown(DropDown):
opened = False
def on_dismiss(self):
self.opened = False
class LaserDropDown(DropDown):
opened = False
def on_dismiss(self):
self.opened = False
class FuncDropDown(DropDown):
pass
class StatusDropDown(DropDown):
def __init__(self, **kwargs):
super(StatusDropDown, self).__init__(**kwargs)
class ComPortsDropDown(DropDown):
def __init__(self, **kwargs):
super(DropDown, self).__init__(**kwargs)
class OperationDropDown(DropDown):
pass
class MachineButton(Button):
ip = StringProperty("")
port = NumericProperty(2222)
busy = BooleanProperty(False)
class IconButton(BoxLayout, Button):
icon = StringProperty("fresk.png")
class TransparentButton(BoxLayout, Button):
icon = StringProperty("fresk.png")
class TransparentGrayButton(BoxLayout, Button):
icon = StringProperty("fresk.png")
class WiFiButton(BoxLayout, Button):
ssid = StringProperty("")
encrypted = BooleanProperty(False)
strength = NumericProperty(1000)
connected = BooleanProperty(False)
class CNCWorkspace(Widget):
config = {}
# -----------------------------------------------------------------------
def __init__(self, **kwargs):
self.bind(size=self.on_draw)
super(CNCWorkspace, self).__init__(**kwargs)
def load_config(self, config):
self.config = config
def draw(self, *args):
if self.x <= 100:
return
self.canvas.clear()
zoom = self.width / CNC.vars['worksize_x']
with self.canvas:
# background
Color(50 / 255, 50 / 255, 50 / 255, 1)
Rectangle(pos=self.pos, size=self.size)
app = App.get_running_app()
if not app.has_4axis:
# anchor1
if self.config['origin']['anchor'] == 1:
Color(75 / 255, 75 / 255, 75 / 255, 1)
else:
Color(55 / 255, 55 / 255, 55 / 255, 1)
Rectangle(pos=(self.x, self.y),
size=(CNC.vars['anchor_length'] * zoom, CNC.vars['anchor_width'] * zoom))
Rectangle(pos=(self.x, self.y),
size=(CNC.vars['anchor_width'] * zoom, CNC.vars['anchor_length'] * zoom))
# anchor2
if self.config['origin']['anchor'] == 2:
Color(75 / 255, 75 / 255, 75 / 255, 1)
else:
Color(55 / 255, 55 / 255, 55 / 255, 1)
Rectangle(pos=(self.x + CNC.vars['anchor2_offset_x'] * zoom, self.y + CNC.vars['anchor2_offset_y'] * zoom),
size=(CNC.vars['anchor_length'] * zoom, CNC.vars['anchor_width'] * zoom))
Rectangle(pos=(self.x + CNC.vars['anchor2_offset_x'] * zoom, self.y + CNC.vars['anchor2_offset_y'] * zoom),
size=(CNC.vars['anchor_width'] * zoom, CNC.vars['anchor_length'] * zoom))
else:
rotation_base_y_center = (CNC.vars['anchor_width'] + CNC.vars['rotation_offset_y']) * zoom
# draw rotation base
Color(60 / 255, 60 / 255, 60 / 255, 1)
Rectangle(pos=(self.x, self.y + rotation_base_y_center - CNC.vars['rotation_base_height'] * zoom / 2),
size=(CNC.vars['rotation_base_width'] * zoom, CNC.vars['rotation_base_height'] * zoom))
# draw rotation head
Color(75 / 255, 75 / 255, 75 / 255, 1)
Rectangle(pos=(self.x, self.y + rotation_base_y_center - CNC.vars['rotation_head_height'] * zoom / 2),
size=(CNC.vars['rotation_head_width'] * zoom, CNC.vars['rotation_head_height'] * zoom))
# draw rotation chuck
Color(75 / 255, 75 / 255, 75 / 255, 1)
Rectangle(pos=(self.x + (CNC.vars['rotation_head_width'] + CNC.vars['rotation_chuck_interval']) * zoom, self.y + rotation_base_y_center - CNC.vars['rotation_chuck_dia'] * zoom / 2),
size=(CNC.vars['rotation_chuck_width'] * zoom, CNC.vars['rotation_chuck_dia'] * zoom))
# draw rotation tail
Color(75 / 255, 75 / 255, 75 / 255, 1)
Rectangle(pos=(self.x + (CNC.vars['rotation_base_width'] - CNC.vars['rotation_tail_width']) * zoom, self.y + rotation_base_y_center - CNC.vars['rotation_tail_height'] * zoom / 2),
size=(CNC.vars['rotation_tail_width'] * zoom, CNC.vars['rotation_tail_height'] * zoom))
# draw rotation probe position
# Color(200 / 255, 200 / 255, 200 / 255, 1)
# Line(points=[self.x + (CNC.vars['rotation_offset_x'] + CNC.vars['anchor_width'] - 5) * zoom, self.y + (CNC.vars['rotation_offset_y'] + CNC.vars['anchor_width']) * zoom,
# self.x + (CNC.vars['rotation_offset_x'] + CNC.vars['anchor_width'] + 5) * zoom, self.y + (CNC.vars['rotation_offset_y'] + CNC.vars['anchor_width']) * zoom], width=1)
# Line(points=[self.x + (CNC.vars['rotation_offset_x'] + CNC.vars['anchor_width']) * zoom, self.y + (CNC.vars['rotation_offset_y'] + CNC.vars['anchor_width'] - 5) * zoom,
# self.x + (CNC.vars['rotation_offset_x'] + CNC.vars['anchor_width']) * zoom, self.y + (CNC.vars['rotation_offset_y'] + CNC.vars['anchor_width'] + 5) * zoom], width=1)
laser_x = CNC.vars['laser_module_offset_x'] if CNC.vars['lasermode'] else 0.0
laser_y = CNC.vars['laser_module_offset_y'] if CNC.vars['lasermode'] else 0.0
# origin
Color(52/255, 152/255, 219/255, 1)
origin_x = CNC.vars['wcox'] - CNC.vars['anchor1_x'] + CNC.vars['anchor_width'] + laser_x
origin_y = CNC.vars['wcoy'] - CNC.vars['anchor1_y'] + CNC.vars['anchor_width'] + laser_y
Ellipse(pos=(self.x + origin_x * zoom - 10, self.y + origin_y * zoom - 10), size=(20, 20))
# work area
Color(0, 0.8, 0, 1)
Line(width=(2 if self.config['margin']['active'] else 1), rectangle=(self.x + (origin_x + CNC.vars['xmin']) * zoom, self.y + (origin_y + CNC.vars['ymin']) * zoom,
(CNC.vars['xmax'] - CNC.vars['xmin']) * zoom, (CNC.vars['ymax'] - CNC.vars['ymin']) * zoom))
# z probe
if self.config['zprobe']['active']:
Color(231 / 255, 76 / 255, 60 / 255, 1)
zprobe_x = self.config['zprobe']['x_offset'] + (origin_x if self.config['zprobe']['origin'] == 1 else origin_x + CNC.vars['xmin'])
zprobe_y = self.config['zprobe']['y_offset'] + (origin_y if self.config['zprobe']['origin'] == 1 else origin_y + CNC.vars['ymin'])
if app.has_4axis:
zprobe_x = CNC.vars['rotation_offset_x'] + CNC.vars['anchor_width'] - 3.0
zprobe_y = CNC.vars['rotation_offset_y'] + CNC.vars['anchor_width']
Ellipse(pos=(self.x + zprobe_x * zoom - 7.5, self.y + zprobe_y * zoom - 7.5), size=(15, 15))
# auto leveling
if self.config['leveling']['active']:
Color(244/255, 208/255, 63/255, 1)
for x in Utils.xfrange(0.0, CNC.vars['xmax'] - CNC.vars['xmin'], self.config['leveling']['x_points']):
for y in Utils.xfrange(0.0, CNC.vars['ymax'] - CNC.vars['ymin'], self.config['leveling']['y_points']):
Ellipse(pos=(self.x + (origin_x + CNC.vars['xmin'] + x) * zoom - 5, self.y + (origin_y + CNC.vars['ymin'] + y) * zoom - 5), size=(10, 10))
# print('x=%f, y=%f' % (x, y))
def on_draw(self, obj, value):
self.draw()
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''
class TopDataView(BoxLayout, Button):
pass
class DirectoryView(BoxLayout, Button):
pass
class DropDownHint(Label):
pass
class DropDownSplitter(Label):
pass
class SelectableLabel(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(SelectableLabel, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
if touch.is_double_tap:
app = App.get_running_app()
app.root.manual_cmd.text = self.text.strip()
Clock.schedule_once(app.root.refocus_cmd)
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
class SelectableBoxLayout(RecycleDataViewBehavior, BoxLayout):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selected_dir = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableBoxLayout, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableBoxLayout, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
if touch.is_double_tap:
rv = self.parent.recycleview
if rv.data[self.index]['is_dir']:
rv.child_dir(rv.data[self.index]['filename'])
return True
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 self.selected:
if rv.data[self.index]['is_dir']:
self.selected_dir = True
else:
self.selected_dir = False
rv.set_curr_selected_file(rv.data[self.index]['filename'], rv.data[self.index]['intsize'])
rv.dispatch('on_select')
# -----------------------------------------------------------------------
# Data Recycle View
# -----------------------------------------------------------------------
class DataRV(RecycleView):
curr_dir = ''
curr_dir_name = StringProperty('')
base_dir = ''
base_dir_win = ''
curr_sort_key = StringProperty('date')
curr_sort_reverse = BooleanProperty(True)
curr_sort_str = ListProperty(['', ' ↓', ''])
curr_path_list = ListProperty([])
curr_full_path_list = []
curr_file_list_buff = []
default_sort_reverse = {'name': False, 'date': True, 'size' : False}
search_event = None
curr_selected_file = ''
curr_selected_filesize = 0
def __init__(self, **kwargs):
super(DataRV, self).__init__(**kwargs)
self.register_event_type('on_select')
# -----------------------------------------------------------------------
def on_select(self):
pass
# -----------------------------------------------------------------------
def set_curr_selected_file(self, filename, filesize):
self.curr_selected_file = os.path.join(self.curr_dir, filename)
self.curr_selected_filesize = filesize
# -----------------------------------------------------------------------
def clear_selection(self):
for key in self.view_adapter.views:
if self.view_adapter.views[key].selected != None:
self.view_adapter.views[key].selected = False
# -----------------------------------------------------------------------
def child_dir(self, child_dir):
new_path = os.path.join(self.curr_dir, child_dir)
self.list_dir(new_dir = new_path)
def fill_dir(self, sort_key = None, switch_reverse = True, keyword = None):
if sort_key == None:
sort_key = self.curr_sort_key
sort_reverse = self.curr_sort_reverse
if sort_key != self.curr_sort_key:
sort_reverse = self.default_sort_reverse[sort_key]
self.curr_sort_reverse = sort_reverse
self.curr_sort_key = sort_key
else:
if switch_reverse:
self.curr_sort_reverse = not self.curr_sort_reverse
sort_reverse = self.curr_sort_reverse
if sort_key == 'name':
self.curr_sort_str = ['↓' if sort_reverse else '↑', '', '']
elif sort_key == 'date':
self.curr_sort_str = ['', '↓' if sort_reverse else '↑', '']
elif sort_key == 'size':
self.curr_sort_str = ['', '', '↓' if sort_reverse else '↑']
self.curr_file_list_buff = sorted(self.curr_file_list_buff, key = lambda x: x[sort_key], reverse = sort_reverse)
filtered_list = []
app = App.get_running_app()
if app.root.file_popup.firmware_mode:
filtered_list = filter(lambda x: x['is_dir'] or 'firmware' in x['name'], self.curr_file_list_buff)
else:
if keyword == None or keyword.strip() == '':
filtered_list = self.curr_file_list_buff
else:
filtered_list = filter(lambda x: keyword.lower() in x['name'].lower(), self.curr_file_list_buff)
# fill out the list
self.clear_selection()
self.data = []
rv_key = 0
for file in filtered_list:
self.data.append({'rv_key': rv_key, 'filename': file['name'], 'intsize': file['size'],
'filesize': '--' if file['is_dir'] else Utils.humansize(file['size']),
'filedate': Utils.humandate(file['date']), 'is_dir': file['is_dir']})
rv_key += 1
# trigger
self.dispatch('on_select')
def goto_path(self, index):
if index < len(self.curr_full_path_list):
app = App.get_running_app()
app.root.file_popup.ti_local_search.text = ''
self.list_dir(new_dir = self.curr_full_path_list[index])
def delay_search(self, keyword):
#if keyword == None or keyword.strip() == '':
# return
if self.search_event is not None:
self.search_event.cancel()
self.search_event = Clock.schedule_once(partial(self.execute_search, keyword), 1)
def execute_search(self, keyword, *args):
self.fill_dir(keyword = keyword, switch_reverse = False)
self.search_event = None
# -----------------------------------------------------------------------
# Remote Recycle View
# -----------------------------------------------------------------------
class RemoteRV(DataRV):
# -----------------------------------------------------------------------
def __init__(self, **kwargs):
super(RemoteRV, self).__init__(**kwargs)
self.register_event_type('on_select')
self.base_dir = '/sd/gcodes'
self.base_dir_win = '\\sd\\gcodes'
self.curr_dir = self.base_dir
self.curr_dir_name = 'gcodes'
# -----------------------------------------------------------------------
def parent_dir(self):
normpath = os.path.normpath(self.curr_dir)
if normpath == self.base_dir or normpath == self.base_dir_win:
self.list_dir(new_dir = normpath)
else:
self.list_dir(new_dir = os.path.dirname(normpath))