-
Notifications
You must be signed in to change notification settings - Fork 0
/
raceclock.py
149 lines (116 loc) · 5.36 KB
/
raceclock.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
#!/usr/bin/env python3
"""Race Clock Classes
This module implements the digital clock used to display current race time.
Upon instantiation, we also validate that the current system time is in sync
with Internet (cellphone) time.
"""
import ntplib
from PyQt5.QtCore import QDate, QDateTime, QTime, QTimer
from PyQt5.QtWidgets import QFrame, QLCDNumber, QMessageBox
import common
from defaults import NTP_SERVER_NUM_CHECKS
__copyright__ = '''
Copyright (C) 2018-2019 Andrew Chew
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/>.
'''
__author__ = common.AUTHOR
__credits__ = common.CREDITS
__license__ = common.LICENSE
__version__ = common.VERSION
__maintainer__ = common.MAINTAINER
__email__ = common.EMAIL
__status__ = common.STATUS
# Use NTP pool for our time server.
NTP_SERVER = 'pool.ntp.org'
# NCNCA race officials seem to like reporting two significant digits of fractional seconds.
ACCEPTABLE_OFFSET = 0.01
class RaceClockException(BaseException):
"""Exceptions generated by this module."""
class DigitalClock(QLCDNumber):
"""Old-fashioned 7-segment display digital clock showing current time."""
def __init__(self, modeldb, validate_clock=True, parent=None):
"""Initialize the DigitalClock instance."""
super().__init__(8, parent=parent)
self.modeldb = modeldb
self.preferences = None
self.setFrameShape(QFrame.NoFrame)
self.setSegmentStyle(QLCDNumber.Filled)
self.timer = QTimer()
self.timer.timeout.connect(self.update)
self.update()
self.timer.start(100)
self.setMinimumHeight(48)
if validate_clock:
self.validate_clock()
def update(self):
"""Update text on the LCD display."""
race_table_model = self.modeldb.race_table_model
if self.preferences and self.preferences.wall_times_checkbox.isChecked():
msecs = race_table_model.get_wall_time_msecs()
else:
msecs = race_table_model.get_reference_msecs()
datetime = QDateTime(QDate(1, 1, 1), QTime(0, 0)).addMSecs(msecs)
if datetime.time().second() % 2:
datetime_string = 'h:mm ss'
else:
datetime_string = 'h:mm:ss'
if (self.preferences and
self.preferences.wall_times_checkbox.isChecked() and
not self.preferences.h24_wall_times_checkbox.isChecked()):
self.setDigitCount(11)
datetime_string += ' a'
else:
self.setDigitCount(8)
text = datetime.toString(datetime_string)
self.display(text)
def validate_clock(self):
"""Check against an NTP server to see if our system time is in sync.
San Bruno Hill Climb 2019's mysterious ~40s offset issue. Never forget!
"""
err_text = None
ntp_client = ntplib.NTPClient()
# Try NTP server clock check some number of times, and take the average.
total = 0.0
num = 0
for _ in range(NTP_SERVER_NUM_CHECKS):
try:
response = ntp_client.request(NTP_SERVER)
total += response.offset
num += 1
except Exception as e: #pylint: disable=broad-except
reason = str(e)
if num == 0:
err_text = ('Failed to validate clock against NTP server ' + NTP_SERVER + '.\n\n' +
'Reason: %s' % reason)
else:
average = total / num
if average > ACCEPTABLE_OFFSET:
err_text = ('System time seems to be off by %.2f seconds! ' % average +
'Results were averaged across %s checks.' % num +
'Please check system settings to ensure that the clock is being ' +
'synchronized with an internet time server.')
if not err_text:
return
if QMessageBox.warning(self, 'Warning', err_text,
QMessageBox.Abort | QMessageBox.Ignore,
QMessageBox.Abort) == QMessageBox.Abort:
raise RaceClockException('Aborting due to system time validation failure.')
message = ("Recorded times will not be consistent with officials' times if Internet " +
"(cellphone) time is used.\n\nYOU HAVE BEEN WARNED!")
QMessageBox.warning(self, 'Warning', message)
def connect_preferences(self, preferences):
"""Connect preferences signals to the various slots that care."""
self.preferences = preferences
preferences.digital_clock_checkbox.stateChanged.connect(self.setVisible)
self.setVisible(preferences.digital_clock_checkbox.checkState())
preferences.wall_times_checkbox.stateChanged.connect(self.update)
preferences.h24_wall_times_checkbox.stateChanged.connect(self.update)