forked from Scummer/carrera-rms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rms.py
1335 lines (1196 loc) · 52 KB
/
rms.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
""" Carrera(R) Digital 124/132 race management system based on carreralib"""
""" Copyright 2017 Thomas Reich [email protected] """
""" V1.0 Initial release """
""" V1.0.1 Formatting of display, outputs and other display improvements """
#For webpage
from flask import (Flask, render_template)
PORT=5000
#For QR-Code
from qrcode import QRCode
import socket
#For threading
from threading import Thread
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QLCDNumber,
QProgressBar,
QPushButton,
QLabel,
QFrame,
QVBoxLayout,
QHBoxLayout,
QGroupBox,
QTabWidget,
QComboBox,
QCheckBox,
QLineEdit,
QGridLayout,
QShortcut,
QInputDialog,
QDialog,
QListWidget,
QSizePolicy,
QTableWidget,
QTableWidgetItem,
QMainWindow
)
from PyQt5.QtCore import (
QTimer,
QTime,
QObject,
QByteArray,
pyqtProperty,
QPropertyAnimation,
Qt,
QThread
)
try:
from PyQt5.QtBluetooth import (
QBluetoothDeviceDiscoveryAgent
)
except ImportError:
QBluetoothDeviceDiscoveryAgent = None
from PyQt5.QtGui import (
QKeySequence,
QFont,
QPainter,
QPalette,
QColor
)
from carreralib import ControlUnit
#Necessary for TimeoutErrorHandling
import carreralib
import sys, os
if os.name != "nt":
import fcntl
import struct
# For Sound
import vlc
# To wait
import time
#For audio output use the folder 'sounds'
class Audio:
def __init__(self):
self.list_songnames=os.listdir(os.path.realpath('sounds'))
#Defines if audio was played in this handeling process
self.played=False
#setting up new directory for songs
self.songs=dict()
for song in self.list_songnames:
#Input Name without ending as key and vlc Object as value
self.songs[song.split('.')[0]]=vlc.MediaPlayer('file://'+os.path.realpath('sounds')+'/'+song)
def play(self, songname):
#Stop first to enable playing afterwards
self.songs[songname].stop()
self.songs[songname].play()
def posgetter(driver):
return (-driver.lapcount, driver.time)
def CtrlNum(driver):
return (driver.CtrlNum)
#Return Format and time
def formattime(time, longfmt):
if time is None:
return '--.---'
s = time // 1000
ms = time % 1000
if not longfmt:
return '%02d.%03d' % ( s % 60, ms)
elif s < 3600:
return '%d:%02d.%03d' % (s // 60, s % 60, ms)
else:
return '%d:%02d:%02d.%03d' % (s // 3600, (s // 60) % 60, s % 60, ms)
### Change to also use CU
class BtSelect(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('Connect to Control Unit')
self.initUI()
def initUI(self):
self.vLayout = QVBoxLayout(self)
self.hBtnLayout = QHBoxLayout()
if QBluetoothDeviceDiscoveryAgent != None:
self.btList = QListWidget()
self.vLayout.addWidget(self.btList)
self.scanBtn = QPushButton('Scan')
self.hBtnLayout.addWidget(self.scanBtn)
else:
self.cuAddressInput = QLineEdit()
self.hCuAddressLayout = QHBoxLayout()
self.hCuAddressLayout.addWidget(QLabel('Enter CU BT address or USB device'))
self.hCuAddressLayout.addWidget(self.cuAddressInput)
self.vLayout.addLayout(self.hCuAddressLayout)
self.connectBtn = QPushButton('Connect')
self.hBtnLayout.addWidget(self.connectBtn)
self.rejectBtn = QPushButton('Cancel')
self.hBtnLayout.addWidget(self.rejectBtn)
self.vLayout.addLayout(self.hBtnLayout)
self.connectBtn.clicked.connect(self.accept)
self.rejectBtn.clicked.connect(self.reject)
class StartLight(QWidget):
def __init__(self):
super().__init__()
self.onVal = False
self.update()
def setOn(self, on):
self.onVal = on
self.update()
def paintEvent(self, e):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
if not self.onVal:
painter.setBrush(QColor(40, 40, 40))
else:
painter.setBrush(Qt.red)
painter.drawEllipse(0,0, self.width(), self.height())
class StartLights(QWidget):
def __init__(self, parent = None):
super().__init__(parent)
hbox = QHBoxLayout(self)
self.lightOne = StartLight()
self.lightTwo = StartLight()
self.lightThree = StartLight()
self.lightFour = StartLight()
self.lightFive = StartLight()
hbox.addWidget(self.lightOne)
hbox.addWidget(self.lightTwo)
hbox.addWidget(self.lightThree)
hbox.addWidget(self.lightFour)
hbox.addWidget(self.lightFive)
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
lightsPal = self.palette()
lightsPal.setColor(lightsPal.Background, Qt.black)
self.setPalette(lightsPal)
self.spacekey = QShortcut(QKeySequence("Space"), self)
class Rms(QMainWindow):
def __init__(self):
super().__init__()
self.shutdown = False
self.setStyleSheet("QMainWindow{background: #282828;} QLCDNumber{ border:1px solid black; background-color: black} QLabel{border:2px; color: #969696} QPushButton{border:1px solid #969696; color:#969696 ; background-color:#282828; border-radius: 0px;} QPushButton:pressed { color:black ; background-color:#969696;}")
# Counter for sleeping before exiting
self.cuoffcounter=0
if len(sys.argv) == 2:
self.startRMS(sys.argv[1])
else:
self.btDialog = BtSelect()
if QBluetoothDeviceDiscoveryAgent != None:
self.discoverCU()
self.btDialog.scanBtn.clicked.connect(self.discoverCU)
if self.btDialog.exec_():
if QBluetoothDeviceDiscoveryAgent != None:
if self.discoverBtDevice.isActive():
self.discoverBtDevice.stop()
BTdevice = self.btDialog.btList.selectedItems()
self.cuaddress = BTdevice[0].text().split(' -> ')[1]
else:
self.cuaddress = self.btDialog.cuAddressInput.text()
self.startRMS(self.cuaddress)
else:
sys.exit()
def closeEvent(self, event):
self.shutdown = True
self.cu.close()
event.accept()
def discoverCU(self):
self.btDialog.scanBtn.setEnabled(False)
self.discoverBtDevice = QBluetoothDeviceDiscoveryAgent()
self.discoverBtDevice.setLowEnergyDiscoveryTimeout(5000)
self.discoverBtDevice.deviceDiscovered.connect(self.addBtDevice)
self.discoverBtDevice.finished.connect(self.btScanFinished)
self.discoverBtDevice.error.connect(self.btScanError)
self.discoverBtDevice.start()
def addBtDevice(self, btDevice):
self.btDialog.btList.addItem(str(btDevice.name()) + ' -> ' + str(btDevice.address().toString()))
if btDevice.name() == 'Control_Unit':
self.btDialog.btList.setCurrentRow(self.btDialog.btList.count() - 1)
def btScanFinished(self):
self.btDialog.scanBtn.setEnabled(True)
def btScanError(self):
print('Bluetooth scan error')
sys.exit()
def startRMS(self, device):
self.cu = ControlUnit(device, timeout = 1.0)
self.cuVersion = self.cu.version()
self.initUI()
def initUI(self):
self.startLights = StartLights()
rectDesktop = app.desktop().availableGeometry()
self.startLights.resize(rectDesktop.width()/2, (rectDesktop.width()/2)/5)
self.setWindowTitle('Race Management System V1.0 CU Version:' + str(self.cuVersion, 'utf-8'))
self.rmsframe = RmsFrame(self.cu)
self.startLights.spacekey.activated.connect(self.rmsframe.racestart)
self.setCentralWidget(self.rmsframe)
def run(self):
last = None
while True:
if self.shutdown:
break
try:
data = self.cu.request()
app.processEvents()
if data == last:
continue
elif isinstance(data, ControlUnit.Status):
self.handle_status(data)
elif isinstance(data, ControlUnit.Timer):
self.handle_timer(data)
else:
pass
last = data
#Reset sleepcounter if run worked
self.cuoffcounter=0
#Handle Exception
except carreralib.connection.TimeoutError:
if self.cuoffcounter ==0:
print('Missing signal from CU')
if self.cuoffcounter < 30:
time.sleep(1)
self.cuoffcounter+=1
pass
else:
raise
except Exception:
raise
sys.exit()
def handle_status(self, status):
if status.start > 0 and status.start <= 7:
self.startLights.show()
if status.start == 1 or status.start == 2:
self.startLights.lightOne.setOn(True)
if status.start == 1 or status.start == 3:
self.startLights.lightTwo.setOn(True)
audio.play("beeplow")
if status.start == 1 or status.start == 4:
self.startLights.lightThree.setOn(True)
audio.play("beeplow")
if status.start == 1 or status.start == 5:
self.startLights.lightFour.setOn(True)
audio.play("beeplow")
if status.start == 1 or status.start == 6:
self.startLights.lightFive.setOn(True)
audio.play("beeplow")
if status.start == 2 or status.start == 7:
if status.start == 7:
self.startLights.lightOne.setOn(False)
self.startLights.lightTwo.setOn(False)
self.startLights.lightThree.setOn(False)
self.startLights.lightFour.setOn(False)
self.startLights.lightFive.setOn(False)
audio.play("beephigh")
else:
self.startLights.hide()
for driver, fuel in zip(self.rmsframe.driverArr, status.fuel):
if not driver.fuellevel == fuel and driver.pit:
if fuel==15:
audio.play("last")
else:
audio.play("tank")
driver.fuellevel=fuel
for driver, pit in zip(self.rmsframe.driverArr, status.pit):
if pit and not driver.pit:
driver.pitcount += 1
driver.pit = pit
self.binmode = "{0:04b}".format(status.mode)
self.rmsframe.updateDisplay(self.binmode)
self.status = status
def handle_timer(self, timer):
driver = self.rmsframe.driverArr[timer.address]
driver.newlap(timer)
if self.rmsframe.start is None:
self.rmsframe.start = timer.timestamp
self.rmsframe.updateDisplay(None)
class CtrlDialog(QDialog):
def __init__(self, driverArr):
super().__init__()
self.driverArr = driverArr
self.setWindowTitle('Assign Controller')
self.vlayout = QVBoxLayout(self)
self.table = QTableWidget(6,2)
self.table.verticalHeader().hide()
self.vlayout.addWidget(self.table)
self.table.setHorizontalHeaderLabels(['Driver', 'Controller'])
for idx, driverObj in enumerate(driverArr):
if idx < 6:
ctrlCombobox = QComboBox()
for ctrlItem in range(1,7):
ctrlCombobox.addItem(str(ctrlItem))
self.table.setItem(idx,0, QTableWidgetItem(driverObj.name))
ctrlCombobox.setCurrentIndex(idx)
self.table.setCellWidget(idx,1, ctrlCombobox)
self.setCtrlBtn = QPushButton('Set Controllers')
self.closeBtn = QPushButton('Cancel')
self.hlayout = QHBoxLayout()
self.vlayout.addLayout(self.hlayout)
self.hlayout.addWidget(self.setCtrlBtn)
self.hlayout.addWidget(self.closeBtn)
self.setCtrlBtn.clicked.connect(self.setNewCtrl)
self.closeBtn.clicked.connect(self.reject)
def setNewCtrl(self):
self.newDriverArr = [None] * 8
for cellNum in range(0, 8):
if cellNum < 6:
self.newDriverArr[int(self.table.cellWidget(cellNum, 1).currentText()) - 1] = self.driverArr[cellNum]
self.driverArr[cellNum].setCtrlNum(int(self.table.cellWidget(cellNum, 1).currentText()))
else:
self.newDriverArr[cellNum] = self.driverArr[cellNum]
self.accept()
class QrCodeDialog(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('Show QRCode')
self.setupUI()
self.qr = QRCode(
version=1,
error_correction=None,
box_size=10,
border=4,
)
self.qr.add_data(self.get_lan_ip()+':'+PORT+'/')
self.qr.make(fit=True)
self.img = self.qr.make_image(fill_color="black", back_color="white")
def setupUI(self):
self.vlayout = QVBoxLayout(self)
self.selectRaceGroup = QGroupBox('Race')
self.raceLayout = QHBoxLayout()
self.selectRaceGroup.setLayout(self.raceLayout)
self.selectRaceCombo = QComboBox()
self.selectRaceCombo.addItems(['Timed', 'Laps'])
self.selectRaceCombo.currentIndexChanged.connect(self.changeRaceMode)
self.raceModeInput = QLineEdit()
self.raceModeInput.setMaxLength(4)
self.raceModeInput.setText('20')
self.raceModeLabel = QLabel()
self.vlayout.addWidget(self.selectRaceGroup)
self.raceLayout.addWidget(self.selectRaceCombo)
self.raceLayout.addWidget(self.raceModeInput)
self.raceLayout.addStretch(1)
self.raceLayout.addWidget(self.raceModeLabel)
self.selectRaceCombo.setCurrentIndex(1)
self.cancelBtn = QPushButton('Cancel')
self.cancelBtn.clicked.connect(self.close)
self.buttonLayout = QHBoxLayout()
self.vlayout.addLayout(self.buttonLayout)
self.buttonLayout.addWidget(self.startRaceBtn)
self.buttonLayout.addWidget(self.cancelBtn)
def get_interface_ip(ifname):
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(self.s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
self.ip = socket.gethostbyname(socket.gethostname())
if self.ip.startswith("127.") and os.name != "nt":
self.interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in self.interfaces:
try:
self.ip = get_interface_ip(ifname)
break
except IOError:
pass
return self.ifip
class RaceModeDialog(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('Set Race Mode')
self.labels = ['', 'Minutes', 'Laps']
self.setupUI()
def setupUI(self):
self.vlayout = QVBoxLayout(self)
self.selectRaceGroup = QGroupBox('Race')
self.raceLayout = QHBoxLayout()
self.selectRaceGroup.setLayout(self.raceLayout)
self.selectRaceCombo = QComboBox()
self.selectRaceCombo.addItems(['Timed', 'Laps'])
self.selectRaceCombo.currentIndexChanged.connect(self.changeRaceMode)
self.raceModeInput = QLineEdit()
self.raceModeInput.setMaxLength(4)
self.raceModeInput.setText('20')
self.raceModeLabel = QLabel()
self.vlayout.addWidget(self.selectRaceGroup)
self.raceLayout.addWidget(self.selectRaceCombo)
self.raceLayout.addWidget(self.raceModeInput)
self.raceLayout.addStretch(1)
self.raceLayout.addWidget(self.raceModeLabel)
self.selectRaceCombo.setCurrentIndex(1)
self.doPractice = QCheckBox('Practice')
self.doPractice.setChecked(False)
self.doPractice.stateChanged.connect(self.practiceEnable)
self.practiceCombo = QComboBox()
self.practiceCombo.addItems(['Open', 'Timed', 'Laps'])
self.practiceCombo.currentIndexChanged.connect(self.changePracticeMode)
self.practiceInput = QLineEdit()
self.practiceInput.setMaxLength(4)
self.practiceLabel = QLabel()
self.practiceCombo.setCurrentIndex(1)
self.doQuali = QCheckBox('Qualifying')
self.doQuali.setChecked(False)
self.doQuali.stateChanged.connect(self.qualiEnable)
self.qualiCombo = QComboBox()
self.qualiCombo.addItems(['Open', 'Timed', 'Laps'])
self.qualiCombo.currentIndexChanged.connect(self.changeQualiMode)
self.qualiInput = QLineEdit()
self.qualiInput.setMaxLength(4)
self.qualiLabel = QLabel()
self.qualiCombo.setCurrentIndex(1)
self.checkBoxhlayout = QHBoxLayout()
self.checkBoxhlayout.addWidget(self.doPractice)
self.checkBoxhlayout.addWidget(self.doQuali)
self.vlayout.addLayout(self.checkBoxhlayout)
self.practicehbox = QHBoxLayout()
self.practiceFrame = QGroupBox('Practice')
self.practiceFrame.setLayout(self.practicehbox)
self.qualihbox = QHBoxLayout()
self.qualiFrame = QGroupBox('Qualifying')
self.qualiFrame.setLayout(self.qualihbox)
self.practicehbox.addWidget(self.practiceCombo)
self.practicehbox.addWidget(self.practiceInput)
self.practicehbox.addStretch(1)
self.practicehbox.addWidget(self.practiceLabel)
self.qualihbox.addWidget(self.qualiCombo)
self.qualihbox.addWidget(self.qualiInput)
self.qualihbox.addStretch(1)
self.qualihbox.addWidget(self.qualiLabel)
self.vlayout.addWidget(self.practiceFrame)
self.vlayout.addStretch(1)
self.vlayout.addWidget(self.qualiFrame)
self.startRaceBtn = QPushButton('Start Race')
self.startRaceBtn.clicked.connect(self.accept)
self.cancelBtn = QPushButton('Cancel')
self.cancelBtn.clicked.connect(self.close)
self.buttonLayout = QHBoxLayout()
self.vlayout.addLayout(self.buttonLayout)
self.buttonLayout.addWidget(self.startRaceBtn)
self.buttonLayout.addWidget(self.cancelBtn)
def changeRaceMode(self, index):
self.raceModeLabel.setText(self.labels[index + 1])
def practiceEnable(self, state):
if state == Qt.Checked:
self.practiceFrame.show()
else:
self.practiceFrame.hide()
def changePracticeMode(self, index):
if index == 0:
self.practiceInput.hide()
else:
self.practiceInput.show()
self.practiceLabel.setText(self.labels[index])
def qualiEnable(self, state):
if state == Qt.Checked:
self.qualiFrame.show()
else:
self.qualiFrame.hide()
def changeQualiMode(self, index):
if index == 0:
self.qualiInput.hide()
else:
self.qualiInput.show()
self.qualiLabel.setText(self.labels[index])
def getRaceModeInfo(self):
self.raceModeDict = {}
if self.doPractice.isChecked():
self.raceModeDict['Practice'] = {}
self.raceModeDict['Practice']['amount'] = str(self.practiceInput.text())
self.raceModeDict['Practice']['mode'] = self.practiceCombo.currentText()
if self.doQuali.isChecked():
self.raceModeDict['Qualification'] = {}
self.raceModeDict['Qualification']['amount'] = str(self.qualiInput.text())
self.raceModeDict['Qualification']['mode'] = self.qualiCombo.currentText()
self.raceModeDict['Race'] = {}
self.raceModeDict['Race']['amount'] = str(self.raceModeInput.text())
self.raceModeDict['Race']['mode'] = self.selectRaceCombo.currentText()
return self.raceModeDict
class RmsFrame(QFrame):
def __init__(self, cu):
super().__init__()
self.cu = cu
self.session = RaceSession()
self.resetRMS()
self.buildframe()
self.nameBtn = {}
self.driverPos = {}
self.driverObj = {}
self.lapcount = {}
self.totalTime = {}
self.laptime = {}
self.bestlaptime = {}
self.fuelbar = {}
self.pits = {}
self.audio=Audio()
# QBAcolor = QByteArray()
# QBAcolor.append('color')
# self.animation = anim = QPropertyAnimation(self, QBAcolor, self)
# anim.setDuration(250)
# anim.setLoopCount(2)
# anim.setStartValue(QColor(230,230, 0))
# anim.setEndValue(QColor(0, 0, 0))
# anim.setKeyValueAt(0.5, QColor(150,100,0))
def buildframe(self):
self.vLayout = QVBoxLayout(self)
self.hBtnLayout = QHBoxLayout()
self.vLayout.addLayout(self.hBtnLayout)
# Add driver to grid
self.addDriverBtn = QPushButton('(A)dd Driver')
self.addDriverKey = QShortcut(QKeySequence("a"), self)
self.hBtnLayout.addWidget(self.addDriverBtn)
self.addDriverBtn.clicked.connect(self.addDriver)
self.addDriverKey.activated.connect(self.addDriver)
# Assign Controller
self.assignCtrlBtn = QPushButton('Assign Controller')
self.hBtnLayout.addWidget(self.assignCtrlBtn)
self.assignCtrlBtn.clicked.connect(self.openCtrlDialog)
# Setup a race
self.setupRace = QPushButton('Setup a Race')
self.hBtnLayout.addWidget(self.setupRace)
self.setupRace.clicked.connect(self.openRaceDlg)
# Code cars
self.codeBtn = QPushButton('(C)ode')
self.codeKey = QShortcut(QKeySequence("c"), self)
self.hBtnLayout.addWidget(self.codeBtn)
self.codeBtn.clicked.connect(self.pressCode)
self.codeKey.activated.connect(self.pressCode)
# Start pace car
self.paceBtn = QPushButton('(P)ace')
self.paceKey = QShortcut(QKeySequence("p"), self)
self.hBtnLayout.addWidget(self.paceBtn)
self.paceBtn.clicked.connect(self.setPace)
self.paceKey.activated.connect(self.setPace)
# set Speed
self.setSpeedBtn = QPushButton('Set (S)peed')
self.setSpeedKey = QShortcut(QKeySequence("s"), self)
self.hBtnLayout.addWidget(self.setSpeedBtn)
self.setSpeedBtn.clicked.connect(self.setSpeed)
self.setSpeedKey.activated.connect(self.setSpeed)
# set Brakes
self.setBrakeBtn = QPushButton('Set (B)rake')
self.setBrakeKey = QShortcut(QKeySequence("b"), self)
self.hBtnLayout.addWidget(self.setBrakeBtn)
self.setBrakeBtn.clicked.connect(self.setBrake)
self.setBrakeKey.activated.connect(self.setBrake)
# Set Fuel
self.setFuelBtn = QPushButton('Set (F)uel')
self.setFuelKey = QShortcut(QKeySequence("f"), self)
self.hBtnLayout.addWidget(self.setFuelBtn)
self.setFuelBtn.clicked.connect(self.setFuel)
self.setFuelKey.activated.connect(self.setFuel)
# Reset CU
self.resetBtn = QPushButton('(R)eset')
self.resetKey = QShortcut(QKeySequence("r"), self)
self.hBtnLayout.addWidget(self.resetBtn)
self.resetBtn.clicked.connect(self.resetRMS)
self.resetKey.activated.connect(self.resetRMS)
# Start Btn Layout
self.hStartBtnLayout = QHBoxLayout()
# Session Info
self.racemode = QLabel('No Race Started')
self.racemode.setAlignment(Qt.AlignCenter)
self.hStartBtnLayout.addWidget(self.racemode)
self.hStartBtnLayout.addStretch(1)
# Start/Pause Race Enter
self.startRaceBtn = QPushButton('Start Race or Enter changed Settings (Spacebar)')
self.startRaceBtn.clicked.connect(self.racestart)
self.spacekey = QShortcut(QKeySequence("Space"), self)
self.spacekey.activated.connect(self.racestart)
self.hStartBtnLayout.addWidget(self.startRaceBtn)
self.hStartBtnLayout.setAlignment(self.startRaceBtn, Qt.AlignHCenter)
self.hStartBtnLayout.addStretch(1)
# Hardware Info
self.pitLaneStatus = QLabel()
self.hStartBtnLayout.addWidget(QLabel('Pitlane'))
self.hStartBtnLayout.addWidget(self.pitLaneStatus)
self.fuelmode = QLabel()
self.hStartBtnLayout.addWidget(QLabel('Fuel Mode'))
self.hStartBtnLayout.addWidget(self.fuelmode)
self.lapCounter = QLabel()
self.hStartBtnLayout.addWidget(QLabel('Lap Counter'))
self.hStartBtnLayout.addWidget(self.lapCounter)
self.vLayout.addLayout(self.hStartBtnLayout)
self.vLayout.setAlignment(self.hStartBtnLayout, Qt.AlignTop)
# self.sepline = QFrame()
# self.sepline.setFrameShape(QFrame.HLine)
# self.sepline.setFrameShadow(QFrame.Sunken)
# self.vLayout.addWidget(self.sepline)
# self.vLayout.setAlignment(self.sepline, Qt.AlignTop)
# Driver Grid
self.vLayout.addLayout(self.buildGrid())
# Session Info
# self.racemode = QLabel('No Race Started')
# self.racemode.setAlignment(Qt.AlignCenter)
#self.racemode.setStyleSheet("QLabel{ background-color: grey; center; color: blue; font: 30pt}")
#self.vLayout.addWidget(self.racemode)
#self.vLayout.setAlignment(self.racemode, Qt.AlignBottom)
def buildGrid(self):
self.mainLayout = QGridLayout()
self.mainLayout.setSpacing(2)
self.mainLayout.setHorizontalSpacing(5)
self.headerFont = QFont()
self.headerFont.setPointSize(14)
self.headerFont.setBold(True)
self.labelArr = [
#'Pos',
'Position', 'Total', 'Name', 'Laps', 'Laptime', 'Best Lap', 'Fuel', 'Pits']
for index, label in enumerate(self.labelArr):
self.headerLabel = QLabel(label)
self.headerLabel.setFont(self.headerFont)
self.mainLayout.addWidget(self.headerLabel, 0 , index, Qt.AlignHCenter)
self.mainLayout.setColumnStretch(1, 1)
self.mainLayout.setColumnStretch(2, 1)
self.mainLayout.setColumnStretch(3, 2)
self.mainLayout.setColumnStretch(4, 3)
self.mainLayout.setColumnStretch(5, 3)
self.mainLayout.setColumnStretch(6, 2)
self.mainLayout.setColumnStretch(7, 1)
return self.mainLayout
def openCtrlDialog(self):
self.ctrlDialog = CtrlDialog(self.driverArr)
if self.ctrlDialog.exec_():
self.driverArr = self.ctrlDialog.newDriverArr
#Prepare Race and open dialog
def openRaceDlg(self):
# Refuel all cars to same amount
self.setFuel()
time.sleep(0.5)
self.racestart()
self.setupRaceDlg = RaceModeDialog()
self.session.session = None
self.session.type = None
if self.setupRaceDlg.exec_():
for driver in self.driverArr:
driver.bestLapTime = None
driver.time = None
driver.lapcount = 0
driver.pitcount = 0
self.session.setRace(self.setupRaceDlg.getRaceModeInfo())
self.racemode.setText(self.session.session + ' ' + str(self.session.amount) + ' ' + self.session.type)
self.clearCU()
self.racestart()
time.sleep(0.5)
self.racestart()
else:
self.setupRaceDlg.close()
def getColor(self):
if self.mainLayout.itemAtPosition(1, 1):
return self.mainLayout.itemAtPosition(1, 1).widget().palette().text()
else:
return None
def setColor(self, color):
PBwidget = self.mainLayout.itemAtPosition(1, 1).widget()
palette = PBwidget.palette()
palette.setColor(PBwidget.foregroundRole(), color)
PBwidget.setFlat(True)
PBwidget.setAutoFillBackground(True)
PBwidget.setPalette(palette)
color = pyqtProperty(QColor, getColor, setColor)
def addDriver(self):
driverRow = self.mainLayout.rowCount()
if driverRow > 6:
return
driver = self.driverArr[driverRow - 1]
self.posFont = QFont()
self.posFont.setPointSize(50)
self.posFont.setBold(True)
self.driverPos[driverRow] = QLabel('#'+str(driver.CtrlNum))
self.driverPos[driverRow].setStyleSheet("QLabel{ border-color: black; background-color: black; color: yellow}")
self.driverPos[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.driverPos[driverRow].setFont(self.posFont)
self.mainLayout.addWidget(self.driverPos[driverRow], driverRow ,0)
self.nameBtn[driverRow] = driver.getNameBtn()
self.nameBtn[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.mainLayout.addWidget(self.nameBtn[driverRow], driverRow ,2)
#Object Driver
self.driverObj[driverRow] = driver
self.nameBtn[driverRow].clicked.connect(lambda: self.changeDriver(self.nameBtn[driverRow], self.driverObj[driverRow]))
self.lapcount[driverRow] = driver.getLapCountLCD()
self.lapcount[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.mainLayout.addWidget(self.lapcount[driverRow], driverRow, 3)
self.totalFont = QFont()
self.totalFont.setPointSize(30)
self.totalFont.setBold(True)
self.totalTime[driverRow] = QLabel('--:---')
self.totalTime[driverRow].setStyleSheet("QLabel{ border-color: black; background-color: black; color:yellow}")
self.totalTime[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.totalTime[driverRow].setFont(self.totalFont)
self.mainLayout.addWidget(self.totalTime[driverRow], driverRow, 1)
self.laptime[driverRow] = driver.getLapLCD()
self.laptime[driverRow].setDigitCount(6)
self.laptime[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.mainLayout.addWidget(self.laptime[driverRow], driverRow, 4)
self.bestlaptime[driverRow] = driver.getBestLapLCD()
self.bestlaptime[driverRow].setDigitCount(6)
self.bestlaptime[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.mainLayout.addWidget(self.bestlaptime[driverRow], driverRow, 5)
self.fuelbar[driverRow] = driver.getFuelBar()
self.fuelbar[driverRow].setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.mainLayout.addWidget(self.fuelbar[driverRow], driverRow, 6)
self.pits[driverRow] = driver.getPits()
self.pits[driverRow].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
self.mainLayout.addWidget(self.pits[driverRow], driverRow, 7)
def racestart(self):
self.cu.start()
# self.mainLayout.itemAtPosition(1, 5).widget().setPits('Pit')
# self.mainLayout.itemAtPosition(1, 5).widget().setPits('Track')
def resetRMS(self):
if hasattr(self, 'driverArr'):
for driverObj in self.driverArr:
driverObj.deleteLater()
self.start = None
#Setup of the table with Informations of the Drivers
self.driverArr = [RmsDriver(num) for num in range(1, 9)]
self.clearCU()
if hasattr(self, 'mainLayout'):
while True:
widgetToRemove = self.mainLayout.takeAt(0)
if widgetToRemove == None:
break
widgetToRemove.widget().deleteLater()
racemode = self.vLayout.takeAt(3)
mainItem = self.vLayout.takeAt(2)
self.vLayout.removeItem(racemode)
self.vLayout.removeItem(mainItem)
mainItem.deleteLater()
self.vLayout.addLayout(self.buildGrid())
self.vLayout.addWidget(self.racemode)
def clearCU(self):
# discard remaining timer messages
status = self.cu.request()
while not isinstance(status, ControlUnit.Status):
status = self.cu.request()
self.status = status
# reset cu timer
self.cu.reset()
def pressCode(self):
print('press Code')
self.cu.request(b'T8')
def setFuel(self):
print('set fuel')
self.cu.request(b'T7')
def setPace(self):
print('pace car')
self.cu.request(b'T1')
def setSpeed(self):
print('set speed')
self.cu.request(b'T5')
def setBrake(self):
print('set brake')
self.cu.request(b'T6')
def changeDriver(self, driverButton, driverObj):
self.driverChangeText = QInputDialog.getText(self, 'Change driver name', 'Driver Name', 0, driverButton.text().split('\n')[0])
if self.driverChangeText[1] == True:
driverButton.setText(self.driverChangeText[0])
driverObj.name = self.driverChangeText[0]
def updateDisplay(self, binMode):
if binMode != None:
if binMode[2] == '1':
self.fuelmode.setText('Real')
elif binMode[3] == '1':
self.fuelmode.setText('On')
elif binMode[3] == '0':
self.fuelmode.setText('Off')
if binMode[1] == '1':
self.pitLaneStatus.setText('Exists')
else:
self.pitLaneStatus.setText('Missing')
if binMode[0] == '1':
self.lapCounter.setText('Exists')
else:
self.lapCounter.setText('Missing')
driversInPlay = [driver for driver in self.driverArr if driver.time]
##### changed from +1 >
if len(driversInPlay) +1 > self.mainLayout.rowCount():
self.addDriver()
# Refresh positions and leading time
#Sorted by position
for pos, driver in enumerate(sorted(driversInPlay, key=posgetter), start=1):
#Calculate Position and Gap
if pos == 1:
if hasattr(self, 'leader') and self.leader != driver:
print('pos change')
# self.animation.start()
self.leader = driver
t = formattime(driver.time - self.start, True)
elif driver.lapcount == self.leader.lapcount:
t = '+%ss' % formattime(driver.time - self.leader.time, False)
else:
gap = self.leader.lapcount - driver.lapcount
t = '+%d Lap%s' % (gap, 's' if gap != 1 else '')
#Position to qt app and web app
self.driverPos[pos].setText('#'+str(pos))
web.position[driver.CtrlNum]=pos
web.posdriverctrl[pos]=driver.CtrlNum
#Totaltime
self.totalTime[pos].setText(driver.name+'\n'+t)
web.totaltime[driver.CtrlNum]=t
web.time[driver.CtrlNum]=driver.time
#Sorted by Controller number
for pos, driver in enumerate(sorted(driversInPlay, key=CtrlNum), start=1):
#Name
self.nameBtn[pos].setText(driver.name)
web.name[driver.CtrlNum]=driver.name
if self.session.lapcountup or self.session.amount == None:
self.lapcount[pos].display(driver.lapcount)
web.laps[driver.CtrlNum]=driver.lapcount
else:
self.lapcount[pos].display(self.session.amount-driver.lapcount)
web.laps[driver.CtrlNum]=self.session.amount-driver.lapcount
#Laptime to qt app and web app
self.laptime[pos].display(formattime(driver.lapTime, False))
web.laptime[driver.CtrlNum]=formattime(driver.lapTime, True)
#Best Lap time to qt app and web app
self.bestlaptime[pos].display(formattime(driver.bestLapTime, False))
web.bestlaptime[driver.CtrlNum]=formattime(driver.bestLapTime, True)
#Fuelbar
self.fuelbar[pos].setText('⣿'*min(5,max(driver.fuellevel-10,0))+'\n'+'⣿'*min(5,max(driver.fuellevel-5,0))+'\n'+'⣿'*min(5,max(driver.fuellevel,0)))
#Make the dots for the web app
if driver.fuellevel > 5:
web.fuellevellights1[driver.CtrlNum]='⣿⣿⣿⣿⣿'
web.fuellevellights2[driver.CtrlNum]='⣿'*(driver.fuellevel-5)
self.fuelbar[pos].setStyleSheet("QLabel{ border-color: black; background-color: black; color: #00CB14}")
else:
web.fuellevellights1[driver.CtrlNum]='⣿'*driver.fuellevel
web.fuellevellights2[driver.CtrlNum]=''
self.fuelbar[pos].setStyleSheet("QLabel{ border-color: black; background-color: black; color: red}")
web.fuellevel[driver.CtrlNum]=driver.fuellevel
#self.fuelbar[pos].setStyleSheet("QProgressBar{ color: white; background-color: black; text-align: center}\
# QProgressBar::chunk { background: qlineargradient(x1: 1, y1: 0.5, x2: 0, y2: 0.5, stop: 0 #00AA00, stop: " + str(0.92 - (1 / (driver.fuellevel))) + " #22FF22, stop: " + str(0.921 - (1 / (driver.fuellevel))) + " #22FF22, stop: " + str(1.001 - (1 / (driver.fuellevel))) + " red, stop: 1 #550000); }")
#Pitcount
self.pits[pos].display(driver.pitcount)
web.pits[driver.CtrlNum]=driver.pitcount
web.driversinplay=len(driversInPlay)
#Race controlling
if hasattr(self, 'leader') and self.session.session != None:
# Check if race is over
if self.session.type != None:
self.racemode.setText(self.session.session + ' ' + str(self.session.amount) + ' ' + self.session.type)
if self.session.type == 'Laps':
self.session.lapcountup=False
# Race ends after leading car finished and all other cars passed the start finish as well
if self.leader.lapcount >= self.session.amount:
self.end=self.leader.time
self.racestop=True
for driver in self.driverArr:
if driver.time and driver.time < self.end:
self.racestop=False
if self.racestop:
self.racestart()
self.session.saveSessionData(driversInPlay)
self.clearCU()
self.session.sessionOver()
elif self.session.type == 'Timed':
self.session.lapcountup=True
if self.leader.time:
if self.leader.time - self.start > self.session.amount * 60000:
self.end=self.leader.time
self.racestop=True
for driver in self.driverArr:
if driver.time and driver.time < self.end:
self.racestop=False
if self.racestop:
self.racestart()
self.session.saveSessionData(driversInPlay)
self.clearCU()
self.session.sessionOver()
elif self.session.type == None:
self.session.lapcountup=True
self.session.session = None
self.showLeaderboard()
#Show Leaderboard at the end
def showLeaderboard(self):
self.leaderBoard = LBDialog(self.session.leaderboard)
self.leaderBoard.show()
class RaceSession(QObject):
def __init__(self):
super().__init__()
self.amount = None
self.session = None
self.sessionSteps = ['Practice', 'Qualification', 'Race']
# Just for displaying the remaining laps
self.lapcountup=True