/
psi_jetson.py
executable file
·1132 lines (963 loc) · 43.8 KB
/
psi_jetson.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/python3
import socket
import sys
def lockFile(lockfile):
#fp = open(lockfile, 'w')
try:
#fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
global s
s = socket.socket()
host = socket.gethostname()
s.bind((host, 60123))
except :
return False
return True
if not lockFile(".lock.pid"):
sys.exit(0)
import os
import io
import time
#import picamera
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5.QtCore import pyqtSlot,Qt, QThread, pyqtSignal
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QDialog, QStyleFactory, QLineEdit, QHBoxLayout, QMessageBox)
from PyQt5.QtGui import QIcon, QPixmap, QImage, QPainter,QPen,QCursor,QMouseEvent,QKeySequence
from PyQt5.uic import loadUi
import logging
from login import LoginDialog
import PhotoViewer
import json
import threading
from multiprocessing import Process
from datetime import datetime
import shutil
import cv2
from serialstatus import FDProtocol
import serial
#from xmlrpc.client import ServerProxy
#import xmlrpc.client
import subprocess
import numpy as np
import testScrew
import myconstdef
import resource
from CSICamera import CSI_Camera
import dlgResult
import urllib.request
files = []
#CURSOR_NEW = QtGui.QCursor(QtGui.QPixmap('cursor.png'))
def listImages(path):
#path = 'c:\\projects\\hc2\\'
# r=root, d=directories, f = files
for r, _, f in os.walk(path):
for file in f:
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
files.append(os.path.join(r, file))
class StatusCheckThread(QThread):
#https://kushaldas.in/posts/pyqt5-thread-example.html
signal = pyqtSignal(int)
def __init__(self, myvar, parent=None):
QThread.__init__(self, parent)
self.serialport = "/dev/ttyUSB0"
self.exit_event = threading.Event()
self.mylock = myvar
self.threhold = 40000
#sudo usermod -a -G tty qa
#sudo chown qa /dev/ttyUSB0
os.system("echo %s | sudo -S usermod -a -G tty qa" % myconstdef.PASSWORD)
os.system("echo %s | sudo -S chown qa /dev/ttyUSB0" % myconstdef.PASSWORD)
def setThrehold(self, value):
self.threhold = value
# run method gets called when we start the thread
def run(self):
ser = serial.serial_for_url('alt://{}'.format(self.serialport), baudrate=115200, timeout=1)
#ser = serial.Serial('/dev/ttyUSB0', baudrate=9600, timeout=1)
status=-1
oldstatus=-1
with serial.threaded.ReaderThread(ser, FDProtocol) as statusser:
while not self.exit_event.is_set():
statusser.setProxThreshold(self.threhold)
if statusser.proximityStatus and statusser.laserStatus:
if status!=1:
status=1
#do task start
elif statusser.laserStatus and not statusser.proximityStatus:
if status != 3:# ready
status = 3
elif not statusser.proximityStatus and not statusser.laserStatus:
if status != 3:
continue
if status!=2:
status=2
#start preview
#
if not self.mylock.locked():
if oldstatus != status:
self.signal.emit(status)
oldstatus = status
#time.sleep(0.05)
self.msleep(50)
statusser.stop()
class UISettings(QDialog):
"""Settings dialog widget
"""
#filepath=""
keyboardID=0
#resized = pyqtSignal()
imageview = pyqtSignal(QPixmap, int)
ViewerPreViewMode = pyqtSignal(bool)
ClearImageShow = pyqtSignal(int)
ShowRepeatTime = pyqtSignal(int)
def __init__(self, parent=None):
super(UISettings, self).__init__()
self.logger = logging.getLogger('PSILOG')
spathUI = os.path.join(os.path.dirname(os.path.realpath(__file__)),"psi_auto.ui")
loadUi(spathUI, self)
self.setWindowFlags(Qt.FramelessWindowHint)
self.changeStyle('Fusion')
self.takelock = threading.Lock()
self.takepic = threading.Event()
self.stop_prv = threading.Event()
self.stop_DryRun = threading.Event()
self.pbClose.clicked.connect(self.closeEvent)
self.tabImages.tabBar().hide()
self.tabSetting.tabBar().hide()
self.tabAllSetting.tabBar().hide()
self.leUserID.setText("12345")
self.pbTop.clicked.connect(self.on_CameraChange)
self.pbLeft.clicked.connect(self.on_CameraChange)
self.pbRight.clicked.connect(self.on_CameraChange)
self.pbtabDryrun.clicked.connect(self.On_settingChange)
self.pbtabSetting.clicked.connect(self.On_settingChange)
self.pbtabProfile.clicked.connect(self.On_settingChange)
self.pbExitSetting.clicked.connect(self.On_ExitSettingMode)
self.pbProfileDelete.clicked.connect(self.On_DeleteProfile)
self.pbStart.clicked.connect(self.on_startclick)
self.pbFinish.clicked.connect(self.on_startPreview)
self.pbShowSetting.clicked.connect(self.On_ShowSetting)
self.pbSettingSave.clicked.connect(self.On_SaveSetting)
self.pbDryRunStart.clicked.connect(self.On_DryRun)
self.pbDryRunStop.clicked.connect(self.On_DryRun)
self.clientA = CSI_Camera()
self.clientB = CSI_Camera()
self.pbProfileSelect.clicked.connect(self.On_ShowProfile)
self.pbProfileEdit.clicked.connect(self.On_EditProfile)
self.serialThread = StatusCheckThread(self.takelock)
self.config=myconstdef.DEFAULTCONFIG
self._loadConfigFile()
self.updateProfile()
self.imageview.connect(self._ShowpixmapGView)
self.ViewerPreViewMode.connect(self.PreviewMode)
self.ClearImageShow.connect(self._ClearImageShow)
self.ShowRepeatTime.connect(self._ShowRepeatTime)
#self.pbSetting.clicked.connect(self.on_settingclick)
#self.pbKeyBoard.clicked.connect(self.on_KeyBoardclick)
self.cbAutoStart.stateChanged.connect(self.btnstate)
#self.leIMEI.setInputMask('9')
self.leDeviceID.editingFinished.connect(self.on_imei_editfinished)
self.leModel.editingFinished.connect(self.on_model_editfinished)
#self.leProfile.hide()
#self.previewEvent = threading.Event()
self.imageTop.SetCamera(PhotoViewer.CAMERA.TOP)
self.imageLeft.SetCamera(PhotoViewer.CAMERA.LEFT)
self.imageRight.SetCamera(PhotoViewer.CAMERA.RIGHT)
self.startKey =False
#self.clientleft = ServerProxy(myconstdef.URL_LEFT, allow_none=True)
#self.clienttop = ServerProxy(myconstdef.URL_TOP, allow_none=True)
#self.clientright = ServerProxy(myconstdef.URL_RIGHT, allow_none=True)
self.setStyleSheet('''
QPushButton{background-color:rgb(68, 114, 196);
color: white;
border-radius: 5px;}
QPushButton:hover{background-color:white;
color: black;}
QPushButton:pressed{background-color:rgb(85, 170, 255);}
QWidget#Dialog{
background:gray;
border-top:1px solid white;
border-bottom:1px solid white;
border-left:1px solid white;
border-top-left-radius:10px;
border-bottom-left-radius:10px;
}''')
self.serialThread.signal.connect(self.StatusChange)
self.pbAddProfile.clicked.connect(self.On_AddProfile)
self.pbDoneProfile.clicked.connect(self.On_DoneProfile)
self.pbProfileSave.clicked.connect(self.On_SaveProfile)
self.pbProfileNew.clicked.connect(self.On_ProfileNew)
self.leProfileStationID.returnPressed.connect(self.On_ProfileTakePic)
self.leProfileModel.returnPressed.connect(self.On_ProfileTakePic)
#self.listWidget.itemDoubleClicked.connect(self.On_ListWidgetDoubleClick)
######Add ShortCut Begin#########
self.scAdd = QtWidgets.QShortcut(QKeySequence("Ctrl+A"), self)
self.scAdd.activated.connect(self.On_AddProfile)
self.scSave = QtWidgets.QShortcut(QKeySequence("Ctrl+S"), self)
self.scSave.activated.connect(self.On_SaveSetting)
self.scNew = QtWidgets.QShortcut(QKeySequence("Ctrl+N"), self)
self.scNew.activated.connect(self.On_ProfileNew)
self.scResult = QtWidgets.QShortcut(QKeySequence("Ctrl+R"), self)
self.scResult.activated.connect(self.On_ShowDryRunResult)
self.scDelProfile = QtWidgets.QShortcut(QKeySequence("Ctrl+D"), self)
self.scDelProfile.activated.connect(self.On_DeleteProfile)
######Add ShortCut End###########
self.threadPreview = None
self.threadDryrun = None
#self.imageResults=[0]*3
self.profileimages = ["", "", ""]
self.imageresults = [[],[],[]]
self.yanthread = None
self._profilepath = "" #with profile name
self.profilename = ""
self.isProfilestatus = False
self.imeidb = None
self.loadImeidb()
self.serialThread.start()
self.dryrunResult = []
self.ProfileImages =[]
self.previewpixEvent = threading.Event()
def PreviewMode(self, v):
self.imageTop.toggleReviewMode(v)
self.imageLeft.toggleReviewMode(v)
self.imageRight.toggleReviewMode(v)
def _ShowpixmapGView(self, pixmap, v):
self.logger.info("_ShowpixmapGView ++")
if v == PhotoViewer.CAMERA.TOP.value:
if self.previewpixEvent.is_set():
if pixmap.height()==720:
self.previewpixEvent.clear()
return
self.imageTop.ShowPreImage(pixmap)
elif v == PhotoViewer.CAMERA.LEFT.value:
self.imageLeft.ShowPreImage(pixmap)
elif v == PhotoViewer.CAMERA.RIGHT.value:
self.imageRight.ShowPreImage(pixmap)
self.logger.info("_ShowpixmapGView --")
def loadImeidb(self):
if os.path.isfile('imei2model.json'):
with open('imei2model.json') as json_file:
self.imeidb = json.load(json_file)
def ImeiQuery(self, imei):
#"cmc_maker": "Apple",
#"cmc_model": "iPhone3GS",
#"maker": "Apple",
#"model": "iPhone3GS",
if 'doc' in self.imeidb:
for item in self.imeidb['doc']:
if imei.startswith(item['uuid']):
maker = item['maker'] if 'maker' in item else ''
model = item['model'] if 'model' in item else ''
cmc_maker = item['cmc_maker'] if 'cmc_maker' in item else ''
cmc_model = item['cmc_model'] if 'cmc_model' in item else ''
return (maker, model, cmc_maker, cmc_model)
return ('', '', '', '')
def _getProfileName(self):
self.profilename = ''
if self.leModel.text() !="" and self.lblStationID.text() != '':
self.profilename = self.leModel.text() +'_'+self.lblStationID.text()
self.config["phonemodel"] = self.leModel.text()
self._saveConfigFile()
return True
return False
def on_imei_editfinished(self):
return
#if len(self.leIMEI.text())>=8:
# _,model,_,_ = self.ImeiQuery(self.leIMEI.text())
# self.leModel.setText(model)
# self._getProfileName()
def on_model_editfinished(self):
self._getProfileName()
def StatusChange(self, value):
self.takelock.acquire()
print("value is :"+str(value))
if (value == 3):
self.lblStatus.setText("ready")
self.lblStatus.setStyleSheet('''
color: black
''')
elif (value == 2):
if self.isAutoDetect or self.isProfilestatus:
self.OnPreview()
elif(value == 1):
#self.previewEvent.set()
#start process
self._stopPreview()
if self.isAutoDetect:
self.on_startclick()
self.takelock.release()
#@staticmethod
def createKeyboard(self):
#subprocess.Popen(["killall","matchbox-keyboa"])
#self.keyboardID = 0
if self.keyboardID == 0:
p = subprocess.Popen(["matchbox-keyboard", "--xid"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.keyboardID = int(p.stdout.readline())
threading.Thread(target=lambda : print(p.stdout.readline())).start()
self.startKey = True
self.logger.debug("capturing window 0x%x ", self.keyboardID)
embed_window = QtGui.QWindow.fromWinId(self.keyboardID)
embed_widget = QtWidgets.QWidget.createWindowContainer(embed_window)
embed_widget.setMinimumWidth(580)
embed_widget.setMinimumHeight(280)
hbox2 = QHBoxLayout()
hbox2.addWidget(embed_widget)
self.wdtKeyBoard.setLayout(hbox2)
def ShowKeyBoard(self):
try:
if self.startKey:
self.wdtKeyBoard.hide()
self.startKey = False
return
self.createKeyboard()
if self.keyboardID == 0:
return
self.wdtKeyBoard.show()
self.startKey = True
#elf.wdtKeyBoard.resize(580, 280)
except:
pass
def _saveConfigFile(self):
try:
with open('config.json', 'w') as json_file:
json.dump(self.config, json_file, indent=4)
except Exception as e:
print(e)
self.logger.exception(str(e))
def _loadConfigFile(self):
if os.path.isfile('config.json'):
with open('config.json') as json_file:
self.config = json.load(json_file)
myconstdef.screwWidth = self.config['screww'] if 'screww' in self.config else 40
myconstdef.screwHeight = self.config['screwh'] if 'screwh' in self.config else 40
self.isPreview = self.config['preview'] if 'preview' in self.config else True
self.isAutoDetect = self.config["autostart"] if 'autostart' in self.config else True
self.cbAutoStart.setChecked(self.isAutoDetect)
self.pbStart.setEnabled(not self.isAutoDetect)
self.pbFinish.setEnabled(not self.isAutoDetect)
spath = os.path.join(os.path.dirname(os.path.realpath(__file__)),"profiles")
self.sProfilePath = self.config["profilepath"] if 'profilepath' in self.config else spath
self.lblStationID.setText(self.config["stationid"] if 'stationid' in self.config else '1')
self.leStationID.setText(self.lblStationID.text())
self.leModel.setText(self.config["phonemodel"] if 'phonemodel' in self.config else '')
self.serialThread.setThrehold(self.config["threhold"]
if 'threhold' in self.config else 20000)
def createprofiledirstruct(self, profiename):
self.clientA.startCamera(0)
self.clientB.startCamera(1)
#self.clientleft = ServerProxy(myconstdef.URL_LEFT, allow_none=True)
#self.clienttop = ServerProxy(myconstdef.URL_TOP, allow_none=True)
#self.clientright = ServerProxy(myconstdef.URL_RIGHT, allow_none=True)
#self.imageLeft.setServerProxy(self.clientleft)
#self.imageTop.setServerProxy(self.clienttop)
#self.imageRight.setServerProxy(self.clientright)
def closeEvent(self, event):
self._stopPreview()
self._saveConfigFile()
#self._shutdown()
self.clientA.close()
self.clientB.close()
self.serialThread.exit_event.set()
self.close()
def changeStyle(self, styleName):
QApplication.setStyle(QStyleFactory.create(styleName))
QApplication.setPalette(QApplication.style().standardPalette())
def updateProfile(self):
self.createprofiledirstruct("")
def _GetImageShow(self):
self.logger.info("preview: thread starting...")
self.imageTop.setImageScale()
self.imageTop.toggleReviewMode(True)
self.previewpixEvent.set()
self.stop_prv.clear()
#self.clientA.SetPreviewMode(True)
while True:
ret, pixmap =self.clientA.read()
#img = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
#img=cv2.resize(img, (580,720))
#image = Image.fromarray(img)
#imageq = ImageQt(image) #convert PIL image to a PIL.ImageQt object
#pixmap = QPixmap.fromImage(imageq)
#self.imageTop.ShowPreImage(pixmap)
if not ret or pixmap is None or pixmap.isNull():
time.sleep(0.05)
continue
self.imageview.emit(pixmap, PhotoViewer.CAMERA.TOP.value)
if self.stop_prv.is_set():
self.stop_prv.clear()
break
self.stop_prv.clear()
self.previewpixEvent.clear()
self.logger.info("preview: thread ending...")
@pyqtSlot()
def btnstate(self):
if self.sender().isChecked():
self.pbStart.setEnabled(False)
self.pbFinish.setEnabled(False)
self.isAutoDetect = True
self.config["autostart"] = True
else:
self.pbStart.setEnabled(True)
self.pbFinish.setEnabled(True)
self.isAutoDetect = False
self.config["autostart"] = False
@pyqtSlot()
def On_ExitSettingMode(self):
self.tabSetting.setCurrentIndex(0)
self.tabAllSetting.setCurrentIndex(0)
#self.imageTop.fitInView()
self.imageTop.toggleReviewMode(True)
#self.imageLeft.fitInView()
self.imageLeft.toggleReviewMode(True)
#self.imageRight.fitInView()
self.imageRight.toggleReviewMode(True)
self.isAutoDetect = self.config["autostart"]
self.isProfilestatus = False
if not self.isAutoDetect:
self.pbStart.setEnabled(True)
self.pbFinish.setEnabled(True)
@pyqtSlot()
def On_ShowSetting(self):
os.system(myconstdef.LOCALCMD)
dlg = LoginDialog(self)
if not dlg.exec_():
return
self.isAutoDetect = False
self.tabSetting.setCurrentIndex(1)
self.pbtabDryrun.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);''')
self.pbtabSetting.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 255, 0);''')
self.pbtabProfile.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);''')
self.leStationID.setText(self.config["stationid"] if 'stationid' in self.config else '1')
self.isProfilestatus = True
self._saveConfigFile()
@pyqtSlot()
def On_SaveSetting(self):
self.config['stationid'] = self.leStationID.text()
self._saveConfigFile()
self.lblStationID.setText(self.leStationID.text())
@pyqtSlot()
def On_DryRun(self):
sender = self.sender()
clickevent = sender.text()
if clickevent == u'Start':
if self.threadDryrun==None or not self.threadDryrun.is_alive():
self.threadDryrun= threading.Thread(target=self.__jason)
self.threadDryrun.start()
elif clickevent == u'Stop':
self.stop_DryRun.set()
@pyqtSlot()
def On_ListWidgetDoubleClick(self, item):
proname = item.text()
pathleft = os.path.join(self.sProfilePath, proname, "left")
pathtop = os.path.join(self.sProfilePath, proname, "top")
pathright = os.path.join(self.sProfilePath, proname, "right")
self.profileimages[PhotoViewer.CAMERA.TOP.value]=os.path.join(pathtop, proname+".jpg")
self.profileimages[PhotoViewer.CAMERA.LEFT.value]=os.path.join(pathleft, proname+".jpg")
self.profileimages[PhotoViewer.CAMERA.RIGHT.value]=os.path.join(pathright, proname+".jpg")
self._stopPreview()
self.profilename = proname
self._loadProfile()
bbb = proname.split('_' )
self.leModel.setText('_'.join(bbb[:-1]))
self.config['stationid'] = bbb[-1]
self.lblStationID.setText(bbb[-1])
self._saveConfigFile()
self.On_ExitSettingMode()
def _stopPreview(self):
if self.threadPreview is not None and self.threadPreview.is_alive():
self.stop_prv.set()
while self.threadPreview is not None and self.threadPreview.is_alive():
time.sleep(0.1)
@pyqtSlot()
def On_EditProfile(self):
curIndex = self.listWidget.currentRow()
if curIndex < 0:
QMessageBox.question(self, 'Error', "Oh no! Select Profile please.", QMessageBox.No, QMessageBox.No)
return
proname = self.listWidget.currentItem().text()
self._stopPreview()
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
pathleft = os.path.join(self.sProfilePath, proname, "left")
pathtop = os.path.join(self.sProfilePath, proname, "top")
pathright = os.path.join(self.sProfilePath, proname, "right")
self.profileimages[PhotoViewer.CAMERA.TOP.value]=os.path.join(pathtop, proname+".jpg")
self.profileimages[PhotoViewer.CAMERA.LEFT.value]=os.path.join(pathleft, proname+".jpg")
self.profileimages[PhotoViewer.CAMERA.RIGHT.value]=os.path.join(pathright, proname+".jpg")
self.profilename = proname
self._loadProfile()
#do edit
finally:
QApplication.restoreOverrideCursor()
@pyqtSlot()
def On_DeleteProfile(self):
if self.listWidget.currentRow()>=0:
proname = self.listWidget.currentItem().text()
self.logger.info("delete:"+proname)
dirPath=os.path.join(self.sProfilePath, proname)
try:
shutil.rmtree(dirPath)
except Exception as e:
print(e)
self.logger.exception(str(e))
self.logger.error('Error while deleting directory')
self.listWidget.takeItem(self.listWidget.currentRow())
@pyqtSlot()
def On_ShowProfile(self):
curIndex = self.listWidget.currentRow()
if curIndex < 0:
QMessageBox.question(self, 'Error', "Oh no! Select Profile please.", QMessageBox.No, QMessageBox.No)
return
proname = self.listWidget.currentItem().text()
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
pathleft = os.path.join(self.sProfilePath, proname, "left")
pathtop = os.path.join(self.sProfilePath, proname, "top")
pathright = os.path.join(self.sProfilePath, proname, "right")
self.profileimages[PhotoViewer.CAMERA.TOP.value]=os.path.join(pathtop, proname+".jpg")
self.profileimages[PhotoViewer.CAMERA.LEFT.value]=os.path.join(pathleft, proname+".jpg")
self.profileimages[PhotoViewer.CAMERA.RIGHT.value]=os.path.join(pathright, proname+".jpg")
self._stopPreview()
self.profilename = proname
self.isProfilestatus = False
self._loadProfile()
bbb = proname.split('_' )
self.leModel.setText('_'.join(bbb[:-1]))
self.config['stationid'] = bbb[-1]
self.lblStationID.setText(bbb[-1])
self._saveConfigFile()
self.On_ExitSettingMode()
finally:
QApplication.restoreOverrideCursor()
@pyqtSlot()
def On_settingChange(self):
if self.threadDryrun is not None and self.threadDryrun.is_alive():
return
self.pbtabDryrun.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);''')
self.pbtabSetting.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);''')
self.pbtabProfile.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 0, 0);''')
sender = self.sender()
clickevent = sender.text()
if clickevent == u'Setting':
self.tabAllSetting.setCurrentIndex(0)
self.pbtabSetting.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 255, 0);''')
elif clickevent == u'Profile':
self.tabAllSetting.setCurrentIndex(1)
self.listWidget.clear()
self.pbtabProfile.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 255, 0);''')
self.listWidget.addItems([name for name in os.listdir(self.sProfilePath) if os.path.isdir(os.path.join(self.sProfilePath, name))])
#for name in os.listdir(self.sProfilePath):
# if os.path.isdir(os.path.join(self.sProfilePath, name)):
# self.listWidget.addItem(name)
else:
self.pbtabDryrun.setStyleSheet('''background-color: rgb(255, 255, 255);color: rgb(0, 255, 0);''')
self.tabAllSetting.setCurrentIndex(2)
self.sbRepeatTime.setValue(self.config['repeattime'] if 'repeattime' in self.config else 100)
@pyqtSlot()
def on_CameraChange(self):
sender = self.sender()
clickevent = sender.text()
if clickevent == u'TOP':
self.tabImages.setCurrentIndex(0)
elif clickevent == u'LEFT':
self.tabImages.setCurrentIndex(1)
else:
self.tabImages.setCurrentIndex(2)
@pyqtSlot()
def on_KeyBoardclick(self):
self.ShowKeyBoard()
def __jason(self):
self.isAutoDetect = False
self.config['repeattime'] = self.sbRepeatTime.value()
self.stop_DryRun.clear()
irepeat = self.sbRepeatTime.value()
self.isProfilestatus = False
self.dryrunResult = []
while not self.stop_DryRun.is_set() and irepeat>0:
self.logger.info("auto dry run Left %d" % irepeat)
self.on_startclick()
irepeat -= 1
#self.sbRepeatTime.setValue(irepeat)
self.ShowRepeatTime.emit(irepeat)
time.sleep(2)
self.isProfilestatus = True
@pyqtSlot()
def on_startPreview(self):
if not self.isProfilestatus:
self.OnPreview()
def _DirSub(self, argument):
switcher = {
1: "left",
0: "top",
2: "right",
}
return switcher.get(argument, "Invalid")
def runsyncprofiles(self, isLeft):
ip = myconstdef.IP_LEFT
#cmd = 'rsync -avz -e ssh pi@{0}:{1}/ {2}/'.format(ip, '/home/pi/Desktop/pyUI/profiles',self.config["profilepath"])
#os.system(cmd)
def capture(self, cam, IsDetect=True):
if cam == PhotoViewer.CAMERA.RIGHT.value:
urllib.request.urlretrieve(myconstdef.URL_RIGHT, '/tmp/ramdisk/phoneimage_%d.jpg' % cam)
else:
client = self.clientA if cam==0 else self.clientB
#_ , data=client.read()
#img = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
#image = Image.fromarray(img)
#image.save("/tmp/ramdisk/phoneimage_%d.jpg" % cam)
time.sleep(0.1)
client.takepic.set()
i = 0
while client.takepic.is_set():
time.sleep(0.05)
i+=1
if i > 30:
self.logger.info('camera thread has some problem.')
break
if not IsDetect:
shutil.copyfile("/tmp/ramdisk/phoneimage_%d.jpg" % cam, os.path.join(self._profilepath, self._DirSub(cam), self.profilename+".jpg"))
else:
self._callyanfunction(cam)
def _callyanfunction(self, index):
self.logger.info('callyanfunction:' + self.profilename)
txtfilename=os.path.join(self._profilepath, self._DirSub(index), self.profilename+".txt")
smplfilename=os.path.join(self._profilepath, self._DirSub(index), self.profilename+".jpg")
self.logger.info(txtfilename)
self.logger.info(smplfilename)
self.imageresults[index] = []
if os.path.exists(txtfilename) and os.path.exists(smplfilename):
self.logger.info("*testScrews**")
try:
self.imageresults[index] = testScrew.testScrews(
txtfilename,
smplfilename,
"/tmp/ramdisk/phoneimage_%d.jpg" % index)
except :
self.imageresults[index] = []
pass
self.logger.info("-testScrews end--"+str(index))
self.logger.info(self.imageresults[index])
def _showImage(self, index, imagelabel):
imagelabel.setImageScale()
self.logger.info("Start testing %d" % index)
self.capture(index, not self.isProfilestatus)
self.logger.info("Start transfer %d" % index)
imagelabel.SetProfile(self.profilename, self.profilename+".jpg")
if self.isProfilestatus:
self.imageview.emit(QPixmap("/tmp/ramdisk/phoneimage_%d.jpg" % index), index)
def _drawtestScrew(self, index, imagelabel):
ret=0
ret = imagelabel.DrawImageResults(self.imageresults[index])
return ret
def _ThreadTakepictureLeft(self):
try:
self._showImage(PhotoViewer.CAMERA.LEFT.value, self.imageLeft)
except Exception as ex:
self.logger.exception(str(ex))
self.logger.info("ending camera Left and transfer")
def _ThreadTakepictureRight(self):
try:
self._showImage(PhotoViewer.CAMERA.RIGHT.value, self.imageRight)
except Exception as ex:
self.logger.exception(str(ex))
self.logger.info("ending camera right and transfer")
def _ThreadTakepicture(self):
self.takepic.clear()
try:
self._showImage(PhotoViewer.CAMERA.TOP.value, self.imageTop)
except Exception as ex:
self.logger.exception(str(ex))
self.logger.info("ending camera A and transfer")
def DrawResultTop(self):
self.ClearImageShow.emit(0x1)
self.imageTop.imagedresult = 0
self.imageTop.DrawImageResults(self.imageresults[PhotoViewer.CAMERA.TOP.value],
self.ProfileImages[PhotoViewer.CAMERA.TOP.value].copy(self.ProfileImages[PhotoViewer.CAMERA.TOP.value].rect()))
def DrawResultLeft(self):
#self.lblImageLeft.clear()
self.ClearImageShow.emit(0x2)
self.imageLeft.imagedresult = 0
self.imageLeft.DrawImageResults(self.imageresults[PhotoViewer.CAMERA.LEFT.value],
self.ProfileImages[PhotoViewer.CAMERA.LEFT.value].copy(self.ProfileImages[PhotoViewer.CAMERA.LEFT.value].rect()))
def DrawResultRight(self):
#self.lblImageRight.clear()
self.ClearImageShow.emit(0x4)
self.imageRight.imagedresult = 0
self.imageRight.DrawImageResults(self.imageresults[PhotoViewer.CAMERA.RIGHT.value],
self.ProfileImages[PhotoViewer.CAMERA.RIGHT.value].copy(self.ProfileImages[PhotoViewer.CAMERA.RIGHT.value].rect()))
def _loadProfile(self):
self.imageTop.DrawProfile(self.profilename)
self.imageLeft.DrawProfile(self.profilename)
self.imageRight.DrawProfile(self.profilename)
def _ClearImageShow(self, index):
if index & 0x1 == 0x1:
self.imageTop.clear()
if index & 0x2 == 0x2:
self.imageLeft.clear()
if index & 0x4 == 0x4:
self.imageRight.clear()
def _ShowRepeatTime(self, repeat):
self.sbRepeatTime.setValue(repeat)
@pyqtSlot()
def On_ShowDryRunResult(self):
dlg = dlgResult.ResultDialog(self.dryrunResult, self)
dlg.exec_()
@pyqtSlot()
def on_startclick(self):
os.system(myconstdef.LOCALCMD)
if self.isProfilestatus:
return
self._getProfileName()
if self.profilename=="":
QMessageBox.question(self, 'Error', "Oh no! Profile name is empty.", QMessageBox.Cancel, QMessageBox.Cancel)
return
#self.ClearImageShow.emit(0xf)
pathleft = os.path.join(self.sProfilePath, self.profilename, "left")
pathtop = os.path.join(self.sProfilePath, self.profilename, "top")
pathright = os.path.join(self.sProfilePath, self.profilename, "right")
self.profileimages[PhotoViewer.CAMERA.TOP.value]=os.path.join(pathtop, self.profilename+".jpg")
self.profileimages[PhotoViewer.CAMERA.LEFT.value]=os.path.join(pathleft, self.profilename+".jpg")
self.profileimages[PhotoViewer.CAMERA.RIGHT.value]=os.path.join(pathright, self.profilename+".jpg")
if len(self.ProfileImages) == 0:
self.ProfileImages.append(QPixmap(self.profileimages[PhotoViewer.CAMERA.TOP.value]).scaledToHeight(820))
self.ProfileImages.append(QPixmap(self.profileimages[PhotoViewer.CAMERA.LEFT.value]).scaledToHeight(820))
self.ProfileImages.append(QPixmap(self.profileimages[PhotoViewer.CAMERA.RIGHT.value]).scaledToHeight(820))
self.ProfileImages.append(self.profilename)
elif self.ProfileImages[3]!=self.profilename:
self.ProfileImages[PhotoViewer.CAMERA.TOP.value]= QPixmap(self.profileimages[PhotoViewer.CAMERA.TOP.value]).scaledToHeight(820)
self.ProfileImages[PhotoViewer.CAMERA.LEFT.value]= QPixmap(self.profileimages[PhotoViewer.CAMERA.LEFT.value]).scaledToHeight(820)
self.ProfileImages[PhotoViewer.CAMERA.RIGHT.value]= QPixmap(self.profileimages[PhotoViewer.CAMERA.RIGHT.value]).scaledToHeight(820)
self.ProfileImages[3] = self.profilename
self._stopPreview()
self._profilepath = os.path.join(self.sProfilePath, self.profilename)
if not self.isProfilestatus and not os.path.exists(self._profilepath):
QMessageBox.question(self, 'Error', "Oh no! Create profile please.", QMessageBox.Cancel, QMessageBox.Cancel)
return
if self.startKey:
self.ShowKeyBoard()
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
#try:
# self.clienttop.profilepath(self.sProfilePath, self.profilename)
#except:
# pass
self.logger.info("Start testing click")
self.logger.info("Start testing top")
p = threading.Thread(target=self._ThreadTakepicture)
p.start()
pLeft = threading.Thread(target=self._ThreadTakepictureLeft)
pLeft.start()
pRight = threading.Thread(target=self._ThreadTakepictureRight)
pRight.start()
p.join()
self.logger.info("Start end top")
pLeft.join()
self.logger.info("Start end left")
pRight.join()
self.logger.info("Start end right")
#if not self.isProfilestatus:
status, status1, status2 = 0, 0, 0
#self.takepic.wait()
#self.takepic.clear()
try:
self.logger.info("Start Draw Thread Info")
#threads=[]
ttop = threading.Thread(target=self.DrawResultTop)
ttop.start()
#threads.append(ttop)
tleft = threading.Thread(target=self.DrawResultLeft)
tleft.start()
#threads.append(tleft)
tright = threading.Thread(target=self.DrawResultRight)
tright.start()
#threads.append(tright)
self.logger.info("Draw Thread started")
ttop.join()
self.logger.info("Draw top finish")
tleft.join()
self.logger.info("Draw left finish")
tright.join()
self.logger.info("Draw right finish")
#for t in threads:
# t.join()
status = self.imageTop.imagedresult
status1 = self.imageLeft.imagedresult
status2 = self.imageRight.imagedresult
self.logger.info("End Draw Info:%d:%d:%d"%(status, status1, status2))
except :
status = 5
self.dryrunResult.append([status, status1, status2])
status = max([status, status1, status2])
if status==0:
self.lblStatus.setText("")
self.lblStatus.setStyleSheet('''
border-image: url(:/icons/yes.png);
''')
elif status==1:
self.lblStatus.setText("")
self.lblStatus.setStyleSheet('''
border-image: url(:/icons/warning.png);
''')
else:
self.lblStatus.setText("")
self.lblStatus.setStyleSheet('''
border-image: url(:/icons/no.png);
''')
self.logger.info("task finished")
except Exception as e:
self.logger.exception(str(e))
finally:
QApplication.restoreOverrideCursor()
def ChangeTab(self):
time.sleep(0.1)
window.tabImages.setCurrentIndex(0)
time.sleep(0.1)
window.tabImages.setCurrentIndex(1)
time.sleep(0.1)
window.tabImages.setCurrentIndex(2)
time.sleep(0.1)
self.logger.info(str(self.lblStatus.width())+"X"+str(self.lblStatus.height()))
self.lblStatus.setFixedSize(self.lblStatus.width(),self.lblStatus.width())
self.logger.info("Status Size:"+str(self.lblStatus.width())+"X"+str(self.lblStatus.height()))
window.tabImages.setCurrentIndex(0)
self.serialThread.start()
self.imageTop.setImageScale()
self.imageLeft.setImageScale()
self.imageRight.setImageScale()
for a in range(0, 5):
os.system(myconstdef.LOCALCMD)
self.logger.info("config ip")
time.sleep(2)
def OnPreview(self):
allowpreview = self.config["preview"] if 'preview' in self.config else True
if not allowpreview:
return
if self.threadPreview==None or not self.threadPreview.is_alive():
self.threadPreview= threading.Thread(target=self._GetImageShow)#self.PreviewCamera)
self.threadPreview.start()
def On_DoneProfile(self):
if self.imageTop.needSaveProfile() or self.imageLeft.needSaveProfile() or self.imageRight.needSaveProfile():
reply = QMessageBox.question(self, 'Info', "Do you want to save Profile?", QMessageBox.Cancel | QMessageBox.Yes, QMessageBox.Cancel)
if reply == QMessageBox.Yes:
self.On_SaveProfile()
self.tabAllSetting.setCurrentIndex(1)
def On_AddProfile(self):
if self.tabImages.currentIndex() == PhotoViewer.CAMERA.TOP.value:
self.imageTop.AddProfilePoint()
elif self.tabImages.currentIndex() == PhotoViewer.CAMERA.LEFT.value:
self.imageLeft.AddProfilePoint()
elif self.tabImages.currentIndex() == PhotoViewer.CAMERA.RIGHT.value:
self.imageRight.AddProfilePoint()
def On_SaveProfile(self):
self.logger.info("On_SaveProfile ++ ")
self.imageTop.SaveProfile()
self.imageLeft.SaveProfile()
self.imageRight.SaveProfile()