forked from esitarski/CrossMgr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JChip.py
435 lines (366 loc) · 11.7 KB
/
JChip.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
from __future__ import print_function
import socket
import six
import sys
import time
import datetime
import atexit
import math
import re
import os
import wx
import wx.lib.newevent
import Utils
import Model
import select
from threading import Thread as Process
from six.moves.queue import Queue, Empty
ChipReaderEvent, EVT_CHIP_READER = wx.lib.newevent.NewEvent()
stripLeadingZeros = Utils.stripLeadingZeros
readerEventWindow = None
def sendReaderEvent( tagTimes ):
if tagTimes and readerEventWindow:
wx.PostEvent( readerEventWindow, ChipReaderEvent(tagTimes = tagTimes) )
combine = datetime.datetime.combine
reTimeChars = re.compile( '^\d\d:\d\d:\d\d\.\d+' )
CR = u'\r' # JChip delimiter
dateToday = datetime.date.today()
tSameCount = 0
tLast = None
def reset( raceDate = None ):
global dateToday
global tSameCount
global tLast
dateToday = raceDate or datetime.date.today()
tLast = None
tSameCount = 0
DEFAULT_HOST = '0.0.0.0' # Listen to all available network cards on this computer.
DEFAULT_PORT = int(os.environ.get('JCHIP_REMOTE_PORT',53135))
q = None
shutdownQ = None
listener = None
def socketSend( s, message ):
sLen = 0
while sLen < len(message):
sLen += s.send( message[sLen:].encode() )
def socketByLine( s ):
buffer = s.recv( 4096 ).decode()
while 1:
nl = buffer.find( CR )
if nl >= 0:
yield buffer[:nl+1]
buffer = buffer[nl+1:]
else:
more = s.recv( 4096 ).decode()
if more:
buffer = buffer + more
else:
break
if buffer:
yield buffer
# 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.00001 )
tDay = datetime.timedelta( days = 1 )
def parseTime( tStr, day = 0 ):
global dateToday
global tLast
global tSameCount
hh, mm, ss = tStr.split(':')
t = combine(dateToday, datetime.time()) + datetime.timedelta(
seconds = (float(hh) * 60.0 * 60.0) + (float(mm) * 60.0) + float(ss) )
t += tDay * day
if tLast is None:
tLast = t - tSmall
# Add a small offset to equal times so the order is preserved.
if t == tLast:
tSameCount += 1
else:
tSameCount = 0
tLast = t
return t + tSmall * tSameCount if tSameCount > 0 else t
def safeRemove( lst, x ):
while 1:
try:
lst.remove( x )
except ValueError:
return
def safeAppend( lst, x ):
if x not in lst:
lst.append( x )
reUnprintable = re.compile( r'[\x00-\x19\x7f-\xff]' )
def formatAscii( s ):
r = []
charsPerLine = 40
for i in six.moves.range(0, len(s), charsPerLine):
line = s[i:i+charsPerLine]
r.append( ''.join( '.{}'.format(c) for c in reUnprintable.sub('.', line)) )
r.append( ''.join( '{:02x}'.format(ord(c)) for c in line ) )
return '\n'.join( r )
def Server( q, shutdownQ, HOST, PORT, startTime ):
global readerEventWindow
if not readerEventWindow:
readerEventWindow = Utils.mainWin
#-----------------------------------------------------
# Support multiple connections to a JChip client.
# If we get a Address Already in use, we wait some time and try again
#
while 1:
server = None
server = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking( 0 )
try:
server.bind((HOST, PORT))
except IOError as e:
if e.errno == 48:
server = None
time.sleep(2)
continue
else:
raise e
server.listen( 5 )
break
# List of ports for select.
inputs = [server]
outputs = []
#
# Read and write buffers and state for JChip readers.
#
readerReadStr, readerWriteStr, readerName, readerComputerTimeDiff, nameReader = {}, {}, {}, {}, {}
def closeReader( s ):
safeRemove( inputs, s )
safeRemove( outputs, s )
try:
del nameReader[readerName[s]]
except ValueError:
pass
for state in [readerReadStr, readerWriteStr, readerName, readerComputerTimeDiff]:
state.pop( s, None )
s.close()
def qLog( category, message ):
q.put( (category, message) )
Utils.writeLog( u'JChip: {}: {}'.format(category, message) )
while inputs:
# qLog( 'waiting', 'for communication' )
readable, writable, exceptional = select.select( inputs, outputs, inputs, 2 )
try:
# Check if we have been told to shutdown.
shutdownQ.get_nowait()
break
except Empty:
pass
# qLog( 'waiting', 'len(readable)=%d, len(writable)=%d, len(exceptional)=%d' % (len(readable), len(writable), len(exceptional) ) )
#----------------------------------------------------------------------------------
# Handle inputs.
#
for s in readable:
if s is server:
# This is the listener. Accept the connection from a JChip reader.
connCur, addr = s.accept()
connCur.setblocking( 0 )
inputs.append( connCur )
readerReadStr[connCur], readerWriteStr[connCur] = u'', u''
qLog( 'connection', 'established {}'.format(addr) )
continue
# This socket is a data socket. Get the data.
try:
data = s.recv( 4096 ).decode()
except Exception as e:
qLog( 'connection', 'error: {}'.format(e) )
data = None
if not data:
# No data - close this socket.
qLog( 'connection', 'disconnected: {}'.format(readerName.get(s, '<unknown>')) )
closeReader( s )
continue
# qLog( 'connection', 'recv: \n{}\n'.format( formatAscii(data) ) )
# Accumulate the data.
readerReadStr[s] += data
if not readerReadStr[s].endswith( CR ):
continue # Missing delimiter - need to get more data.
# The message is delimited. Process the messages.
tagTimes = []
lines = readerReadStr[s].split( CR )
readerReadStr[s] = ''
for line in lines:
line = line.strip()
if not line:
continue
try:
if line.startswith( 'D' ):
# The tag and time are always separated by at least one space.
iSpace = line.find( ' ' )
if iSpace < 0:
qLog( 'error', line.strip() )
continue
tag = line[2:iSpace] # Skip the D and first initial letter (always the same).
# Find the first colon of the time and parse the time working backwards.
iColon = line.find( ':' )
if iColon < 0:
qLog( 'error', line.strip() )
continue
m = reTimeChars.match( line[iColon-2:] )
if not m:
qLog( 'error', line.strip() )
continue
tStr = m.group(0)
# Find the second field separated by a space after the time.
# The second character of the field is the day count.
iSecondField = line.find( ' ', iColon ) + 1
if iSecondField >= 0:
try:
day = int(line[iSecondField+1:iSecondField+2])
except:
day = 0
try:
iDate = line.index( 'date=' ) + 5
YYYY, MM, DD = int(line[iDate:iDate+4]), int(line[iDate+4:iDate+6]), int(line[iDate+6:iDate+8])
if Model.race and Model.race.isRunning():
raceStartTime = Model.race.startTime
startDate = datetime.date( raceStartTime.year, raceStartTime.month, raceStartTime.day )
tagDate = datetime.date( YYYY, MM, DD )
day = (tagDate - startDate).days
except ValueError:
pass
t = parseTime( tStr, day )
t += readerComputerTimeDiff.get(s, datetime.timedelta())
tag = stripLeadingZeros(tag)
q.put( ('data', tag, t) )
tagTimes.append( (tag, t) )
elif line.startswith( 'N' ):
name = line[5:].strip() # Skip the cmd and current number of recorded times.
# Check if this reader is known to us already.
# If so, the reader has dropped its previous connection and is reconnecting.
# Close the previous connection as it is no longer needed.
if name in nameReader:
s_dropped = nameReader[name]
qLog( 'transmitting', '"{}" is reconnecting'.format(readerName[s]) )
closeReader( s_dropped )
readerName[s] = name
nameReader[name] = s
q.put( ('name', name) )
# Now, get the reader's current time.
cmd = u'GT'
qLog( 'transmitting', '{} command to "{}" (gettime)'.format(cmd, readerName[s]) )
readerWriteStr[s] += u'{}{}'.format(cmd, CR)
safeAppend( outputs, s )
elif line.startswith( 'GT' ):
tNow = datetime.datetime.now()
iStart = 3
hh, mm, ss, hs = [int(line[i:i+2]) for i in range(iStart, iStart + 4 * 2, 2)]
try:
iDate = line.index( 'date=' ) + 5
YYYY, MM, DD = int(line[iDate:iDate+4]), int(line[iDate+4:iDate+6]), int(line[iDate+6:iDate+8])
tJChip = datetime.datetime( YYYY, MM, DD, hh, mm, ss, hs * 10000 )
except ValueError:
tJChip = datetime.datetime.combine( tNow.date(), datetime.time(hh, mm, ss, hs * 10000) )
except Exception as e:
tJChip = datetime.datetime.combine( tNow.date(), datetime.time(hh, mm, ss, hs * 10000) )
readerComputerTimeDiff[s] = tNow - tJChip
qLog( 'getTime', '({})={:02d}:{:02d}:{:02d}.{:02d}'.format(line[2:].strip(), hh,mm,ss,hs) )
rtAdjust = readerComputerTimeDiff[s].total_seconds()
if rtAdjust > 0:
behindAhead = 'Behind'
else:
behindAhead = 'Ahead'
rtAdjust *= -1
qLog( 'timeAdjustment',
'"{}" is: {} {} (relative to computer)'.format(
readerName.get(s, '<<unknown>>'),
behindAhead,
Utils.formatTime(rtAdjust, True)
) )
# Send command to start sending data.
cmd = u'S0000'
qLog( 'transmitting', '{} command to "{}" (start transmission)'.format(
cmd, readerName.get(s, '<<unknown>>')) )
readerWriteStr[s] += u'{}{}'.format(cmd, CR)
safeAppend( outputs, s )
else:
q.put( ('unknown', line ) )
except (ValueError, KeyError, IndexError) as e:
qLog( 'exception', '{}: {}'.format(line, e) )
pass
sendReaderEvent( tagTimes )
#----------------------------------------------------------------------------------
# Handle outputs.
#
for s in writable:
# Write out the waiting data. If we sent it all, remove it from the outputs list.
try:
readerWriteStr[s] = readerWriteStr[s][s.send(readerWriteStr[s].encode()):]
except Exception as e:
qLog( 'exception', u'send error: {}'.format(e) )
readerWriteStr[s] = u''
if not readerWriteStr[s]:
outputs.remove( s )
#----------------------------------------------------------------------------------
# Handle exceptional list.
#
for s in exceptional:
# Close the socket and remove its state.
closeReader( s )
server.close()
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 six.moves.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 StartListener( startTime = datetime.datetime.now(),
HOST = DEFAULT_HOST, PORT = DEFAULT_PORT ):
global q
global shutdownQ
global listener
global dateToday
dateToday = startTime.date()
StopListener()
q = Queue()
shutdownQ = Queue()
listener = Process( target = Server, args=(q, shutdownQ, HOST, PORT, startTime) )
listener.name = 'JChip Listener'
listener.daemon = True
listener.start()
def IsListening():
return listener is not None
@atexit.register
def CleanupListener():
global shutdownQ
global listener
if listener and listener.is_alive():
shutdownQ.put( 'shutdown' )
listener.join()
listener = None
if __name__ == '__main__':
StartListener()
count = 0
for count in six.moves.range(50):
time.sleep( 1 )
sys.stdout.write( '.' )
messages = GetData()
if messages:
sys.stdout.write( '\n' )
for m in messages:
print( m )
sys.stdout.flush()