forked from DanalEstes/TAMV
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathTAMV.py
2627 lines (2492 loc) · 127 KB
/
TAMV.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
#!/usr/bin/env python3
import argparse, logging, os, sys, traceback, time
from logging.handlers import RotatingFileHandler
from urllib.parse import urlparse
# openCV imports
from cv2 import cvtColor, COLOR_BGR2RGB
# Qt imports
from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal, QSize, QThread, QMutex
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QStyle, QWidget, QMenu, QAction, QStatusBar, QLabel, QHBoxLayout, QVBoxLayout, QTextEdit, QPushButton, QApplication, QTabWidget, QButtonGroup, QGridLayout, QFrame, QCheckBox
# Other imports
import json
import numpy as np
import copy
import threading
# Custom modules import
from modules.SettingsDialog import SettingsDialog
from modules.ConnectionDialog import ConnectionDialog
from modules.DetectionManager import DetectionManager
from modules.PrinterManager import PrinterManager
from modules.StatusTipFilter import StatusTipFilter
########################################################################### Core application class
class App(QMainWindow):
# Global mutex
__mutex = QMutex()
# Signals
######## Detection Manager
startVideoSignal = pyqtSignal()
setImagePropertiesSignal = pyqtSignal(object)
getVideoFrameSignal = pyqtSignal()
# Endstop detection signals
toggleEndstopDetectionSignal = pyqtSignal(bool)
toggleEndstopAutoDetectionSignal = pyqtSignal(bool)
# Nozzle detection signals
toggleNozzleDetectionSignal = pyqtSignal(bool)
toggleNozzleAutoDetectionSignal = pyqtSignal(bool)
# UV coordinates update signal
getUVCoordinatesSignal = pyqtSignal()
# Master detection enable/disable signal
toggleDetectionSignal = pyqtSignal(bool)
######## Printer Manager
connectSignal = pyqtSignal(object)
disconnectSignal = pyqtSignal(object)
moveRelativeSignal = pyqtSignal(object)
moveAbsoluteSignal = pyqtSignal(object)
callToolSignal = pyqtSignal(int)
unloadToolSignal = pyqtSignal()
pollCoordinatesSignal = pyqtSignal()
pollCurrentToolSignal = pyqtSignal()
setOffsetsSignal = pyqtSignal(object)
limitAxesSignal = pyqtSignal()
flushBufferSignal = pyqtSignal()
saveToFirmwareSignal = pyqtSignal()
announceSignal = pyqtSignal(bool)
# Settings Dialog
resetImageSignal = pyqtSignal()
pushbuttonSize = 38
# default move speed in feedrate/min
__moveSpeed = 6000
# Maximum number of retries for detection
__maxRetries = 3
# Maximum runtime (in seconds) for calibration cycles
__maxRuntime = 120
# Timeout for Qthread termination (DetectionManager and PrinterManager)
__detectionManagerThreadWaitTime = 20
__printerManagerThreadWaitTime = 60
########################################################################### Initialize class
def __init__(self, parent=None):
# send calling to log
_logger.debug('*** calling App.__init__')
# output greeting to log
_logger.info('Initializing application.. ')
# call QMainWindow init function
super().__init__()
#### class attributes definition
if(True):
# main window size
self.windowWidthOriginal, self.windowHeightOriginal = 800, 600
# main camera capture size
# self.imageWidthOriginal, self.imageHeightOriginal = 640, 480
# stylesheets used for interface status updates
self.styleGreen = '* { background-color: green; color: white;} QToolTip { color: black; background-color: #DDDDDD } *:hover{background-color: #003874; color: #ffa000;} *:pressed{background-color: #ffa000; color: #003874;}'
self.styleRed = '* { background-color: red; color: white;} QToolTip { color: black; background-color: #DDDDDD }'
self.styleDisabled = '* { background-color: #cccccc; color: #999999; border-style: solid;} QToolTip { color: black; background-color: #DDDDDD }'
self.styleOrange = '* { background-color: dark-grey; color: #ffa000;} QToolTip { color: black; background-color: #DDDDDD }'
self.styleBlue = '* { background-color: #003874; color: #ffa000;} QToolTip { color: black; background-color: #DDDDDD }'
self.styleDefault = '* { background-color: rgba(0,0,0,0); color: black;} QToolTip { color: black; background-color: #DDDDDD }'
# standby image placeholder
self.standbyImage = QPixmap('./resources/background.png')
self.errorImage = QPixmap('./resources/error.png')
# user-defined cameras array
self.__cameras = []
# active camera
self.__activeCamera ={}
# user-defined printers array
self.__printers = []
# active printer
self.__activePrinter = {}
# Control Point
self.__cpCoordinates = {'X': None, 'Y': None, 'Z': None}
self.__currentPosition = {'X': None, 'Y': None, 'Z': None}
self.__stateManualCPCapture = False
self.__stateAutoCPCapture = False
self.__stateEndstopAutoCalibrate = False
self.__restorePosition = None
self.__firstConnection = False
self.state = 0
# Camera transform matrix
self.transformMatrix = None
self.transform_input = None
self.mpp = None
# Nozzle detection
self.__stateAutoNozzleAlignment = False
self.__stateOverrideManualNozzleAlignment = False
self.singleToolOffsetsCapture = False
self.__displayCrosshair = False
#### setup window properties
if(True):
_logger.debug(' .. setting up window properties..')
self.setWindowFlag(Qt.WindowContextHelpButtonHint,False)
self.setWindowTitle('TAMV')
self.setWindowIcon(QIcon('./resources/jubilee.png'))
screen = QDesktopWidget().availableGeometry()
self.setGeometry(QStyle.alignedRect(Qt.LeftToRight,Qt.AlignHCenter,QSize(self.windowWidthOriginal,self.windowHeightOriginal),screen))
self.setMinimumWidth(self.windowWidthOriginal)
self.setMinimumHeight(self.windowHeightOriginal)
appScreen = self.frameGeometry()
appScreen.moveCenter(screen.center())
self.move(appScreen.topLeft())
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
# create stylehseets
self.globalStylesheet = '\
QLabel#instructions_text {\
background-color: rgba(255,153,0,.4);\
}\
QPushButton {\
border: 1px solid #adadad;\
border-style: outset;\
border-radius: 4px;\
font: 16px;\
padding: 2px;\
}\
QPushButton>QToolTip {\
color: black;\
}\
QPushButton#calibrating:enabled {\
background-color: orange;\
color: white;\
}\
QPushButton#completed:enabled {\
background-color: blue;\
color: white;\
}\
QPushButton:hover,QPushButton:enabled:hover,QPushButton:enabled:!checked:hover,QPushButton#completed:enabled:hover {\
background-color: #003874;\
color: #ffa000;\
border: 1px solid #aaaaaa;\
}\
QPushButton:pressed,QPushButton:enabled:pressed,QPushButton:enabled:checked,QPushButton#completed:enabled:pressed {\
background-color: #ffa000;\
border: 1px solid #aaaaaa;\
}\
QPushButton:enabled {\
background-color: green;\
color: white;\
}\
QLabel#labelPlus {\
font: 20px;\
padding: 0px;\
}\
QPushButton#plus:enabled {\
font: 20px;\
padding: 0px;\
background-color: #eeeeee;\
color: #000000;\
}\
QPushButton#plus:enabled:hover {\
font: 20px;\
padding: 0px;\
background-color: green;\
color: #000000;\
}\
QPushButton#plus:enabled:pressed {\
font: 20px;\
padding: 0px;\
background-color: #FF0000;\
color: #222222;\
}\
QPushButton#debug,QMessageBox > #debug {\
background-color: blue;\
color: white;\
}\
QPushButton#debug:hover, QMessageBox > QAbstractButton#debug:hover {\
background-color: green;\
color: white;\
}\
QPushButton#debug:pressed, QMessageBox > QAbstractButton#debug:pressed {\
background-color: #ffa000;\
border-style: inset;\
color: white;\
}\
QPushButton#active, QMessageBox > QAbstractButton#active {\
background-color: green;\
color: white;\
}\
QPushButton#active:pressed,QMessageBox > QAbstractButton#active:pressed {\
background-color: #ffa000;\
}\
QPushButton#terminate {\
background-color: red;\
color: white;\
}\
QPushButton#terminate:pressed {\
background-color: #c0392b;\
}\
QPushButton:disabled, QPushButton#terminate:disabled {\
background-color: #cccccc;\
color: #999999;\
}\
QInputDialog QDialogButtonBox > QPushButton:enabled, QDialog QPushButton:enabled,QPushButton[checkable="true"]:enabled {\
background-color: none;\
color: black;\
border: 1px solid #adadad;\
border-style: outset;\
border-radius: 4px;\
font: 14px;\
padding: 6px;\
}\
QPushButton:enabled:checked {\
background-color: #ffa000;\
border: 1px solid #aaaaaa;\
}\
QInputDialog QDialogButtonBox > QPushButton:pressed, QDialog QPushButton:pressed {\
background-color: #ffa000;\
}\
QInputDialog QDialogButtonBox > QPushButton:hover:!pressed, QDialog QPushButton:hover:!pressed {\
background-color: #003874;\
color: #ffa000;\
}\
QToolTip, QLabel > QToolTip, QPushButton > QLabel> QToolTip {\
color: black;\
}\
'
self.setStyleSheet(self.globalStylesheet)
#### Driver API imports
if(True):
try:
self.__firmwareList = []
self.__driverList = []
with open('drivers.json','r') as inputfile:
driverJSON = json.load(inputfile)
_logger.info(' .. loading drivers..')
for driverEntry in driverJSON:
self.__firmwareList.append(driverEntry['firmware'])
self.__driverList.append(driverEntry['filename'])
except:
_logger.critical('Cannot load driver definitions: ' + traceback.format_exc())
raise SystemExit('Cannot load driver definitions.')
#### Setup components
# load user parameters
if(True):
try:
with open('./config/settings.json','r') as inputfile:
self.__userSettings = json.load(inputfile)
except FileNotFoundError:
try:
# try and see if moving from older build
with open('./settings.json','r') as inputfile:
self.__userSettings = json.load(inputfile)
try:
_logger.info(' .. moving settings file to /config/settings.json.. ')
# create config folder if it doesn't exist
os.makedirs('./config',exist_ok=True)
# move settings.json to new config folder
os.replace('./settings.json','./config/settings.json')
except:
_logger.warning('Cannot rename old settings.json, leaving in place and using new file.')
except FileNotFoundError:
# create config folder if it doesn't exist
os.makedirs('./config',exist_ok=True)
# No settings file defined, create a default file
_logger.info(' .. creating new settings.json..')
self.__userSettings = {}
# create a camera array
self.__userSettings['camera'] = [
{
'video_src': 0,
'display_width': '640',
'display_height': '480',
'default': 1
} ]
# Create a printer array
self.__userSettings['printer'] = [
{
'address': 'http://localhost',
'password': 'reprap',
'name': 'My Duet',
'nickname': 'Default',
'controller' : 'RRF',
'version': '',
'default': 1,
'rotated': 0,
'tools': [
{
'number': 0,
'name': 'Tool 0',
'nozzleSize': 0.4,
'offsets': [0,0,0]
} ]
} ]
try:
# set class attributes
self._cameraWidth = int(self.__userSettings['camera'][0]['display_width'])
self._cameraHeight = int(self.__userSettings['camera'][0]['display_height'])
self._videoSrc = self.__userSettings['camera'][0]['video_src']
# save default settings file
with open('./config/settings.json','w') as outputfile:
json.dump(self.__userSettings, outputfile)
except Exception as e1:
errorMsg = 'Error reading user settings file.' + traceback.format_exc()
_logger.critical(errorMsg)
raise SystemExit(errorMsg)
_logger.info(' .. reading configuration settings..')
# Fetch defined cameras
if(True):
defaultCameraDefined = False
for source in self.__userSettings['camera']:
try:
self.__cameras.append(source)
if(source['default'] == 1 and defaultCameraDefined is False):
self.__activeCamera = source
defaultCameraDefined = True
elif(defaultCameraDefined):
source['default'] = 0
continue
except KeyError as ke:
source['default'] = 0
continue
if(defaultCameraDefined is False):
self.__userSettings['camera'][0]['default'] = 1
self.__activeCamera = self.__userSettings['camera'][0]
self._cameraHeight = int(self.__activeCamera['display_height'])
self._cameraWidth = int(self.__activeCamera['display_width'])
self._videoSrc = self.__activeCamera['video_src']
if(len(str(self._videoSrc)) == 1 or str(self._videoSrc) == "-1"):
self._videoSrc = int(self._videoSrc)
# Fetch defined machines
if(True):
defaultPrinterDefined = False
for machine in self.__userSettings['printer']:
# Find default printer first
try:
self.__printers.append(machine)
if(machine['default'] == 1):
self.__activePrinter = machine
defaultPrinterDefined = True
except KeyError as ke:
# no default field detected - create a default if not already done
if(defaultPrinterDefined is False):
machine['default'] = 1
defaultPrinterDefined = True
else:
machine['default'] = 0
# Check if password doesn't exist
try:
temp = machine['password']
except KeyError:
machine['password'] = 'reprap'
# Check if nickname doesn't exist
try:
temp = machine['nickname']
except KeyError:
machine['nickname'] = machine['name']
# Check if controller doesn't exist
try:
temp = machine['controller']
except KeyError:
machine['controller'] = 'RRF'
# Check if version doesn't exist
try:
temp = machine['version']
except KeyError:
machine['version'] = ''
# Check if rotated kinematics doesn't exist
try:
temp = machine['rotated']
except KeyError:
machine['rotated'] = 0
# Check if tools doesn't exist
try:
temp = machine['tools']
except KeyError:
machine['tools'] = [ { 'number': 0, 'name': 'Tool 0', 'nozzleSize': 0.4, 'offsets': [0,0,0] } ]
if(machine['default'] == 1):
self.__activePrinter = machine
# Check if we have no default machine
if(defaultPrinterDefined is False):
self.__activePrinter = self.__userSettings['printer'][0]
if(self.__activePrinter['controller'] == 'RRF'):
(_errCode, _errMsg, self.printerURL) = self.sanitizeURL(self.__activePrinter['address'])
self.__activePrinter['address'] = self.printerURL
if _errCode > 0:
# invalid input
_logger.error('Invalid printer URL detected in settings.json')
_logger.error(_errMsg)
_logger.info('Defaulting to \"http://localhost\"...')
self.printerURL = 'http://localhost'
##### Settings Dialog
self.__settingsGeometry = None
# Note: settings dialog is created when user clicks the button
#### Setup interface
##### Menu bar
self.setupMenu()
##### Status bar
self.setupStatusbar()
##### GUI elements
self.setupMainWindow()
# send exiting to log
_logger.debug('*** exiting App.__init__')
########################################################################### Menu setup
def setupMenu(self):
# send calling to log
_logger.debug('*** calling App.setupMenu')
self.menubar = self.menuBar()
self.menubar.installEventFilter(StatusTipFilter(self))
#### File menu
fileMenu = QMenu('&File', self)
self.menubar.addMenu(fileMenu)
#### Preferences
self.preferencesAction = QAction(self)
self.preferencesAction.setText('&Preferences..')
self.preferencesAction.triggered.connect(self.displayPreferences)
fileMenu.addAction(self.preferencesAction)
#### Save offsets to firmware
self.saveFirmwareAction = QAction(self)
self.saveFirmwareAction.setText('&Save offsets..')
self.saveFirmwareAction.triggered.connect(self.saveOffsets)
fileMenu.addAction(self.saveFirmwareAction)
# Quit
self.quitAction = QAction(self)
self.quitAction.setText('&Quit')
self.quitAction.triggered.connect(self.close)
fileMenu.addSeparator()
fileMenu.addAction(self.quitAction)
# send exiting to log
_logger.debug('*** exiting App.setupMenu')
########################################################################### Status bar setup
def setupStatusbar(self):
# send calling to log
_logger.debug('*** calling App.setupStatusbar')
self.statusBar = QStatusBar()
self.statusBar.showMessage('Welcome.')
self.setStatusBar(self.statusBar)
#### CP coodinate status
self.cpLabel = QLabel('<b>CP:</b> <i>undef</i>')
self.statusBar.addPermanentWidget(self.cpLabel)
self.cpLabel.setStyleSheet(self.styleOrange)
#### Connection status
self.connectionStatusLabel = QLabel('<i>Disconnected</i>')
self.connectionStatusLabel.setStyleSheet(self.styleOrange)
self.statusBar.addPermanentWidget(self.connectionStatusLabel)
# send exiting to log
_logger.debug('*** exiting App.setupStatusbar')
########################################################################### Main window setup
def setupMainWindow(self):
# send calling to log
_logger.debug('*** calling App.setupMenu')
self.containerLayout = QVBoxLayout()
self.containerLayout.setSpacing(8)
self.centralWidget.setLayout(self.containerLayout)
#### Main grid layout
if(True):
self.mainLayout = QHBoxLayout()
self.mainLayout.setSpacing(8)
self.containerLayout.addLayout(self.mainLayout)
##### Left toolbar
if(True):
self.leftToolbarLayout = QVBoxLayout()
self.leftToolbarLayout.setAlignment(Qt.AlignTop)
self.mainLayout.addLayout(self.leftToolbarLayout)
# Connect button
self.connectButton = QPushButton('+')
self.connectButton.setStyleSheet(self.styleDisabled)
self.connectButton.setMinimumSize(self.pushbuttonSize,self.pushbuttonSize)
self.connectButton.setMaximumSize(self.pushbuttonSize,self.pushbuttonSize)
self.connectButton.setToolTip('Connect..')
self.connectButton.setDisabled(True)
self.connectButton.clicked.connect(self.connectPrinter)
self.leftToolbarLayout.addWidget(self.connectButton)#, 1, 0, 1, 1, Qt.AlignLeft|Qt.AlignTop)
# Disconnect button
self.disconnectButton = QPushButton('D')
self.disconnectButton.setStyleSheet(self.styleDisabled)
self.disconnectButton.setMinimumSize(self.pushbuttonSize,self.pushbuttonSize)
self.disconnectButton.setMaximumSize(self.pushbuttonSize,self.pushbuttonSize)
self.disconnectButton.setToolTip('Disconnect..')
self.disconnectButton.setDisabled(True)
self.disconnectButton.clicked.connect(self.haltPrinterOperation)
self.leftToolbarLayout.addWidget(self.disconnectButton)#, 1, 0, 1, 1, Qt.AlignLeft|Qt.AlignTop)
# Crosshair button
self.crosshairDisplayButton = QPushButton('-+-')
self.crosshairDisplayButton.setStyleSheet(self.styleBlue)
self.crosshairDisplayButton.setMinimumSize(self.pushbuttonSize,self.pushbuttonSize)
self.crosshairDisplayButton.setMaximumSize(self.pushbuttonSize,self.pushbuttonSize)
self.crosshairDisplayButton.setToolTip('toggle crosshair on display')
self.crosshairDisplayButton.setDisabled(False)
self.crosshairDisplayButton.setChecked(False)
self.crosshairDisplayButton.clicked.connect(self.toggleCrosshair)
self.leftToolbarLayout.addWidget(self.crosshairDisplayButton)
# Setup Control Point button
self.cpSetupButton = QPushButton('CP')
self.cpSetupButton.setStyleSheet(self.styleDisabled)
self.cpSetupButton.setMinimumSize(self.pushbuttonSize,self.pushbuttonSize)
self.cpSetupButton.setMaximumSize(self.pushbuttonSize,self.pushbuttonSize)
self.cpSetupButton.setToolTip('Setup Control Point..')
self.cpSetupButton.setDisabled(True)
self.cpSetupButton.clicked.connect(self.setupCPCapture)
self.leftToolbarLayout.addWidget(self.cpSetupButton)
# CP Automated Capture button
self.cpAutoCaptureButton = QPushButton('Auto')
self.cpAutoCaptureButton.setStyleSheet(self.styleDisabled)
self.cpAutoCaptureButton.setMinimumSize(self.pushbuttonSize,self.pushbuttonSize)
self.cpAutoCaptureButton.setMaximumSize(self.pushbuttonSize,self.pushbuttonSize)
self.cpAutoCaptureButton.setToolTip('Automated CP Capture..')
self.cpAutoCaptureButton.setDisabled(True)
self.cpAutoCaptureButton.clicked.connect(self.setupCPAutoCapture)
self.leftToolbarLayout.addWidget(self.cpAutoCaptureButton)
##### Main image preview
if(True):
self.image = QLabel(self)
self.image.resize(self._cameraWidth, self._cameraHeight)
self.image.setMinimumWidth(self._cameraWidth)
self.image.setMinimumHeight(self._cameraHeight)
self.image.setAlignment(Qt.AlignLeft)
# self.image.setStyleSheet('text-align:center; border: 1px solid black')
self.image.setPixmap(self.standbyImage)
self.mainLayout.addWidget(self.image)#, 1, 1, 1, -1, Qt.AlignLeft|Qt.AlignTop)
##### Right toolbar
if(True):
# Jog Panel
self.tabPanel = QTabWidget()
self.firstTab = QWidget()
self.jogPanel = QGridLayout()
self.jogPanel.setAlignment(Qt.AlignRight|Qt.AlignTop)
self.jogPanel.setSpacing(5)
# create jogPanel buttons
## increment size
self.button_1 = QPushButton('1')
self.button_1.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_1.setMaximumHeight(self.pushbuttonSize)
self.button_1.setToolTip('set jog distance to 1 unit')
self.button_01 = QPushButton('.1')
self.button_01.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_01.setMaximumHeight(self.pushbuttonSize)
self.button_01.setToolTip('set jog distance to 0.1 unit')
self.button_001 = QPushButton('.01')
self.button_001.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_001.setMaximumHeight(self.pushbuttonSize)
self.button_001.setToolTip('set jog distance to 0.01 unit')
self.incrementButtonGroup = QButtonGroup()
self.incrementButtonGroup.addButton(self.button_1)
self.incrementButtonGroup.addButton(self.button_01)
self.incrementButtonGroup.addButton(self.button_001)
self.incrementButtonGroup.setExclusive(True)
self.button_1.setCheckable(True)
self.button_01.setCheckable(True)
self.button_001.setCheckable(True)
self.button_1.setChecked(True)
# horizontal separators
self.incrementLine = QFrame()
self.incrementLine.setFrameShape(QFrame.HLine)
self.incrementLine.setLineWidth(1)
self.incrementLine.setFrameShadow(QFrame.Sunken)
self.keypadLine = QFrame()
self.keypadLine.setFrameShape(QFrame.HLine)
self.keypadLine.setFrameShadow(QFrame.Sunken)
self.keypadLine.setLineWidth(1)
## X movement
self.button_x_left = QPushButton('-X', objectName='plus')
self.button_x_left.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_x_left.setMaximumHeight(self.pushbuttonSize)
self.button_x_left.setToolTip('jog X-')
self.button_x_left.clicked.connect(self.xleftClicked)
self.button_x_right = QPushButton('X+', objectName='plus')
self.button_x_right.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_x_right.setMaximumHeight(self.pushbuttonSize)
self.button_x_right.setToolTip('jog X+')
self.button_x_right.clicked.connect(self.xRightClicked)
## Y movement
self.button_y_left = QPushButton('-Y', objectName='plus')
self.button_y_left.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_y_left.setMaximumHeight(self.pushbuttonSize)
self.button_y_left.setToolTip('jog Y-')
self.button_y_left.clicked.connect(self.yleftClicked)
self.button_y_right = QPushButton('Y+', objectName='plus')
self.button_y_right.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_y_right.setMaximumHeight(self.pushbuttonSize)
self.button_y_right.setToolTip('jog Y+')
self.button_y_right.clicked.connect(self.yRightClicked)
## Z movement
self.button_z_down = QPushButton('-Z', objectName='plus')
self.button_z_down.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_z_down.setMaximumHeight(self.pushbuttonSize)
self.button_z_down.setToolTip('jog Z-')
self.button_z_down.clicked.connect(self.zleftClicked)
self.button_z_up = QPushButton('Z+', objectName='plus')
self.button_z_up.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
self.button_z_up.setMaximumHeight(self.pushbuttonSize)
self.button_z_up.setToolTip('jog Z+')
self.button_z_up.clicked.connect(self.zRightClicked)
## layout jogPanel buttons
# add increment buttons
self.jogPanel.addWidget(self.button_001,0,0)
self.jogPanel.addWidget(self.button_01,0,1)
self.jogPanel.addWidget(self.button_1,1,1)
# add separator
self.jogPanel.addWidget(self.incrementLine, 2,0,1,2)
# add X movement buttons
self.jogPanel.addWidget(self.button_x_left,3,0)
self.jogPanel.addWidget(self.button_x_right,3,1)
# add Y movement buttons
self.jogPanel.addWidget(self.button_y_left,4,0)
self.jogPanel.addWidget(self.button_y_right,4,1)
# add Z movement buttons
self.jogPanel.addWidget(self.button_z_down,5,0)
self.jogPanel.addWidget(self.button_z_up,5,1)
# add separator
self.jogPanel.addWidget(self.keypadLine, 6,0,1,2)
self.tabPanel.setDisabled(True)
self.mainLayout.addWidget(self.tabPanel)
self.firstTab.setLayout(self.jogPanel)
self.tabPanel.addTab(self.firstTab,'Jog')
self.tabPanel.setFixedWidth(95)
self.tabPanel.setTabBarAutoHide(True)
self.tabPanel.setStyleSheet('QTabWidget::pane {\
margin: -13px -9px -13px -9px;\
border: 1px solid white;\
padding: 0px;\
}')
#### Footer layout
if(True):
self.footerLayout = QGridLayout()
self.footerLayout.setSpacing(0)
self.containerLayout.addLayout(self.footerLayout)
# Intructions box
self.instructionsBox = QTextEdit()
self.instructionsBox.setReadOnly(True)
self.instructionsBox.setFixedSize(640, 45)
self.instructionsBox.setVisible(False)
self.footerLayout.addWidget(self.instructionsBox, 0,0,1,-1,Qt.AlignLeft|Qt.AlignVCenter)
# Manual CP Capture button
self.manualCPCaptureButton = QPushButton('Save CP')
self.manualCPCaptureButton.setStyleSheet(self.styleDisabled)
self.manualCPCaptureButton.setMinimumSize(self.pushbuttonSize*2,self.pushbuttonSize)
self.manualCPCaptureButton.setMaximumSize(self.pushbuttonSize*2,self.pushbuttonSize)
self.manualCPCaptureButton.setToolTip('Capture current machine coordinates as the Control Point.')
self.manualCPCaptureButton.setDisabled(True)
self.manualCPCaptureButton.setVisible(False)
self.manualCPCaptureButton.clicked.connect(self.manualCPCapture)
self.footerLayout.addWidget(self.manualCPCaptureButton, 0,1,1,1,Qt.AlignRight|Qt.AlignVCenter)
# Override Manual Tool offset Capture button
self.overrideManualOffsetCaptureButton = QPushButton('Capture offset')
self.overrideManualOffsetCaptureButton.setStyleSheet(self.styleDisabled)
self.overrideManualOffsetCaptureButton.setMinimumSize(self.pushbuttonSize*3,self.pushbuttonSize)
self.overrideManualOffsetCaptureButton.setMaximumSize(self.pushbuttonSize*3,self.pushbuttonSize)
self.overrideManualOffsetCaptureButton.setToolTip('Capture current position and calculate tool offset.')
self.overrideManualOffsetCaptureButton.setDisabled(True)
self.overrideManualOffsetCaptureButton.setVisible(False)
self.overrideManualOffsetCaptureButton.clicked.connect(self.overrideManualToolOffsetCapture)
self.footerLayout.addWidget(self.overrideManualOffsetCaptureButton, 0,1,1,1,Qt.AlignRight|Qt.AlignVCenter)
# Manual Tool offset Capture button
self.manualToolOffsetCaptureButton = QPushButton('Capture offset')
self.manualToolOffsetCaptureButton.setStyleSheet(self.styleDisabled)
self.manualToolOffsetCaptureButton.setMinimumSize(self.pushbuttonSize*3,self.pushbuttonSize)
self.manualToolOffsetCaptureButton.setMaximumSize(self.pushbuttonSize*3,self.pushbuttonSize)
self.manualToolOffsetCaptureButton.setToolTip('Capture current position and calculate tool offset.')
self.manualToolOffsetCaptureButton.setDisabled(True)
self.manualToolOffsetCaptureButton.setVisible(False)
self.manualToolOffsetCaptureButton.clicked.connect(self.manualToolOffsetCapture)
self.footerLayout.addWidget(self.manualToolOffsetCaptureButton, 0,0,1,1,Qt.AlignRight|Qt.AlignVCenter)
# Start Alignment button
self.startAlignToolsButton = QPushButton('Align Tools')
self.startAlignToolsButton.setStyleSheet(self.styleDisabled)
self.startAlignToolsButton.setMinimumSize(self.pushbuttonSize*3,self.pushbuttonSize)
self.startAlignToolsButton.setMaximumSize(self.pushbuttonSize*3,self.pushbuttonSize)
self.startAlignToolsButton.setToolTip('Start automated tool offset calibration')
self.startAlignToolsButton.setDisabled(True)
self.startAlignToolsButton.setVisible(False)
self.startAlignToolsButton.clicked.connect(self.startAlignTools)
self.footerLayout.addWidget(self.startAlignToolsButton, 0,1,1,1,Qt.AlignRight|Qt.AlignVCenter)
# Resume auto alignment button
self.resumeAutoToolAlignmentButton = QPushButton('Resume Auto Align')
self.resumeAutoToolAlignmentButton.setMinimumSize(self.pushbuttonSize*4,self.pushbuttonSize)
self.resumeAutoToolAlignmentButton.setMaximumSize(self.pushbuttonSize*4,self.pushbuttonSize)
self.resumeAutoToolAlignmentButton.setToolTip('Resume automated calibration')
self.resumeAutoToolAlignmentButton.setDisabled(True)
self.resumeAutoToolAlignmentButton.setVisible(False)
self.resumeAutoToolAlignmentButton.clicked.connect(self.resumeAutoAlignment)
self.footerLayout.addWidget(self.resumeAutoToolAlignmentButton, 0,0,1,1,Qt.AlignRight|Qt.AlignVCenter)
#### Set current interface state to disconnected
self.stateDisconnected()
# send exiting to log
_logger.debug('*** exiting App.setupMenu')
########################################################################### Jog Panel functions
def xleftClicked(self):
# disable buttons
self.tabPanel.setDisabled(True)
# fetch current increment value
if self.button_1.isChecked():
incrementDistance = 1
elif self.button_01.isChecked():
incrementDistance = 0.1
elif self.button_001.isChecked():
incrementDistance = 0.01
params = {'moveSpeed': self.__moveSpeed, 'position':{'X': str(-1*incrementDistance)}}
self.moveRelativeSignal.emit(params)
def xRightClicked(self):
# disable buttons
self.tabPanel.setDisabled(True)
# fetch current increment value
if self.button_1.isChecked():
incrementDistance = 1
elif self.button_01.isChecked():
incrementDistance = 0.1
elif self.button_001.isChecked():
incrementDistance = 0.01
params = {'moveSpeed': self.__moveSpeed, 'position':{'X': str(incrementDistance)}}
self.moveRelativeSignal.emit(params)
def yleftClicked(self):
# disable buttons
self.tabPanel.setDisabled(True)
# fetch current increment value
if self.button_1.isChecked():
incrementDistance = 1
elif self.button_01.isChecked():
incrementDistance = 0.1
elif self.button_001.isChecked():
incrementDistance = 0.01
params = {'moveSpeed': self.__moveSpeed, 'position':{'Y': str(-1*incrementDistance)}}
self.moveRelativeSignal.emit(params)
def yRightClicked(self):
# disable buttons
self.tabPanel.setDisabled(True)
# fetch current increment value
if self.button_1.isChecked():
incrementDistance = 1
elif self.button_01.isChecked():
incrementDistance = 0.1
elif self.button_001.isChecked():
incrementDistance = 0.01
params = {'moveSpeed': self.__moveSpeed, 'position':{'Y': str(incrementDistance)}}
self.moveRelativeSignal.emit(params)
def zleftClicked(self):
# disable buttons
self.tabPanel.setDisabled(True)
# fetch current increment value
if self.button_1.isChecked():
incrementDistance = 1
elif self.button_01.isChecked():
incrementDistance = 0.1
elif self.button_001.isChecked():
incrementDistance = 0.01
params = {'moveSpeed': self.__moveSpeed, 'position':{'Z': str(-1*incrementDistance)}}
self.moveRelativeSignal.emit(params)
def zRightClicked(self):
# disable buttons
self.tabPanel.setDisabled(True)
# fetch current increment value
if self.button_1.isChecked():
incrementDistance = 1
elif self.button_01.isChecked():
incrementDistance = 0.1
elif self.button_001.isChecked():
incrementDistance = 0.01
params = {'moveSpeed': self.__moveSpeed, 'position':{'Z': str(incrementDistance)}}
self.moveRelativeSignal.emit(params)
########################################################################### GUI State functions
def stateDisconnected(self):
# Settings option in menu
self.preferencesAction.setDisabled(False)
# Connect button
self.connectButton.setVisible(True)
self.connectButton.setDisabled(False)
self.connectButton.setStyleSheet(self.styleGreen)
# Disconnect button
self.disconnectButton.setVisible(False)
self.disconnectButton.setDisabled(True)
self.disconnectButton.setStyleSheet(self.styleDisabled)
# Setup CP button
self.cpSetupButton.setVisible(False)
self.cpSetupButton.setDisabled(True)
self.cpSetupButton.setStyleSheet(self.styleDisabled)
# CP Automated Capture button
self.cpAutoCaptureButton.setVisible(False)
self.cpAutoCaptureButton.setDisabled(True)
self.cpAutoCaptureButton.setStyleSheet(self.styleDisabled)
# Manual capture button
self.manualCPCaptureButton.setVisible(False)
self.manualCPCaptureButton.setDisabled(True)
self.manualCPCaptureButton.setStyleSheet(self.styleDisabled)
# Start Alignment button
self.startAlignToolsButton.setVisible(False)
self.startAlignToolsButton.setDisabled(True)
self.startAlignToolsButton.setText('Align Tools')
self.startAlignToolsButton.setStyleSheet(self.styleDisabled)
# Override Manual Tool offset Capture button
self.overrideManualOffsetCaptureButton.setVisible(False)
self.overrideManualOffsetCaptureButton.setDisabled(True)
self.overrideManualOffsetCaptureButton.setStyleSheet(self.styleDisabled)
# Manual Tool offset Capture button
self.manualToolOffsetCaptureButton.setDisabled(True)
self.manualToolOffsetCaptureButton.setVisible(False)
self.manualToolOffsetCaptureButton.setStyleSheet(self.styleDisabled)
# Resume auto alignment button
self.resumeAutoToolAlignmentButton.setVisible(False)
self.resumeAutoToolAlignmentButton.setDisabled(True)
self.resumeAutoToolAlignmentButton.setStyleSheet(self.styleDisabled)
# Delete tool buttons
count = self.jogPanel.count()
for i in range(11,count):
item = self.jogPanel.itemAt(i)
widget = item.widget()
widget.setVisible(False)
# widget.deleteLater()
self.resetCalibration()
# Crosshair display button
self.crosshairDisplayButton.setVisible(True)
self.crosshairDisplayButton.setDisabled(False)
if(self.__displayCrosshair):
self.crosshairDisplayButton.setStyleSheet(self.styleOrange)
self.crosshairDisplayButton.setChecked(True)
else:
self.crosshairDisplayButton.setStyleSheet(self.styleBlue)
self.crosshairDisplayButton.setChecked(False)
# Jog panel tab
self.tabPanel.setDisabled(True)
def stateConnected(self):
# Settings option in menu
self.preferencesAction.setDisabled(False)
# Connect button
self.connectButton.setVisible(False)
self.connectButton.setDisabled(True)
self.connectButton.setStyleSheet(self.styleDisabled)
# Disconnect button
self.disconnectButton.setVisible(True)
self.disconnectButton.setDisabled(False)
self.disconnectButton.setStyleSheet(self.styleRed)
self.disconnectButton.setText('D')
self.disconnectButton.setToolTip('Disconnect..')
# Setup CP button
self.cpSetupButton.setVisible(True)
self.cpSetupButton.setDisabled(False)
self.cpSetupButton.setStyleSheet(self.styleGreen)
# CP Automated Capture button
self.cpAutoCaptureButton.setVisible(False)
self.cpAutoCaptureButton.setDisabled(True)
self.cpAutoCaptureButton.setStyleSheet(self.styleDisabled)
# Manual capture button
self.manualCPCaptureButton.setVisible(False)
self.manualCPCaptureButton.setDisabled(True)
self.manualCPCaptureButton.setStyleSheet(self.styleDisabled)
# Start Alignment button
self.startAlignToolsButton.setVisible(False)
self.startAlignToolsButton.setDisabled(True)
self.startAlignToolsButton.setText('Align Tools')
self.startAlignToolsButton.setStyleSheet(self.styleDisabled)
# Override Manual Tool offset Capture button
self.overrideManualOffsetCaptureButton.setVisible(False)
self.overrideManualOffsetCaptureButton.setDisabled(True)
self.overrideManualOffsetCaptureButton.setStyleSheet(self.styleDisabled)
# Manual Tool offset Capture button
self.manualToolOffsetCaptureButton.setDisabled(True)
self.manualToolOffsetCaptureButton.setVisible(False)
self.manualToolOffsetCaptureButton.setStyleSheet(self.styleDisabled)
# Resume auto alignment button
self.resumeAutoToolAlignmentButton.setVisible(False)
self.resumeAutoToolAlignmentButton.setDisabled(True)
self.resumeAutoToolAlignmentButton.setStyleSheet(self.styleDisabled)
# Jog panel tab
self.tabPanel.setDisabled(False)
# Add tool checkboxes to right panel
self.toolButtons = []
self.toolCheckboxes = []
# highest tool number storage
numTools = max(self.__activePrinter['tools'], key= lambda x:int(x['number']))['number']
_logger.debug('Highest tool number is: ' + str(numTools))
# Delete old toolbuttons, if they exist
# Delete tool buttons
count = self.jogPanel.count()
for i in range(11,count):
item = self.jogPanel.itemAt(i)
widget = item.widget()
widget.deleteLater()
currentTool = 0
for tool in range(numTools+1):
# add tool buttons
toolButton = QPushButton('T' + str(tool))
toolButton.setObjectName('toolButton_'+str(tool))
toolButton.setFixedSize(self.pushbuttonSize,self.pushbuttonSize)
toolButton.clicked.connect(self.identifyToolButton)
# check if current index exists in tool numbers from machine
if(any(d.get('number', -1) == tool for d in self.__activePrinter['tools'])):
toolTip = 'Fetch T' + str(tool) + ' to current machine position.'
toolTip += '<pre>'
toolTip += 'X: ' + "{:>9.3f}".format(self.__activePrinter['tools'][currentTool]['offsets'][0])
toolTip += '<br>'
toolTip += 'Y: ' + "{:>9.3f}".format(self.__activePrinter['tools'][currentTool]['offsets'][1])
toolTip += '<br>'
toolTip += 'Z: ' + "{:>9.3f}".format(self.__activePrinter['tools'][currentTool]['offsets'][2])
toolTip += '</pre>'
currentTool += 1
toolButton.setToolTip(toolTip)
self.toolButtons.append(toolButton)
# add tool checkboxes
toolCheckbox = QCheckBox()
toolCheckbox.setObjectName('toolCheckbox_' + str(tool))
toolCheckbox.setToolTip('Add T' + str(tool) + ' to calibration.')
toolCheckbox.setChecked(True)
toolCheckbox.setCheckable(True)
toolCheckbox.setObjectName('toolCheckbox_' + str(tool))
self.toolCheckboxes.append(toolCheckbox)
# Display tool buttons
for i,button in enumerate(self.toolButtons):
button.setCheckable(True)
index = button.objectName()
index = int(index[-1:])
if int(self.__activePrinter['currentTool']) == index:
button.setChecked(True)
else:
button.setChecked(False)
# button.clicked.connect(self.callTool)
self.jogPanel.addWidget(button, (7+i), 0, Qt.AlignCenter|Qt.AlignHCenter)
# Display tool checkboxes
for i,checkbox in enumerate(self.toolCheckboxes):
checkbox.setCheckable(True)
checkbox.setChecked(True)
# button.clicked.connect(self.callTool)
self.jogPanel.addWidget(checkbox, (7+i), 1, Qt.AlignCenter|Qt.AlignHCenter)
# Alignment/Detection state reset
self.state = 0
# Endstop calibration state flags
self.__stateManualCPCapture = False
self.__stateAutoCPCapture = False
self.__stateEndstopAutoCalibrate = False
self.toggleEndstopAutoDetectionSignal.emit(False)
# Nozzle calibration state flags
self.__stateOverrideManualNozzleAlignment = False
self.__stateAutoNozzleAlignment = False
self.toggleNozzleAutoDetectionSignal.emit(False)
# Crosshair display button
self.crosshairDisplayButton.setVisible(True)
self.crosshairDisplayButton.setDisabled(False)
if(self.__displayCrosshair):