-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1114 lines (955 loc) · 43.9 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__license__ = '''
Multipack Parser Application - to parse the data from the Multipack Robot to an UR Robot
Copyright (C) 2024 Yann-Luca Näher
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
#TODO: After starting the program, ask the user to confirm each palette if it is empty or not. and if it is not empty ask the user to confirm if the user wants to continue anyways and ask for the current layer.
#TODO: Implement option for UR10e or UR20 robot. If UR20 is selected robot will have 2 pallets. else only it is like the old code.
#TODO: Implement seemless palletizing with 2 pallets for UR20 robot.
import sys
import subprocess
import argparse
import hashlib
import os
import shutil
import time
import threading
import socket
from xmlrpc.server import SimpleXMLRPCServer
import logging
from datetime import datetime
# import the needed qml modules for the virtual keyboard to work
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQuick import QQuickView
################################################################
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox, QCompleter, QFileDialog, QMessageBox
from PySide6.QtCore import Qt, QFileSystemWatcher, QProcess, QRegularExpression, QLocale
from PySide6.QtGui import QIntValidator, QDoubleValidator, QRegularExpressionValidator, QIcon
from ui_files.ui_main_window import Ui_Form
from ui_files import MainWindowResources_rc
from utils import global_vars
from utils.settings import Settings
from utils import UR_Common_functions as UR
from utils import UR10_Server_functions as UR10
from utils import UR20_Server_functions as UR20
from ui_files.BlinkingLabel import BlinkingLabel
logger = global_vars.logger
audio_thread = None
audio_thread_running = False
os.environ["QT_IM_MODULE"] = "qtvirtualkeyboard"
# global_vars.PATH_USB_STICK = 'E:\' # Pfad zu den .rob Dateien nur auskommentieren zum testen
if global_vars.PATH_USB_STICK == '..':
# Bekomme CWD und setze den Pfad auf den Überordner
logger.debug(os.path.dirname(os.getcwd()))
global_vars.PATH_USB_STICK = f'{os.path.dirname(os.getcwd())}/'
####################
# Server functions #
####################
def server_start():
"""
Start the XMLRPC server.
Returns:
0
"""
global server
server = SimpleXMLRPCServer(("", 8080), allow_none=True)
logger.debug("Start Server")
try:
robot_type = settings.settings['info']['UR_Model'] # Use the global settings object instead
logger.debug(f"Robot type: {robot_type}")
if robot_type not in ['UR10', 'UR20']:
# default to UR10
robot_type = 'UR10'
logger.warning(f"Invalid robot type {robot_type}, defaulting to UR10")
except (AttributeError, KeyError, TypeError) as e:
# If there's any error accessing the settings, default to UR10
robot_type = 'UR10'
logger.error(f"Error accessing robot type from settings: {e}. Defaulting to UR10")
# Register common functions for both robot types
server.register_function(UR.UR_SetFileName, "UR_SetFileName")
server.register_function(UR.UR_ReadDataFromUsbStick, "UR_ReadDataFromUsbStick")
server.register_function(UR.UR_Palette, "UR_Palette")
server.register_function(UR.UR_Karton, "UR_Karton")
server.register_function(UR.UR_Lagen, "UR_Lagen")
server.register_function(UR.UR_Zwischenlagen, "UR_Zwischenlagen")
server.register_function(UR.UR_PaketPos, "UR_PaketPos")
server.register_function(UR.UR_AnzLagen, "UR_AnzLagen")
server.register_function(UR.UR_AnzPakete, "UR_AnzPakete")
server.register_function(UR.UR_PaketeZuordnung, "UR_PaketeZuordnung")
server.register_function(UR.UR_Paket_hoehe, "UR_Paket_hoehe")
server.register_function(UR.UR_Startlage, "UR_Startlage")
server.register_function(UR.UR_Quergreifen, "UR_Quergreifen")
server.register_function(UR.UR_CoG, "UR_CoG")
server.register_function(UR.UR_MasseGeschaetzt, "UR_MasseGeschaetzt")
server.register_function(UR.UR_PickOffsetX, "UR_PickOffsetX")
server.register_function(UR.UR_PickOffsetY, "UR_PickOffsetY")
# Register robot type specific functions here if needed
if robot_type == 'UR10':
server.register_function(UR10.UR10_scanner1and2niobild, "UR_scanner1and2niobild")
server.register_function(UR10.UR10_scanner1bild, "UR_scanner1bild")
server.register_function(UR10.UR10_scanner2bild, "UR_scanner2bild")
server.register_function(UR10.UR10_scanner1and2iobild, "UR_scanner1and2iobild")
elif robot_type == 'UR20':
server.register_function(UR20.UR20_SetActivePalette, "UR_SetActivePalette")
server.register_function(UR20.UR20_GetActivePaletteNumber, "UR_GetActivePaletteNumber")
server.register_function(UR20.UR20_GetPaletteStatus, "UR_GetPaletteStatus")
server.register_function(UR20.UR20_scannerStatus, "UR_scannerStatus")
logger.debug(f"Successfully registered functions for {robot_type}")
server.serve_forever()
return 0
def server_stop():
"""
Stop the XMLRPC server.
"""
global_vars.ui.ButtonStopRPCServer.setEnabled(False)
server.shutdown()
logger.debug("Server stopped")
datensenden_manipulation(True, "Server starten", "")
def server_thread():
"""
Start the XMLRPC server in a separate thread.
"""
logger.debug("Starting server thread")
xServerThread = threading.Thread(target=server_start)
xServerThread.start()
global_vars.ui.ButtonStopRPCServer.setEnabled(True)
datensenden_manipulation(False, "Server läuft", "green")
def datensenden_manipulation(visibility: bool, display_text: str, display_colour: str):
"""
Manipulate the visibility of the "Daten Senden" button and the display text.
"""
buttons = [global_vars.ui.ButtonDatenSenden, global_vars.ui.ButtonDatenSenden_2]
for button in buttons:
button.setStyleSheet(f"color: {display_colour}")
button.setEnabled(visibility)
button.setText(display_text)
def send_cmd_play():
"""
Send a command to the robot to start.
"""
try:
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (global_vars.robot_ip, 29999)
logger.debug('connecting to %s port %s' %(server_address))
sock.connect(server_address)
# Send data
message = 'play\n'
logger.debug('sending %s' %(message))
sock.sendall(message.encode('utf-8'))
# Print any response
data = sock.recv(4096)
logger.debug('received %s' %(data))
finally:
logger.debug('closing socket')
sock.close()
def send_cmd_pause():
"""
Send a command to the robot to pause.
"""
try:
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (global_vars.robot_ip, 29999)
logger.debug('connecting to %s port %s' %(server_address))
sock.connect(server_address)
# Send data
message = 'pause\n'
logger.debug('sending %s' %(message))
sock.sendall(message.encode('utf-8'))
# Print any response
data = sock.recv(4096)
logger.debug('received %s' %(data))
finally:
logger.debug('closing socket')
sock.close()
def send_cmd_stop():
"""
Send a command to the robot to stop.
"""
try:
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (global_vars.robot_ip, 29999)
logger.debug('connecting to %s port %s' %(server_address))
sock.connect(server_address)
# Send data
message = 'stop\n'
logger.debug('sending %s' %(message))
sock.sendall(message.encode('utf-8'))
# Print any response
data = sock.recv(4096)
logger.debug('received %s' %(data))
finally:
logger.debug('closing socket')
sock.close()
################
# UI functions #
################
def update_status_label(text: str, color: str, blink: bool = False, second_color: str = None):
"""Update the status label with the given text and color"""
# Create blinking label if it doesn't exist
if not hasattr(global_vars, 'blinking_label'):
global_vars.blinking_label = BlinkingLabel(
text,
color,
global_vars.ui.LabelPalletenplanInfo.geometry(),
parent=global_vars.ui.stackedWidget.widget(0),
second_color=second_color,
font=global_vars.ui.LabelPalletenplanInfo.font(),
alignment=global_vars.ui.LabelPalletenplanInfo.alignment()
)
global_vars.ui.LabelPalletenplanInfo.hide() # Hide the original label
# Update the blinking label
global_vars.blinking_label.update_text(text)
global_vars.blinking_label.update_color(color, second_color)
if blink:
global_vars.blinking_label.start_blinking()
else:
global_vars.blinking_label.stop_blinking()
def open_password_dialog() -> None:
"""
Open the password dialog.
"""
from ui_files.PasswordDialog import PasswordEntryDialog # Import here instead of top
dialog = PasswordEntryDialog(parent_window=main_window)
#dialog.setModal(False) #cant set to true because it will block the qtvirtualkeyboard
dialog.show()
dialog.ui.lineEdit.setFocus()
dialog.exec()
if dialog.password_accepted:
open_settings_page()
def open_settings_page() -> None:
"""
Open the settings page.
"""
# set page of the stacked widgets to index 2
settings.reset_unsaved_changes()
global_vars.ui.stackedWidget.setCurrentIndex(2)
def open_parameter_page() -> None:
"""
Open the parameter page.
"""
# set page of the stacked widgets to index 1
global_vars.ui.tabWidget.setCurrentIndex(0)
global_vars.ui.stackedWidget.setCurrentIndex(1)
def open_main_page() -> None:
"""
Open the main page.
"""
# set page of the stacked widgets to index 0
global_vars.ui.stackedWidget.setCurrentIndex(0)
def open_explorer() -> None:
"""
Open the explorer.
"""
logger.info("Opening explorer")
try:
if sys.platform == "win32":
subprocess.Popen(["explorer.exe"])
elif sys.platform == "linux":
# Try different file managers in order of preference
file_managers = ["nautilus", "dolphin", "thunar", "pcmanfm"]
for fm in file_managers:
try:
subprocess.Popen([fm, "."])
break
except FileNotFoundError:
continue
except Exception as e:
logger.error(f"Failed to open file explorer: {e}")
def open_terminal() -> None:
"""
Open the terminal.
"""
logger.info("Opening terminal")
try:
if sys.platform == "win32":
subprocess.Popen(["start", "cmd.exe"], shell=True)
elif sys.platform == "linux":
# Try different terminals in order of preference
terminals = ["gnome-terminal", "konsole", "xfce4-terminal", "xterm"]
for term in terminals:
try:
subprocess.Popen([term])
break
except FileNotFoundError:
continue
except Exception as e:
logger.error(f"Failed to open terminal: {e}")
def load() -> None:
"""
Load the selected file.
This function is called when the user clicks the "Lade Palettenplan" button.
"""
# get the value of the EingabePalettenplan text box and run UR_SET_FILENAME then check if the file exists and if it doesnt open a message box
Artikelnummer = global_vars.ui.EingabePallettenplan.text()
UR.UR_SetFileName(Artikelnummer)
errorReadDataFromUsbStick = UR.UR_ReadDataFromUsbStick()
if errorReadDataFromUsbStick == 1:
logger.error(f"Error reading file for {Artikelnummer=} no file found")
update_status_label("Kein Plan gefunden", "red")
else:
# remove the editing focus from the text box
global_vars.ui.EingabePallettenplan.clearFocus()
logger.debug(f"File for {Artikelnummer=} found")
update_status_label("Plan erfolgreich geladen", "green")
global_vars.ui.ButtonOpenParameterRoboter.setEnabled(True)
global_vars.ui.ButtonDatenSenden.setEnabled(True)
global_vars.ui.EingabeKartonGewicht.setEnabled(True)
global_vars.ui.EingabeKartonhoehe.setEnabled(True)
global_vars.ui.EingabeStartlage.setEnabled(True)
global_vars.ui.checkBoxEinzelpaket.setEnabled(True)
Volumen = (global_vars.g_PaketDim[0] * global_vars.g_PaketDim[1] * global_vars.g_PaketDim[2]) / 1E+9 # in m³
logger.debug(f"{Volumen=}")
Dichte = 1000 # Dichte von Wasser in kg/m³
logger.debug(f"{Dichte=}")
Ausnutzung = 0.4 # Empirsch ermittelter Faktor - nicht für Gasflaschen
logger.debug(f"{Ausnutzung=}")
Gewicht = round(Volumen * Dichte * Ausnutzung, 1) # Gewicht in kg
logger.debug(f"{Gewicht=}")
global_vars.ui.EingabeKartonGewicht.setText(str(Gewicht))
global_vars.ui.EingabeKartonhoehe.setText(str(global_vars.g_PaketDim[2]))
def send_data() -> None:
"""
Send the data to the robot.
This function is called when the user clicks the "Daten Senden" button.
"""
logger.debug("Button Daten Senden clicked")
server_thread()
def load_wordlist() -> list:
"""
Load the wordlist from the USB stick.
Returns:
A list of wordlist items.
"""
wordlist = []
count = 0
for file in os.listdir(global_vars.PATH_USB_STICK):
if file.endswith(".rob"):
wordlist.append(file[:-4])
count = count + 1
logger.debug(f"Wordlist {count=}")
settings.settings['info']['number_of_plans'] = count
return wordlist
def init_settings():
"""
Initialize the settings.
This function is called when the application starts.
"""
global settings
settings = Settings()
global_vars.PATH_USB_STICK = settings.settings['admin']['path']
logger.debug(f"Settings: {settings}")
def leave_settings_page():
"""
Leave the settings page.
This function is called when the user clicks the "Zurueck" button in the settings page.
"""
try:
settings.compare_loaded_settings_to_saved_settings()
except ValueError as e:
logger.error(f"Error: {e}")
# If settings do not match, ask whether to discard or save the new data
response = QMessageBox.question(main_window, "Verwerfen oder Speichern", "Möchten Sie die neuen Daten verwerfen oder speichern?",
QMessageBox.Discard | QMessageBox.Save, QMessageBox.Save)
main_window.setWindowState(main_window.windowState() ^ Qt.WindowActive) # This will make the window blink
if response == QMessageBox.Save:
try:
settings.save_settings()
logger.debug("New settings saved.")
except Exception as e:
logger.error(f"Failed to save settings: {e}")
QMessageBox.critical(main_window, "Error", f"Failed to save settings: {e}")
return
elif response == QMessageBox.Discard:
settings.reset_unsaved_changes()
set_settings_line_edits()
logger.debug("All changes discarded.")
# Navigate back to the main page
open_main_page()
def open_file():
"""
Open a file.
This function is called when the user clicks the "Open" button in the editor settings tab.
"""
# Open a file browser to select a file
file_path, _ = QFileDialog.getOpenFileName(parent=main_window, caption="Open File")
global_vars.ui.lineEditFilePath.setText(file_path)
logger.debug(f"File path: {global_vars.ui.lineEditFilePath.text()}")
# Open the selected file and load its content into the text edit widget
try:
with open(file_path, 'r') as file:
file_content = file.read()
global_vars.ui.textEditFile.setPlainText(file_content) # Use setPlainText for QTextEdit
except Exception as e:
logger.error(f"Failed to open file: {e}")
QMessageBox.critical(main_window, "Error", f"Failed to open file: {e}")
main_window.setWindowState(main_window.windowState() ^ Qt.WindowActive) # This will make the window blink
def save_open_file():
"""
Save or open a file.
This function is called when the user clicks the "Speichern" button in the editor settings tab.
"""
# save the file to the selected file path but prompt the user before overwriting the file
file_path = global_vars.ui.lineEditFilePath.text()
if file_path:
if os.path.exists(file_path):
overwrite = QMessageBox.question(main_window, "Overwrite File?", f"The file {file_path} already exists. Do you want to overwrite it?", QMessageBox.Yes | QMessageBox.No)
main_window.setWindowState(main_window.windowState() ^ Qt.WindowActive) # This will make the window blink
if overwrite == QMessageBox.Yes:
with open(file_path, 'w') as file:
file.write(global_vars.ui.textEditFile.toPlainText())
else:
logger.debug("File not saved.")
else:
with open(file_path, 'w') as file:
file.write(global_vars.ui.textEditFile.toPlainText())
else:
logger.debug("File not saved.")
QMessageBox.warning(main_window, "Error", "Please select a file to save.")
def execute_command():
"""
Execute a command in the console.
"""
command = global_vars.ui.lineEditCommand.text().strip()
# Check if the command starts with ">"
if command.startswith("> "):
command = command[2:].strip() # Remove the "> " prefix
if not command:
return
# Clear the console if the command is 'cls' or 'clear'
if command.lower() in ['cls', 'clear']:
global_vars.ui.textEditConsole.clear()
global_vars.ui.lineEditCommand.setText("> ") # Reset lineEdit with the prefix
return
global_vars.ui.textEditConsole.append(f"$ {command}")
global_vars.ui.lineEditCommand.setText("> ") # Reset lineEdit with the prefix
process = QProcess()
process.setProcessChannelMode(QProcess.MergedChannels)
process.readyReadStandardOutput.connect(handle_stdout)
process.readyReadStandardError.connect(handle_stderr)
# On Linux, use sh to execute commands
if sys.platform == "linux":
process.start("sh", ["-c", command])
else:
process.start(command)
global_vars.process = process
def handle_stdout():
"""
Handle standard output.
"""
data = global_vars.process.readAllStandardOutput()
stdout = bytes(data).decode("utf-8", errors="replace")
global_vars.ui.textEditConsole.append(stdout)
def handle_stderr():
"""
Handle standard error output.
"""
data = global_vars.process.readAllStandardError()
stderr = bytes(data).decode("utf-8", errors="replace")
global_vars.ui.textEditConsole.append(stderr)
def set_settings_line_edits():
"""
Set the line edits in the settings page to the current settings.
This function is called when the settings page is opened or when the settings are changed.
"""
global_vars.ui.lineEditDisplayHeight.setText(str(settings.settings['display']['specs']['height']))
global_vars.ui.lineEditDisplayWidth.setText(str(settings.settings['display']['specs']['width']))
global_vars.ui.lineEditDisplayRefreshRate.setText(str(int(float(settings.settings['display']['specs']['refresh_rate']))))
global_vars.ui.lineEditDisplayModel.setText(settings.settings['display']['specs']['model'])
# Set the combo box value
current_model = settings.settings['info']['UR_Model']
index = global_vars.ui.comboBoxChooseURModel.findText(current_model)
if index >= 0:
global_vars.ui.comboBoxChooseURModel.setCurrentIndex(index)
global_vars.ui.lineEditURSerialNo.setText(settings.settings['info']['UR_Serial_Number'])
global_vars.ui.lineEditURManufacturingDate.setText(settings.settings['info']['UR_Manufacturing_Date'])
global_vars.ui.lineEditURSoftwareVer.setText(settings.settings['info']['UR_Software_Version'])
global_vars.ui.lineEditURName.setText(settings.settings['info']['Pallettierer_Name'])
global_vars.ui.lineEditURStandort.setText(settings.settings['info']['Pallettierer_Standort'])
global_vars.ui.lineEditNumberPlans.setText(str(settings.settings['info']['number_of_plans']))
global_vars.ui.lineEditNumberCycles.setText(str(settings.settings['info']['number_of_use_cycles']))
global_vars.ui.lineEditLastRestart.setText(settings.settings['info']['last_restart'])
global_vars.ui.pathEdit.setText(settings.settings['admin']['path'])
global_vars.ui.audioPathEdit.setText(settings.settings['admin']['alarm_sound_file'])
def restart_app():
"""
Restart the system.
"""
try:
settings.compare_loaded_settings_to_saved_settings()
except ValueError as e:
logger.error(f"Error: {e}")
response = QMessageBox.question(main_window, "Verwerfen oder Speichern",
"Möchten Sie die neuen Daten verwerfen oder speichern?",
QMessageBox.Discard | QMessageBox.Save,
QMessageBox.Save)
if response == QMessageBox.Save:
try:
settings.save_settings()
except Exception as e:
logger.error(f"Failed to save settings: {e}")
return
logger.info("Rebooting system...")
if 'server' in globals():
server_stop()
subprocess.run(['sudo', 'reboot'], check=True)
def save_and_exit_app():
"""
Safely exit the application.
"""
try:
settings.compare_loaded_settings_to_saved_settings()
except ValueError as e:
logger.error(f"Error: {e}")
# If settings do not match, ask whether to discard or save the new data
response = QMessageBox.question(main_window, "Verwerfen oder Speichern", "Möchten Sie die neuen Daten verwerfen oder speichern?",
QMessageBox.Discard | QMessageBox.Save, QMessageBox.Save)
main_window.setWindowState(main_window.windowState() ^ Qt.WindowActive) # This will make the window blink
if response == QMessageBox.Save:
try:
settings.save_settings()
logger.debug("New settings saved.")
except Exception as e:
logger.error(f"Failed to save settings: {e}")
QMessageBox.critical(main_window, "Error", f"Failed to save settings: {e}")
return
elif response == QMessageBox.Discard:
settings.reset_unsaved_changes()
set_settings_line_edits()
logger.debug("All changes discarded.")
exit_app()
def exit_app():
"""
Exit the application.
"""
if 'server' in globals():
server_stop()
sys.exit(0)
def set_wordlist():
"""
Set the wordlist.
"""
global completer # Declare completer as global
wordlist = load_wordlist()
completer = QCompleter(wordlist, main_window) # Now this will access the global variable
global_vars.ui.EingabePallettenplan.setCompleter(completer)
file_watcher = QFileSystemWatcher([global_vars.PATH_USB_STICK], main_window)
file_watcher.directoryChanged.connect(update_wordlist)
def open_folder_dialog():
"""
Open the folder dialog.
"""
# show warning dialog if the user wants to set the path
# only if the user acknowledges the warning dialog and the risks then continue with choosing the folder else cancel asap
response = QMessageBox.warning(main_window, "Warnung! - Mögliche Risiken!", "<b>Möchten Sie den Pfad wirklich ändern?</b><br>Dies könnte zu Problemen führen, wenn bereits ein Palettenplan geladen ist und nach dem Setzen des Pfades nicht ein neuer geladen wird.", QMessageBox.Yes | QMessageBox.No)
main_window.setWindowState(main_window.windowState() ^ Qt.WindowActive) # This will make the window blink
if response == QMessageBox.Yes:
pass
else:
return
logger.debug(f"Opening folder dialog")
folder = QFileDialog.getExistingDirectory(parent=main_window, caption="Open Folder")
if folder:
if not folder.endswith('/') and not folder.endswith('\\'):
folder += '/'
logger.debug(f"{folder=}")
global_vars.ui.pathEdit.setText(folder)
global_vars.PATH_USB_STICK = folder
set_wordlist() # Ensure this is defined before calling it
def open_file_dialog():
"""
Open the file dialog.
"""
file_path = QFileDialog.getOpenFileName(main_window, "Open Audio File", "", "Audio Files (*.wav)")
if file_path:
global_vars.ui.audioPathEdit.setText(file_path[0])
def update_wordlist():
"""
Update the wordlist.
"""
new_wordlist = load_wordlist()
completer.model().setStringList(new_wordlist) # This will now work with the global completer
set_wordlist()
def check_for_updates():
"""
Check for a file called MultipackParser under /media/ and /mnt/.
If it exists, spawn an updater process to replace the current binary.
"""
# TODO: Add visual feedback to the user so that they know that the application is checking for updates
search_paths = ["/media", "/mnt"]
update_file_name = "MultipackParser"
found_update_file = None
# Traverse /media and /mnt to find the update file
for base_path in search_paths:
for root, dirs, files in os.walk(base_path):
if update_file_name in files:
found_update_file = os.path.join(root, update_file_name)
break
if found_update_file:
break
if not found_update_file:
logger.info("No update file found.")
return
logger.info(f"Update file found: {found_update_file}")
# copy the new binary to cwd/update/MultipackParser and make it executable
os.makedirs("update", exist_ok=True)
shutil.copy(found_update_file, "update/MultipackParser")
os.chmod("update/MultipackParser", 0o755)
found_update_file = f"{os.getcwd()}/update/MultipackParser"
logger.debug("New binary copied to update/MultipackParser")
logger.debug("New binary is executable")
logger.debug("Checking for new Version")
# run the new binary with --version to check for version string and compare it to the global_arg.VERSION
new_version = subprocess.check_output([f"{found_update_file}", "--version"]).decode().strip()
# the version string is in the format "Multipack Parser Application Version: 1.5.3-beta"
new_version = new_version.split(" ")[-1]
logger.debug(f"New version: {new_version}")
current_version = global_vars.VERSION.split("-")
current_version_tag = current_version[1] if len(current_version) > 1 else None
current_version = current_version[0].split(".")
new_version = new_version.split("-")
new_version_tag = new_version[1] if len(new_version) > 1 else None
new_version = new_version[0].split(".")
# Convert str[] to int[]
current_version = [int(x) for x in current_version]
new_version = [int(x) for x in new_version]
# Compare versions
if new_version[0] <= current_version[0] and new_version[1] <= current_version[1] and new_version[2] <= current_version[2]:
logger.info("No new version found.")
return
logger.info(f"New version found: {new_version}")
# Spawn an updater process
current_binary = sys.argv[0] # Path to the running binary
updater_script = f"""#!/bin/bash
# Wait for the parent process to terminate
sleep 5
# Replace the current binary with the update file
cp "{found_update_file}" "{current_binary}"
chmod +x "{current_binary}" # Ensure the binary is executable
rm -rf "{os.getcwd()}/update"
# Optionally reboot the system immediately
reboot
"""
# Write the updater script to a temporary file
updater_path = f"{os.getcwd()}/update/updater_script.sh"
with open(updater_path, "w") as f:
f.write(updater_script)
# Make the script executable
os.chmod(updater_path, 0o755) # Ensure the script is executable
# Spawn the updater process
subprocess.Popen( # Spawn the updater process
["/bin/bash", updater_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
close_fds=True,
start_new_session=True, # Detach the process
)
logger.info("Updater process spawned. Exiting current application.") # Log the process spawn
exit_app()
def spawn_play_stepback_warning_thread():
"""
Spawn a thread to play the stepback warning.
"""
global audio_thread, audio_thread_running
if audio_thread is None:
audio_thread_running = True
audio_thread = threading.Thread(target=play_stepback_warning)
audio_thread.daemon = True
audio_thread.start()
def kill_play_stepback_warning_thread():
"""
Kill the thread playing the stepback warning.
"""
global audio_thread, audio_thread_running
audio_thread_running = False
if audio_thread:
audio_thread = None
def play_stepback_warning():
"""
Play the stepback warning in a loop using aplay.
"""
global audio_thread_running
try:
while audio_thread_running:
try:
# Use aplay to play the audio file
subprocess.run(['aplay', settings.settings['admin']['alarm_sound_file']],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
logger.debug("Stepback warning played")
time.sleep(0.1) # Small delay between loops
except subprocess.CalledProcessError as e:
logger.error(f"Error during playback: {e}")
break
except Exception as e:
logger.error(f"Error in audio thread: {e}")
finally:
logger.debug("Audio thread stopping")
def set_audio_volume():
"""Set system audio volume using amixer"""
if not global_vars.audio_muted:
volume = '0%'
icon_name = ":/Sound/imgs/volume-off.png"
else:
volume = '100%'
icon_name = ":/Sound/imgs/volume-on.png"
logger.debug(f"Setting audio volume to {volume}")
try:
# Try PulseAudio first, then fallback to default ALSA
try:
subprocess.run(['amixer', '-D', 'pulse', 'set', 'Master', volume],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True)
except:
subprocess.run(['amixer', 'set', 'Master', volume],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True)
global_vars.ui.pushButtonVolumeOnOff.setIcon(QIcon(icon_name))
global_vars.audio_muted = not global_vars.audio_muted
except Exception as e:
logger.error(f"Error setting volume: {e}")
def delay_warning_sound():
"""
This should be called in a thread at the start of the application. and never get stopped.
Delays the warning sound start by 40 seconds.
The sound starts if global_vars.timestamp_scanner_fault is not None and 40 seconds or older than current time.
"""
while True:
if global_vars.timestamp_scanner_fault and (datetime.now() - global_vars.timestamp_scanner_fault).total_seconds() >= 40:
if not audio_thread_running:
spawn_play_stepback_warning_thread()
if global_vars.timestamp_scanner_fault is None:
kill_play_stepback_warning_thread()
time.sleep(5)
#################
# Main function #
#################
class CustomDoubleValidator(QDoubleValidator):
"""
Custom double validator.
This class inherits from QDoubleValidator and overrides the validate method to allow
commas to be used as decimal separators.
"""
def validate(self, usr_input, pos):
"""
Validate the input.
Args:
input (str): The input to be validated.
pos (int): The position of the input in the text box.
Returns:
bool: True if the input is valid, False otherwise.
"""
if ',' in usr_input:
usr_input = usr_input.replace(',', '.')
return super().validate(usr_input, pos)
def fixup(self, usr_input):
"""
Fixup the input.
Args:
input (str): The input to be fixed up.
Returns:
str: The fixed up input.
"""
if ',' in usr_input:
usr_input = usr_input.replace(',', '.')
return usr_input # Directly return the modified input without further processing
# Main function to run the application
def main():
"""
Main function to run the application.
"""
global main_window
parser = argparse.ArgumentParser(description="Multipack Parser Application")
parser.add_argument('--version', action='store_true', help='Show version information and exit')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose logging')
parser.add_argument('--rob-path', type=str, help='Path to the .rob files')
args = parser.parse_args()
if args.version:
print(f"Multipack Parser Application Version: {global_vars.VERSION}")
return
if args.verbose:
# enable verbose logging
logger.setLevel(logging.DEBUG)
if args.rob_path:
# try to check if the path is valid
if os.path.exists(args.rob_path):
# set the path to the .rob files
global_vars.PATH_USB_STICK = args.rob_path
else:
logger.error(f"Path {args.rob_path} does not exist")
return
logger.debug(f"MultipackParser Application Version: {global_vars.VERSION}")
QLocale.setDefault(QLocale(QLocale.German, QLocale.Germany)) # set locale to german for german keyboard layout
app = QApplication(sys.argv)
main_window = QMainWindow()
main_window.setWindowFlags(Qt.FramelessWindowHint) # remove the window border to prevent moving or minimizing the window
global_vars.ui = Ui_Form()
global_vars.ui.setupUi(main_window)
global_vars.ui.stackedWidget.setCurrentIndex(0)
global_vars.ui.tabWidget_2.setCurrentIndex(0)
# init settings
init_settings()
# set last restart and number of use cycles
settings.settings['info']['last_restart'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
settings.settings['info']['number_of_use_cycles'] = str(int(settings.settings['info']['number_of_use_cycles']) + 1)
settings.save_settings()
logger.debug(f"{sys.argv=}")
logger.debug(f"{global_vars.VERSION=}")
logger.debug(f"{global_vars.PATH_USB_STICK=}")
# Set the regular expression validator for EingabePallettenplan
regex = QRegularExpression(r"^[0-9\-_]*$")
validator = QRegularExpressionValidator(regex)
global_vars.ui.EingabePallettenplan.setValidator(validator)
set_wordlist()
# Apply QIntValidator to restrict the input to only integers
int_validator = QIntValidator()
global_vars.ui.EingabeKartonhoehe.setValidator(int_validator)
# Apply CustomDoubleValidator to restrict the input to only numbers
float_validator = CustomDoubleValidator()
float_validator.setNotation(QDoubleValidator.StandardNotation)
float_validator.setDecimals(2) # Set to desired number of decimals
global_vars.ui.EingabeKartonGewicht.setValidator(float_validator)
# if the user entered a Artikelnummer in the text box and presses enter it calls the load function
global_vars.ui.EingabePallettenplan.returnPressed.connect(load)
#Page 1 Buttons
global_vars.ui.ButtonSettings.clicked.connect(open_password_dialog)
global_vars.ui.LadePallettenplan.clicked.connect(load)
global_vars.ui.ButtonOpenParameterRoboter.clicked.connect(open_parameter_page)
global_vars.ui.ButtonDatenSenden.clicked.connect(send_data)
global_vars.ui.startaudio.clicked.connect(spawn_play_stepback_warning_thread)
global_vars.ui.stopaudio.clicked.connect(kill_play_stepback_warning_thread)
# when global_vars.ui.pushButtonVolumeOnOff is clicked and changed to state checked then set the audio volume of the system to 0% if it is not checked then set it to 100%
global_vars.ui.pushButtonVolumeOnOff.clicked.connect(set_audio_volume)
#Page 2 Buttons
# Roboter Tab
global_vars.ui.ButtonZurueck.clicked.connect(open_main_page)
global_vars.ui.ButtonRoboterStart.clicked.connect(send_cmd_play)
global_vars.ui.ButtonRoboterPause.clicked.connect(send_cmd_pause)
global_vars.ui.ButtonRoboterStop.clicked.connect(send_cmd_stop)
global_vars.ui.ButtonStopRPCServer.clicked.connect(server_stop)
# Aufnahme Tab
global_vars.ui.ButtonZurueck_2.clicked.connect(open_main_page)
global_vars.ui.ButtonDatenSenden_2.clicked.connect(send_data)
# Page 3 Stuff
# Settings Tab
global_vars.ui.ButtonZurueck_3.clicked.connect(leave_settings_page)
global_vars.ui.pushButtonSpeichern.clicked.connect(settings.save_settings)
global_vars.ui.lineEditDisplayHeight.textChanged.connect(lambda text: settings.settings['display']['specs'].__setitem__('height', int(text)))
global_vars.ui.lineEditDisplayWidth.textChanged.connect(lambda text: settings.settings['display']['specs'].__setitem__('width', int(text)))
global_vars.ui.lineEditDisplayRefreshRate.textChanged.connect(lambda text: settings.settings['display']['specs'].__setitem__('refresh_rate', int(text)))
global_vars.ui.lineEditDisplayModel.textChanged.connect(lambda text: settings.settings['display']['specs'].__setitem__('model', text))