-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
1149 lines (977 loc) · 42.5 KB
/
test.py
File metadata and controls
1149 lines (977 loc) · 42.5 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
from operator import index
import sys
import random
from matplotlib import pyplot as plt
import psutil
import json
import argparse
import time
import threading
from datetime import datetime, timedelta
from Layouts import MyWindow
from MockPLCServer.mock_plc import pycomm3
from fault_delay_layout import CurrentFaultDelay
from PyQt5.QtCore import Qt, QTimer, QTime, QDateTime, QStringListModel
from PyQt5.QtGui import QColor, QFont, QIcon, QPainter, QPen, QBrush, QPixmap, QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QLabel, QVBoxLayout, QHBoxLayout, QGridLayout,
QTextEdit, QFrame, QPushButton, QSizePolicy, QMenu, QAction, QWidget,
QTableView, QLineEdit, QListView, QProgressDialog, QTimeEdit, QMessageBox, QSpacerItem, QDialog, QDesktopWidget
)
from dashboard_parameter_manager import ParameterManagerWindow
from TagManager import TagManagerWindow
from Dialog import *
from OEE_config_dialog import ConfigDialog
import os
import pandas as pd
import my_plc
from Graph import GraphPlotter
from summary_card import SummaryCard
from PyQt5.QtCore import QThread, pyqtSignal
from oee_calculator import OEECalculator
from oee_dashboard_test import OEEDashboard
qss = """
QMenuBar {
background-color: #C6E5F5; /* Dark blue-gray */
font-weight: bold;
color: #002A4D;
}
QMenuBar::item {
spacing: 3px;
padding: 4px 12px;
background-color: #C6E5F5; /* Slightly lighter */
}
QMenuBar::item:selected {
background-color: #AAD8F0; /* Hover color */
}
QMenuBar::item:pressed {
background-color: #AAD8F0; /* Clicked color */
}
QMenu {
background-color: #C6E5F5; /* Dropdown background */
}
QMenu::item {
padding: 5px 20px;
background-color: transparent;
}
QMenu::item:selected {
background-color: #6ABBE5;
color: black;
}
"""
class WorkerThread(QThread):
finished = pyqtSignal()
def run(self):
try:
print("trying to connect")
plc = my_plc.Plc('192.168.0.10')
tags_data = plc.read_cycletime_tags()
dw = my_plc.data_writer()
dw.write_to_excel(tags_data,dw.CYCLETIME_BACKUP_DIR)
except Exception as e:
print("Exception occured in Worker Thread:\n" + str(e))
self.finished.emit()
class CustomTimeEdit(QTimeEdit):
def keyPressEvent(self, event):
if event.key() in (Qt.Key_Backspace, Qt.Key_Delete):
# Ignore Backspace and Delete
print("Blocked key:", event.key())
return
super().keyPressEvent(event)
class BackupTimeDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.setWindowTitle("Saved Backup Time")
self.setWindowIcon(QIcon("icon.png"))
self.setModal(True)
layout = QVBoxLayout(self)
backup_time = os.getenv("PRODUCTION_BACKUP_TIME")
if backup_time:
time_text = f"{backup_time}"
else:
time_text = "No Backup time is set.\nNo data will be backed up automatically."
label = QLabel(time_text)
label.setFont(QFont("Segoe UI", 14, QFont.Bold))
label.setAlignment(Qt.AlignCenter)
layout.addWidget(label)
# Apply theme stylesheet
self.setStyleSheet(self._get_stylesheet())
def _get_stylesheet(self):
if self.parent and hasattr(self.parent, 'dark_mode') and self.parent.dark_mode:
return """
QWidget {
background-color: #34495e;
color: #ecf0f1;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
QLabel {
color: #ecf0f1;
}
"""
else:
return """
QWidget {
background-color: #FFFFFF;
color: #002A4D;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
QLabel {
color: #002A4D;
}
"""
class Dashboard(QMainWindow):
def __init__(self,which_plc):
super().__init__()
self.ui_activated_once = False
if which_plc == "plc":
self.real_plc_init()
elif which_plc == "no-plc":
self.mock_plc_init()
self.currentfile_path= ""
self.initialise_dashboard()
def initialise_dashboard(self):
self.setWindowTitle("Automated Production Analyser")
self.setWindowIcon(QIcon.fromTheme("applications-system"))
self.dark_mode = True
self.setStyleSheet(self._get_stylesheet())
self.menu_bar = self.menuBar()
self.active_dashboard = True
self.setWindowTitle("Production Analyser")
self.setWindowIcon(QIcon("icon.png"))
self.cycle_time = 0
self.file_path = "production.xlsx"
self.Dialog = Dialog()
self.dlg = BackupTimeDialog(self)
self.edit_cyctime_win = TagManagerWindow(json_path="plc_custom_user_tags\\cycle_time_tags.json")
self.edit_fault_delay_win = TagManagerWindow(json_path="plc_custom_user_tags\\fault_delay_tags.json")
self.edit_station_fault_win = TagManagerWindow(json_path="plc_custom_user_tags\\station_fault_tags.json")
self.edit_tip_dress_win = TagManagerWindow(json_path="plc_custom_user_tags\\tip_dress_tags.json")
self.edit_tip_change_win = TagManagerWindow(json_path="plc_custom_user_tags\\tip_dress_tags.json")
self.edit_dashboard_win = ParameterManagerWindow(json_path="plc_custom_user_tags\\dashboard_tags.json")
# Initialize OEE Calculator
self.oee_calc = OEECalculator()
self.ideal_cycle_time = float(self.oee_calc.config.get("ideal_cycle_time", 1.0))
self.label = QLabel()
self.last_backup_time = os.getenv("LAST_BACKUP_TIME")
self.plc_connected = False
# Store original window size for scaling
self.original_size = (850, 520)
self.original_fonts = {
'heading': 24,
'time': 22,
'backup': 14,
'plc': 14,
'log_title': 18,
'param_title': 12,
'param_value': 22,
'button': 10
}
self._init_ui()
self._init_timers()
self.param_thread = threading.Thread(target=self._update_parameters,daemon=True)
self.param_thread.start()
self._log("Dashboard initialized.")
def real_plc_init(self):
self.plc = my_plc.Plc('192.168.0.10')
def mock_plc_init(self):
self.plc = pycomm3()
def _init_ui(self):
try:
self.central_widget.destroy()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
except Exception as e:
pass
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
main_layout = QVBoxLayout(self.central_widget)
main_layout.setContentsMargins(10, 10, 10, 10)
main_layout.setSpacing(10)
if self.ui_activated_once == False:
self._create_menu_bar()
self.ui_activated_once = True
# Get screen resolution
screen = QDesktopWidget().screenGeometry()
screen_width = screen.width()
screen_height = screen.height()
# Set window size as a percentage of screen resolution
window_width = int(screen_width * 0.6) # 60% of screen width
window_height = int(screen_height * 0.6) # 60% of screen height
# Resize and center the window
self.resize(window_width, window_height)
self.center()
# Top header with logo and heading
header_frame = QFrame()
header_frame.setFrameShape(QFrame.StyledPanel)
header_layout = QHBoxLayout()
header_layout.setSpacing(5)
header_layout.setAlignment(Qt.AlignLeft)
# Logo
logo_label = QLabel()
pixmap = QPixmap("logo.PNG")
logo_label.setPixmap(pixmap.scaled(48, 48, Qt.KeepAspectRatio))
header_layout.addWidget(logo_label)
# Right side: main heading and subheading
right_layout = QVBoxLayout()
right_layout.setSpacing(2)
# Main heading
heading = QLabel("Production Analyser")
heading.setFont(QFont("Segoe UI", 20, QFont.Bold))
heading.setAlignment(Qt.AlignLeft)
right_layout.addWidget(heading)
# Subheading
subheading = QLabel("Dashboard - Monitoring Parameters in Real-Time")
subheading.setFont(QFont("Segoe UI", 10,QFont.Bold))
subheading.setAlignment(Qt.AlignLeft)
right_layout.addWidget(subheading)
header_layout.addLayout(right_layout)
header_frame.setLayout(header_layout)
main_layout.addWidget(header_frame)
# Top info panel
info_panel = QHBoxLayout()
info_panel.setSpacing(15)
# O.E.E (%)
self.oee_label = QLabel("0.0")
self.oee_label.setFont(QFont("Segoe UI", 15))
self.oee_label.setAlignment(Qt.AlignCenter)
self.oee_label.setFixedWidth(220)
oee_box = QFrame()
oee_box.setFrameShape(QFrame.StyledPanel)
oee_layout = QVBoxLayout()
oee_title = QLabel("O.E.E (%)")
oee_title.setFont(QFont("Segoe UI", 10, QFont.Bold))
oee_title.setAlignment(Qt.AlignCenter)
oee_layout.addWidget(oee_title)
oee_layout.addWidget(self.oee_label)
self.more_info_btn = QPushButton("Show More Info")
self.more_info_btn.setFont(QFont("Segoe UI", 10))
self.more_info_btn.clicked.connect(self.show_more_info)
oee_layout.addWidget(self.more_info_btn)
oee_box.setLayout(oee_layout)
oee_box.setFixedWidth(250)
info_panel.addWidget(oee_box)
# Current Time
self.time_label = QLabel()
self.time_label.setFont(QFont("Segoe UI", 15, QFont.Bold))
self.time_label.setAlignment(Qt.AlignCenter)
self.time_label.setFixedWidth(220)
time_box = self._create_info_box("Current Time", self.time_label)
time_box.setFixedWidth(250)
info_panel.addWidget(time_box)
# Last Backup Time
self.backup_label = QLabel()
self.backup_label.setFont(QFont("Segoe UI", 15, QFont.Bold))
self.backup_label.setAlignment(Qt.AlignCenter)
self.backup_label.setFixedWidth(220)
backup_box = self._create_info_box("Last Backup", self.backup_label)
backup_box.setFixedWidth(250)
info_panel.addWidget(backup_box)
# PLC Connection Status
plc_status_layout = QHBoxLayout()
plc_status_layout.setAlignment(Qt.AlignCenter)
self.plc_status_label = QLabel("Disconnected")
self.plc_status_label.setFont(QFont("Segoe UI", 14))
self.plc_status_label.setStyleSheet("color: white; background-color: #FF0000; border-radius: 0px; padding: 4px 8px;")
plc_status_layout.addWidget(self.plc_status_label)
plc_status_widget = QWidget()
plc_status_widget.setLayout(plc_status_layout)
info_panel.addWidget(self._create_info_box("PLC Connection", plc_status_widget))
# Light/Dark Mode Toggle Button moved to log section
main_layout.addLayout(info_panel)
# Bottom layout: Four parameter frames + Log window
bottom_layout = QVBoxLayout()
bottom_layout.setSpacing(15)
# Four parameter frames
params_widget = QWidget()
params_layout = QGridLayout()
params_layout.setSpacing(15)
# Create parameter frames
self.param_labels = {}
# Load parameters from JSON
data = {}
self.create_default_config_if_missing("plc_custom_user_tags\\dashboard_tags.json")
with open('plc_custom_user_tags\\dashboard_tags.json', 'r') as f:
data = json.load(f)
param_names = [p['name'] for p in data.get('parameters', [])]
for i, name in enumerate(param_names):
label_value = QLabel("0")
label_value.setFont(QFont("Segoe UI", 22, QFont.Bold))
label_value.setAlignment(Qt.AlignCenter)
label_value.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
frame = self._create_info_box(name, label_value)
# frame.setMinimumSize(180, 110)
params_layout.addWidget(frame, i // 4, i % 4)
self.param_labels[name] = label_value
params_widget.setLayout(params_layout)
bottom_layout.addWidget(params_widget)
# Log window
log_widget = QWidget()
log_layout = QVBoxLayout()
log_layout.setContentsMargins(0, 0, 0, 0)
log_layout.setSpacing(0)
log_title = QLabel("Events")
log_title.setFont(QFont("Segoe UI", 12, QFont.Bold))
log_title.setAlignment(Qt.AlignLeft)
log_title.setStyleSheet("padding-bottom: 5px;border-radius: 0px;")
log_layout.addWidget(log_title)
self.log_text = QTextEdit()
self.log_text.setFont(QFont("Consolas", 11))
self.log_text.setStyleSheet("border-radius: 0px; padding: 2px;")
self.log_text.setReadOnly(True)
log_layout.addWidget(self.log_text)
# Buttons layout
buttons_layout = QHBoxLayout()
buttons_layout.setSpacing(5)
# Add a clear log button
clear_log_btn = QPushButton("Clear Log")
clear_log_btn.setFixedWidth(100)
clear_log_btn.setFont(QFont("Segoe UI", 10, QFont.Bold))
clear_log_btn.clicked.connect(self.log_text.clear)
buttons_layout.addWidget(clear_log_btn)
# Light/Dark Mode Toggle Button moved here for smoother functioning
self.mode_toggle_btn = QPushButton("Switch to Light Mode")
self.mode_toggle_btn.setFixedSize(180, 36)
self.mode_toggle_btn.setFont(QFont("Segoe UI", 10, QFont.Bold))
self.mode_toggle_btn.clicked.connect(self._toggle_mode)
buttons_layout.addWidget(self.mode_toggle_btn)
buttons_widget = QWidget()
buttons_widget.setLayout(buttons_layout)
log_layout.addWidget(buttons_widget, alignment=Qt.AlignRight)
log_widget.setLayout(log_layout)
bottom_layout.addWidget(log_widget)
main_layout.addLayout(bottom_layout)
def center(self):
# Center the window on the screen
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def _init_timers(self):
# Update current time every second
self.timer = QTimer()
self.timer.timeout.connect(self._update_time)
self.timer.start(1000)
self._update_time()
# self._update_plc_status()
def _update_time(self):
now = QTime.currentTime()
self.time_label.setText(now.toString("hh:mm:ss AP"))
# Log every minute
if now.second() == 0:
self._log(f"Time updated: {now.toString('hh:mm:ss AP')}")
def _update_backup_time(self):
try:
self.backup_label.setText(f"{self.last_backup_time}")
except Exception as e:
pass
def _update_plc_status(self):
try:
self.plc_connected = not self.plc_connected
if self.plc_connected:
self.plc_status_label.setText("Connected")
self.plc_status_label.setStyleSheet("color: white; background-color: #008000; border-radius: 0px; padding: 4px 8px;")
self._log("PLC connected.")
else:
self.plc_status_label.setText("Disconnected")
self.plc_status_label.setStyleSheet("color: white; background-color: #FF0000; border-radius: 0px; padding: 4px 8px;")
self._log("PLC disconnected.")
except Exception as e:
pass
def _update_parameters(self):
while True:
self._update_backup_time()
plc_res = self.plc.read_dashboard_tags()
# Update parameter values from JSON or simulate if no value provided
with open('plc_custom_user_tags\\dashboard_tags.json', 'r') as f:
data = json.load(f)
parameters = data.get('parameters', [])
for param in parameters:
name = param.get('name')
if name in self.param_labels:
self.param_labels[name].setText(str(plc_res[name]))
# Compute OEE in real-time
try:
total_pieces, downtime = self.oee_calc.read_plc_tags()
self.current_total_pieces = total_pieces
self.current_downtime = downtime
now = datetime.now()
shift_start, shift_end = self.oee_calc.get_current_shift(now)
if shift_start and shift_end:
oee_result = self.oee_calc.compute_realtime_oee(shift_start, shift_end, now, total_pieces, total_pieces, downtime, self.ideal_cycle_time)
self.latest_oee = oee_result
print(f"Realtime OEE result: {oee_result}")
else:
print("No active shift.")
except Exception as e:
print(f"Error: {e}")
try:
oee = self.latest_oee.get('oee', 0.0)
self.oee_label.setText(f"{oee:.1f}")
self._log(f"Parameters updated from config.json, O.E.E={oee:.1f}%")
except Exception as e:
pass
time.sleep(90)
def create_default_config_if_missing(self,json_path):
if not os.path.exists(json_path):
default_data = {
"parameters": [
{"name": "param1", "value": "value1"},
{"name": "param2", "value": "value2"},
{"name": "param3", "value": "value3"}
]
}
os.makedirs(os.path.dirname(json_path) or '.', exist_ok=True)
with open(json_path, "w", encoding="utf-8") as f:
json.dump(default_data, f, indent=4, ensure_ascii=False)
def _log(self, message):
timestamp = datetime.now().strftime("%H:%M:%S")
self.log_text.append(f"[{timestamp}] {message}")
def _create_info_box(self, title, widget):
box = QFrame()
box.setFrameShape(QFrame.StyledPanel)
layout = QVBoxLayout()
label = QLabel(title)
label.setFont(QFont("Segoe UI", 10, QFont.Bold))
label.setAlignment(Qt.AlignCenter)
layout.addWidget(label)
layout.addWidget(widget)
box.setLayout(layout)
return box
def _create_menu_bar(self):
self.menu_bar.setStyleSheet(qss)
# Menu bar
cycle_menu = self.menu_bar.addMenu("Cycle Time")
fault_menu = self.menu_bar.addMenu("Fault Delay")
tip_dress_menu = self.menu_bar.addMenu("Tip Dress")
edit_tag_menu = self.menu_bar.addMenu("Edit Tag")
setting_menu = self.menu_bar.addMenu("Setting")
#menu bar actions
self.view_cycle_action = QAction("Veiw Backup Data", self)
self.view_current_cycle_action = QAction("Veiw Current Data", self)
self.view_current_fault_action = QAction("View Fault Delay (Current)", self)
self.view_backup_fault_action = QAction("View Fault Delay (Backup)", self)
self.tip_dressing_action = QAction("Tip Dress Data",self) # show tip dressing data
self.tip_change_action = QAction("Tip Change Data",self)
self.edit_stationfault_tag_action = QAction("Station Fault Tag",self)
self.edit_faultdelay_tag_action = QAction("Fault Delay Tag",self)
self.edit_cycletime_tag_action = QAction("Cycle time Tag",self)
self.edit_tipdress_tag_action = QAction("Tip Dress Tag",self)
self.edit_tipchange_tag_action = QAction("Tip Change Tag",self)
self.edit_dashboard_tag_action = QAction("Dashboard Tag",self)
self.set_backup_time = QAction("Set New Backup Time", self)
self.get_backup_time = QAction("Show Saved Backup Time", self)
self.oee_config_action = QAction("OEE Configuration", self)
cycle_menu.addAction(self.view_cycle_action)
cycle_menu.addAction(self.view_current_cycle_action)
fault_menu.addAction(self.view_current_fault_action)
fault_menu.addAction(self.view_backup_fault_action)
tip_dress_menu.addAction(self.tip_dressing_action)
tip_dress_menu.addAction(self.tip_change_action)
edit_tag_menu.addAction(self.edit_cycletime_tag_action)
edit_tag_menu.addAction(self.edit_stationfault_tag_action)
edit_tag_menu.addAction(self.edit_faultdelay_tag_action)
edit_tag_menu.addAction(self.edit_tipdress_tag_action)
edit_tag_menu.addAction(self.edit_tipchange_tag_action)
edit_tag_menu.addAction(self.edit_dashboard_tag_action)
setting_menu.addAction(self.get_backup_time)
setting_menu.addAction(self.set_backup_time)
setting_menu.addAction(self.oee_config_action)
self.view_current_cycle_action.triggered.connect(lambda: (self.cycletime_current_layout(), self.start_task()))
self.view_cycle_action.triggered.connect(lambda: self.cycletime_backup_layout())
self.view_current_fault_action.triggered.connect(lambda: self.show_current_fault_delay())
self.view_backup_fault_action.triggered.connect(lambda: self.show_backup_fault_delay())
self.set_backup_time.triggered.connect(lambda: self.dlg.show()) #Placeholder action
self.get_backup_time.triggered.connect(lambda: self.dlg.show())
self.edit_cycletime_tag_action.triggered.connect(lambda: self.edit_cycle_time_tags())
self.edit_faultdelay_tag_action.triggered.connect(lambda: self.edit_fault_delay_tags())
self.edit_stationfault_tag_action.triggered.connect(lambda: self.edit_station_fault_tags())
self.edit_tipchange_tag_action.triggered.connect(lambda: self.edit_tip_change_tags())
self.edit_tipdress_tag_action.triggered.connect(lambda:self.edit_tip_dress_tags())
self.edit_dashboard_tag_action.triggered.connect(lambda:self.edit_dashboard_tags())
self.oee_config_action.triggered.connect(lambda: self.show_oee_config())
def _get_stylesheet(self):
if self.dark_mode:
return """
QWidget {
background-color: #34495e;
color: #ecf0f1;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
QLabel {
color: #ecf0f1;
}
QPushButton {
background-color: #002A4D;
border: none;
color: white;
padding: 7px 14px;
border-radius: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #003A5D;
}
QTextEdit {
background-color: #1e1e2f;
color: #ecf0f1;
font-family: Consolas, monospace;
font-size: 11pt;
padding: 8px;
}
QFrame {
background-color: #2c3e50;
border-radius: 10px;
padding: 3px;
}
QMenuBar {
color: #002A4D;
background-color: #C6E5F5; /* Dark blue-gray */
font-weight: bold;
color: #002A4D;
}
QMenuBar::item {
spacing: 3px;
padding: 4px 12px;
color: #002A4D;
background-color: #C6E5F5; /* Slightly lighter */
}
QMenuBar::item:selected {
color: #002A4D;
background-color: #AAD8F0; /* Hover color */
}
QMenuBar::item:pressed {
color: #002A4D;
background-color: #AAD8F0; /* Clicked color */
}
QMenu {
color: #002A4D;
background-color: #C6E5F5; /* Dropdown background */
}
QMenu::item {
padding: 5px 20px;
color: #002A4D;
background-color: transparent;
}
QMenu::item:selected {
background-color: #6ABBE5;
color: black;
}
QTableView {
font-size: 10px;
background-color: #f5f5f5;
color: #002A4D;
gridline-color: #cccccc;
selection-background-color: #d3d3d3;
alternate-background-color: #f0f8ff;
font-family: 'Segoe UI';
border: 1px solid #cccccc;
border-radius: 5px;
}
QTableView::item {
padding: 5px;
}
QHeaderView::section {
background-color: #002A4D;
color: white;
font-weight: bold;
padding: 8px;
border: none;
border-bottom: 2px solid #aad8f0;
}
QHeaderView::section:hover {
background-color: #003A5D;
}
"""
else:
return """
QWidget {
background-color: #FFFFFF;
color: #002A4D;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
QLabel {
color: #002A4D;
}
QPushButton {
background-color: #002A4D;
border: none;
color: white;
padding: 7px 14px;
border-radius: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #003A5D;
}
QTextEdit {
background-color: #ffffff;
color: #002A4D;
font-family: Consolas, monospace;
font-size: 11pt;
padding: 8px;
}
QFrame {
background-color: #C6E5F5;
border-radius: 10px;
padding: 5px;
}
QMenuBar {
background-color: #C6E5F5; /* Dark blue-gray */
font-weight: bold;
color: #002A4D;
}
QMenuBar::item {
spacing: 3px;
padding: 4px 12px;
color: #002A4D;
background-color: #C6E5F5; /* Slightly lighter */
}
QMenuBar::item:selected {
color: #002A4D;
background-color: #AAD8F0; /* Hover color */
}
QMenuBar::item:pressed {
color: #002A4D;
background-color: #AAD8F0; /* Clicked color */
}
QMenu {
background-color: #C6E5F5; /* Dropdown background */
color: #002A4D;
}
QMenu::item {
padding: 5px 20px;
color: #002A4D;
background-color: transparent;
}
QMenu::item:selected {
background-color: #6ABBE5;
color: black;
}
QTableView {
font-size: 10px;
background-color: #f5f5f5;
color: #002A4D;
gridline-color: #cccccc;
selection-background-color: #d3d3d3;
alternate-background-color: #f0f8ff;
font-family: 'Segoe UI';
border: 1px solid #cccccc;
border-radius: 5px;
}
QTableView::item {
padding: 5px;
}
QHeaderView::section {
background-color: #002A4D;
color: white;
font-weight: bold;
padding: 8px;
border: none;
border-bottom: 2px solid #aad8f0;
}
QHeaderView::section:hover {
background-color: #003A5D;
}
"""
def _toggle_mode(self):
self.dark_mode = not self.dark_mode
if self.dark_mode:
self.mode_toggle_btn.setText("Switch to Light Mode")
else:
self.mode_toggle_btn.setText("Switch to Dark Mode")
self.setStyleSheet(self._get_stylesheet())
def edit_cycle_time_tags(self):
self.edit_cyctime_win.show()
def edit_station_fault_tags(self):
self.edit_fault_delay_win.show()
def edit_fault_delay_tags(self):
self.edit_station_fault_win.show()
def edit_tip_dress_tags(self):
self.edit_tip_dress_win.show()
def edit_tip_change_tags(self):
self.edit_tip_change_win.show()
def edit_dashboard_tags(self):
self.edit_dashboard_win.show()
def show_about_dialog(self):
QMessageBox.about(self, "About", "Production Analyser\nVersion 1.0\nDeveloped by Your Name")
def cycletime_backup_layout(self):
self.timer.stop()
files = (
os.listdir("CycleTimeBackup")
if os.path.exists("CycleTimeBackup")
else self.Dialog.show_error_dialog()
)
if not files:
return
#self.central_widget.destroy()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
header_label = QLabel("Please Choose a backup record from below list of the available records to view it.")
header_label.setStyleSheet(
"font-size: 14px; font-weight: normal; padding-bottom: 8px;"
)
print(files)
for file in files:
new_file = file.replace(".xlsx","")
files[files.index(file)] = new_file
print(files)
self.model = QStringListModel(files)
# List view
list_view = QListView()
list_view.setFixedWidth(500)
list_view.setModel(self.model)
list_view.clicked.connect(
lambda index: self.list_view_item_clicked(index=index)
)
# Create control panel layout
control_panel = QHBoxLayout()
# file name display
self.file_name_label = QLabel(f"File: {"No file selected"}")
self.file_name_label.setFont(QFont("Arial", 10, QFont.Bold))
self.file_name_label.setStyleSheet("padding: 5px;")
control_panel.addWidget(self.file_name_label, alignment=Qt.AlignLeft)
# Layout
layout = QVBoxLayout(self.central_widget)
layout.addLayout(control_panel)
layout.addWidget(header_label)
layout.addWidget(list_view)
def list_view_item_clicked(self, index):
self.file_path = "./CycleTimeBackup/" + self.model.data(index, 0)+ ".xlsx"
self.cycletime_current_layout()
self.currentfile_path = self.file_path
self.file_name_label.setText(f"Record Dated: {self.model.data(index,0)}")
self.load_data_to_veiw()
def cycletime_current_layout(self):
self.timer.stop()
self.central_widget.destroy()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
main_layout = QVBoxLayout(self.central_widget)
# Create horizontal layout for tables
tables_layout = (QHBoxLayout()) # change to QHBoxLayout for horizontal layout or Change to QVBoxLayout for vertical layout
# Create three table frames
self.left_frame = self.create_table_frame("Production Data")
self.middle_frame = self.create_table_frame("Delay in Production")
self.right_frame = self.create_table_frame("Process Delay \n (Stationwise)")
# Add frames to horizontal layout
tables_layout.addWidget(self.left_frame,stretch=4)
tables_layout.addWidget(self.middle_frame,stretch=4)
self.right_frame.setFixedWidth(200)
tables_layout.addWidget(self.right_frame,stretch=1)
# Create control panel layout
control_panel = QHBoxLayout()
control_panel.setContentsMargins(0, 0, 50, 0)
# Create back button to go to dashboard
back_button = QPushButton("Back")
back_button.clicked.connect(lambda : self.reinitialize_dashboard())
#Create graph button to show graph
self.graph_button = QPushButton("Show Pie Chart Analysis")
#df = pd.read_excel(self.file_path,index_col=0)
# Create cycle time input
cycle_label = QLabel("Cycle Time:")
cycle_label.setFont(QFont("Arial", 8, QFont.Bold))
self.cycle_input = QLineEdit()
self.cycle_input.setFixedWidth(100)
self.cycle_input.setText(str(self.cycle_time)) # Default value
self.cycle_input.setPlaceholderText("Enter cycle time")
self.cycle_input.returnPressed.connect(self.load_data_to_veiw)
# File name display
self.file_name_label = QLabel(f"File: {"No file selected"}")
self.file_name_label.setFont(QFont("Arial", 10, QFont.Bold))
self.file_name_label.setStyleSheet("padding: 5px;")
# # Time picker setup
# self.time_edit = CustomTimeEdit()
# self.time_edit.setDisplayFormat("hh:mm") # You can customize this format
# self.time_edit.setTime(QTime.currentTime()) # Set current time as default
# # Button setup
# self.button = QPushButton("SET BACKUP TIME")
# self.button.clicked.connect(self.set_backuptime)
# # Add widgets to control panel
spacer = QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Minimum)
control_panel.addWidget(back_button, alignment=Qt.AlignLeft)
control_panel.addWidget(cycle_label, alignment=Qt.AlignLeft)
control_panel.addWidget(self.cycle_input, alignment=Qt.AlignLeft)
control_panel.addItem(spacer)
control_panel.addWidget(self.file_name_label, alignment=Qt.AlignLeft)
main_layout.addLayout(control_panel)
# Add tables layout to main layout
main_layout.addLayout(tables_layout)
# Create tables
self.table1 = QTableView()
self.table2 = QTableView()
self.table3 = QTableView()
# Add tables to their respective frames
self.left_frame.layout().addWidget(self.table1)
self.middle_frame.layout().addWidget(self.table2)
self.middle_frame.layout().addWidget(self.graph_button,alignment=Qt.AlignCenter)
self.right_frame.layout().addWidget(self.table3)
def load_data_to_veiw(self):
try:
self.cycle_time = int(self.cycle_input.text())
# Read Excel file using pandas
df = pd.read_excel(self.file_path)
df_graph = pd.read_excel(self.file_path,index_col=0)
graph = GraphPlotter()
self.graph_button.clicked.connect(lambda : graph.pie_graph(df_graph, self.cycle_time))
#plit the dataframe into three parts
if not df.empty:
df.columns.values[0] = "Station No"
# Populate the three tables
self.populate_table(self.table1, df)
delaydf = df.copy()
self.get_delay_df(delaydf, self.cycle_time)
self.populate_delay_table(self.table2, delaydf)
self.populate_delay_total(self.table3, delaydf)
return MyWindow.LOAD_DATA_SUCCESS
else:
return MyWindow.EMPTY_DATAFRAME
except FileNotFoundError:
return MyWindow.LOAD_DATA_FAILED
def populate_delay_table(self, table, df):
# Calculate row sums for numeric columns
row_sums = df.select_dtypes(include=["int64", "float64"]).sum(axis=1)
model = QStandardItemModel()
model.setRowCount(df.shape[0])
model.setColumnCount(df.shape[1] + 1)
# Set headers
headers = [str(col) for col in df.columns] + ["Row Total"]
model.setHorizontalHeaderLabels(headers)
# Populate table with data
for row in range(df.shape[0]):
for col in range(df.shape[1]):
item = QStandardItem(str(df.iloc[row, col]))
if type(df.iloc[row, col]) != str:
if int(df.iloc[row, col]) > 0 :
item.setBackground(QColor(255, 255, 100))
model.setItem(row, col, item)
# Add row sum in the last column
row_sum_item = QStandardItem(f"{row_sums[row]}")
row_sum_item.setBackground(
QColor(200, 230, 255)
) # Light purple background(230, 230, 250)
row_sum_item.setFont(QFont("Arial", 8, QFont.Bold))
model.setItem(row, df.shape[1], row_sum_item)
table.setModel(model)
table.verticalHeader().setVisible(False)
self.highlight_max_values(model)
# Adjust column widths
table.resizeColumnsToContents()
def populate_table(self, table, df):