forked from esitarski/CrossMgr
/
RaceResult.py
452 lines (375 loc) · 11.9 KB
/
RaceResult.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
import socket
import sys
import six
import time
import datetime
import atexit
import subprocess
import threading
import re
import wx
import wx.lib.newevent
import Utils
import Model
from threading import Thread as Process
from six.moves.queue import Queue, Empty
import JChip
from RaceResultImport import parseTagTime
from Utils import logCall, logException
ChipReaderEvent, EVT_CHIP_READER = JChip.ChipReaderEvent, JChip.EVT_CHIP_READER
readerEventWindow = None
def sendReaderEvent( tagTimes ):
if tagTimes and readerEventWindow:
wx.PostEvent( readerEventWindow, ChipReaderEvent(tagTimes = tagTimes) )
EOL = '\r\n' # RaceResult delimiter
len_EOL = len(EOL)
DEFAULT_PORT = 3601
DEFAULT_HOST = '127.0.0.1' # Port to connect to the RaceResult receiver.
q = None
shutdownQ = None
listener = None
def socketSend( s, message ):
if not isinstance(message, bytes):
message = message.encode()
sLen = 0
while sLen < len(message):
sLen += s.send( message[sLen:] )
def socketReadDelimited( s, delimiter=EOL ):
buffer = s.recv( 4096 ).decode()
while not buffer.endswith( delimiter ):
more = s.recv( 4096 ).decode()
if more:
buffer += more
else:
break
return buffer
def AutoDetect( raceResultPort=3601, callback=None ):
''' Search ip addresses adjacent to the computer in an attempt to find the reader. '''
ip = [int(i) for i in Utils.GetDefaultHost().split('.')]
j = 0
for i in range(14):
j = -j if j > 0 else -j + 1
ipTest = list( ip )
ipTest[-1] += j
if not (0 <= ipTest[-1] < 256):
continue
raceResultHost = '.'.join( '{}'.format(v) for v in ipTest )
if callback:
if not callback( '{}:{}'.format(raceResultHost,raceResultPort) ):
return None
try:
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.settimeout( 0.5 )
s.connect( (raceResultHost, raceResultPort) )
except Exception as e:
continue
cmd = 'GETSTATUS'
try:
socketSend( s, u'{}{}'.format(cmd, EOL) )
except Exception as e:
continue
try:
buffer = socketReadDelimited( s )
except Exception as e:
continue
try:
s.close()
except Exception as e:
pass
if buffer.startswith( '{};'.format(cmd) ):
return raceResultHost
return None
# if we get the same time, make sure we give it a small offset to make it unique, but preserve the order.
tSmall = datetime.timedelta( seconds = 0.000001 )
statusFields = (
'Date', 'Time', 'HasPower', 'Antennas', 'IsInTimingMode', 'FileNumber', 'GPSHasFix',
)
reNonDigit = re.compile( '[^0-9]+' )
def Server( q, shutdownQ, HOST, PORT, startTime ):
global readerEventWindow
if not readerEventWindow:
readerEventWindow = Utils.mainWin
timeoutSecs = 5
delaySecs = 3
readerTime = None
readerComputerTimeDiff = None
s = None
passingsCur = 0
status = None
startOperation = None
def qLog( category, message ):
q.put( (category, message) )
Utils.writeLog( u'RaceResult: {}: {}'.format(category, message) )
def keepGoing():
try:
shutdownQ.get_nowait()
except Empty:
return True
return False
def autoDetectCallback( m ):
qLog( 'autodetect', u'{} {}'.format(_('Checking'), m) )
return keepGoing()
def makeCall( s, message ):
cmd = message.split(';', 1)[0]
qLog( 'command', u'sending: {}'.format(message) )
try:
socketSend( s, u'{}{}'.format(message,EOL) )
buffer = socketReadDelimited( s )
except Exception as e:
qLog( 'connection', u'{}: {}: "{}"'.format(cmd, _('Connection failed'), e) )
raise ValueError
if not buffer.startswith( u'{};'.format(cmd) ):
qLog( 'command', u'{}: {} "{}"'.format(cmd, _('Unexpected return'), buffer) )
raise ValueError
return buffer
while keepGoing():
if s:
try:
s.shutdown( socket.SHUT_RDWR )
s.close()
except Exception as e:
pass
time.sleep( delaySecs )
#-----------------------------------------------------------------------------------------------------
qLog( 'connection', u'{} {}:{}'.format(_('Attempting to connect to RaceResult reader at'), HOST, PORT) )
try:
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.settimeout( timeoutSecs )
s.connect( (HOST, PORT) )
except Exception as e:
qLog( 'connection', u'{}: {}'.format(_('Connection to RaceResult reader failed'), e) )
s, status, startOperation = None, None, None
qLog( 'connection', u'{}'.format(_('Attempting AutoDetect...')) )
HOST_AUTO = AutoDetect( callback = autoDetectCallback )
if HOST_AUTO:
qLog( 'connection', u'{}: {}'.format(_('AutoDetect RaceResult at'), HOST_AUTO) )
HOST = HOST_AUTO
else:
time.sleep( delaySecs )
continue
#-----------------------------------------------------------------------------------------------------
crossMgrMinProtocol = (1,2)
crossMgrMinProtocolStr = '.'.join('{}'.format(p) for p in crossMgrMinProtocol)
try:
buffer = makeCall( s, 'GETPROTOCOL' )
except ValueError as e:
logException( e, sys.exc_info() )
continue
current, minSupported, maxSupported = [f.strip() for f in buffer.strip().split(';')[1:]]
if tuple(int(i) for i in maxSupported.split('.')) < crossMgrMinProtocol:
qLog(
'connection',
u'{}. {} >={}. {} {}.'.format(
_("RaceResult requires Firmware Upgrade"),
_("CrossMgr requires PROTOCOL"), crossMgrMinProtocolStr,
_("RaceResult supports"), maxSupported,
)
)
time.sleep( delaySecs )
continue
try:
buffer = makeCall( s, 'SETPROTOCOL;{}'.format(maxSupported) )
except ValueError:
continue
qLog( 'status', u'{}'.format(buffer.strip()) )
try:
buffer = makeCall( s, 'GETSTATUS' )
except ValueError:
continue
fields = [f.strip() for f in buffer.strip().split(';')]
status = zip( statusFields, fields[1:] )
for name, value in status:
qLog( 'status', u'{}: {}'.format(name, value) )
#-----------------------------------------------------------------------------------------------------
try:
buffer = makeCall( s, 'STOPOPERATION' )
except ValueError:
continue
#-----------------------------------------------------------------------------------------------------
try:
buffer = makeCall( s, 'SETTIME;{}'.format(datetime.datetime.now().strftime('%Y-%m-%d;%H:%M:%S.%f')[:-3]) )
except ValueError:
continue
#-----------------------------------------------------------------------------------------------------
try:
buffer = makeCall( s, 'STARTOPERATION' )
except ValueError:
continue
qLog( 'status', u'{}'.format(buffer.strip()) )
#-----------------------------------------------------------------------------------------------------
try:
buffer = makeCall( s, 'GETTIME' )
except ValueError:
continue
try:
dt = reNonDigit.sub(' ', buffer).strip()
fields[-1] = (fields[-1] + '000000')[:6] # Pad with zeros to convert to microseconds.
readerTime = datetime.datetime( *[int(f) for f in dt.split()] )
readerComputerTimeDiff = datetime.datetime.now() - readerTime
except Exception as e:
qLog( 'command', u'GETTIME: {} "{}" "{}"'.format(_('Unexpected return'), buffer, e) )
continue
while keepGoing():
#-------------------------------------------------------------------------------------------------
cmd = 'PASSINGS'
try:
socketSend( s, u'{}{}'.format(cmd, EOL) )
buffer = socketReadDelimited( s )
if buffer.startswith( '{};'.format(cmd) ):
fields = buffer.split(';')
try:
passingsText = fields[1]
except Exception as e:
qLog( 'command', u'{}: {} "{}" "{}"'.format(cmd, _('Unexpected return'), buffer, e) )
continue
try:
passingsNew = int( reNonDigit.sub(' ', passingsText).strip() )
except Exception as e:
qLog( 'command', u'{}: {} "{}" "{}"'.format(cmd, _('Unexpected return'), buffer, e) )
continue
else:
qLog( 'command', u'{}: {} "{}"'.format(cmd, _('Unexpected return'), buffer) )
continue
except Exception as e:
qLog( 'connection', u'{}: {}: "{}"'.format(cmd, _('Connection failed'), e) )
break
if passingsNew != passingsCur:
if passingsNew < passingsCur:
passingsCur = 0
tagTimes = []
errors = []
times = set()
passingsCount = passingsNew - passingsCur
#---------------------------------------------------------------------------------------------
cmd = '{}:{}'.format(passingsCur+1, passingsCount) # Add one as the reader counts inclusively.
qLog( 'command', u'sending: {} ({}+{}={} passings)'.format(cmd, passingsCur, passingsCount, passingsNew) )
try:
# Get the passing data.
socketSend( s, u'{}{}'.format(cmd, EOL) )
except Exception as e:
qLog( 'connection', u'cmd={}: {}: "{}"'.format(cmd, _('Connection failed'), e) )
break
tagReadSuccess = False
try:
readAllPassings = False
while not readAllPassings:
response = socketReadDelimited( s )
sStart = 0
while 1:
sEnd = response.find( EOL, sStart )
if sEnd < 0:
break
if sEnd == sStart: # An empty passing indicates this is the last one.
readAllPassings = True
break
line = response[sStart:sEnd]
sStart = sEnd + len_EOL
tag, t = parseTagTime(line, passingsCur+len(tagTimes), errors)
if tag is None or t is None:
qLog( 'command', u'{}: {} "{}"'.format(cmd, _('Unexpected return'), line) )
continue
t += readerComputerTimeDiff
while t in times: # Ensure no equal times.
t += tSmall
times.add( t )
tagTimes.append( (tag, t) )
tagReadSuccess = True
except Exception as e:
qLog( 'connection', u'cmd={}: {}: "{}"'.format(cmd, _('Connection failed'), e) )
sendReaderEvent( tagTimes )
for tag, t in tagTimes:
q.put( ('data', tag, t) )
passingsCur += len(tagTimes)
if not tagReadSuccess:
break
time.sleep( delaySecs )
# Final cleanup.
cmd = 'STOPOPERATION'
try:
socketSend( s, u'{}{}'.format(cmd, EOL) )
buffer = socketReadDelimited( s )
s.shutdown( socket.SHUT_RDWR )
s.close()
except:
pass
def GetData():
data = []
while 1:
try:
data.append( q.get_nowait() )
except (Empty, AttributeError):
break
return data
def StopListener():
global q
global listener
global shutdownQ
# Terminate the server process if it is running.
# Add a number of shutdown commands as we may check a number of times.
if listener:
for i in range(32):
shutdownQ.put( 'shutdown' )
listener.join()
listener = None
# Purge the queues.
while q:
try:
q.get_nowait()
except Empty:
q = None
break
shutdownQ = None
def IsListening():
return listener is not None
def StartListener( startTime=datetime.datetime.now(), HOST=None, PORT=None ):
global q
global shutdownQ
global listener
StopListener()
if Model.race:
HOST = (HOST or Model.race.chipReaderIpAddr)
PORT = (PORT or Model.race.chipReaderPort)
q = Queue()
shutdownQ = Queue()
listener = Process( target = Server, args=(q, shutdownQ, HOST, PORT, startTime) )
listener.name = 'RaceResult Listener'
listener.daemon = True
listener.start()
@atexit.register
def CleanupListener():
global shutdownQ
global listener
if listener and listener.is_alive():
shutdownQ.put( 'shutdown' )
listener.join()
listener = None
if __name__ == '__main__':
def doTest():
try:
StartListener( HOST='127.0.0.1', PORT=DEFAULT_PORT )
count = 0
while 1:
time.sleep( 1 )
sys.stdout.write( '.' )
messages = GetData()
if messages:
sys.stdout.write( '\n' )
for m in messages:
if m[0] == 'data':
count += 1
print( '{}: {}, {}'.format(count, m[1], m[2].time()) )
elif m[0] == 'status':
print( 'status: {}'.format(m[1]) )
elif m[0] == 'passings':
print( 'passings: {}'.format(m[1]) )
elif m[0] == 'command':
print( 'command: {}'.format(m[1]) )
else:
print( 'other: {}, {}'.format(m[0], ', '.join('"{}"'.format(s) for s in m[1:])) )
sys.stdout.flush()
except KeyboardInterrupt:
return
t = threading.Thread( target=doTest )
t.daemon = True
t.run()
time.sleep( 1000000 )