-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplay.py
executable file
·631 lines (526 loc) · 17.9 KB
/
display.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
#!/home/pi/nfc/bin/python
# -*- coding: utf8 -*-
from __future__ import unicode_literals
import sys
import requests
import logging
import os
import pygame
import time
import random
import RPi.GPIO as GPIO
import spi
import signal
from configparser import ConfigParser
from requests.auth import HTTPBasicAuth
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler('display.log'))
class MFRC522:
NRSTPD = 22
MAX_LEN = 16
PCD_IDLE = 0x00
PCD_AUTHENT = 0x0E
PCD_RECEIVE = 0x08
PCD_TRANSMIT = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC = 0x03
PICC_REQIDL = 0x26
PICC_REQALL = 0x52
PICC_ANTICOLL = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ = 0x30
PICC_WRITE = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE = 0xC2
PICC_TRANSFER = 0xB0
PICC_HALT = 0x50
MI_OK = 0
MI_NOTAGERR = 1
MI_ERR = 2
Reserved00 = 0x00
CommandReg = 0x01
CommIEnReg = 0x02
DivlEnReg = 0x03
CommIrqReg = 0x04
DivIrqReg = 0x05
ErrorReg = 0x06
Status1Reg = 0x07
Status2Reg = 0x08
FIFODataReg = 0x09
FIFOLevelReg = 0x0A
WaterLevelReg = 0x0B
ControlReg = 0x0C
BitFramingReg = 0x0D
CollReg = 0x0E
Reserved01 = 0x0F
Reserved10 = 0x10
ModeReg = 0x11
TxModeReg = 0x12
RxModeReg = 0x13
TxControlReg = 0x14
TxAutoReg = 0x15
TxSelReg = 0x16
RxSelReg = 0x17
RxThresholdReg = 0x18
DemodReg = 0x19
Reserved11 = 0x1A
Reserved12 = 0x1B
MifareReg = 0x1C
Reserved13 = 0x1D
Reserved14 = 0x1E
SerialSpeedReg = 0x1F
Reserved20 = 0x20
CRCResultRegM = 0x21
CRCResultRegL = 0x22
Reserved21 = 0x23
ModWidthReg = 0x24
Reserved22 = 0x25
RFCfgReg = 0x26
GsNReg = 0x27
CWGsPReg = 0x28
ModGsPReg = 0x29
TModeReg = 0x2A
TPrescalerReg = 0x2B
TReloadRegH = 0x2C
TReloadRegL = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F
Reserved30 = 0x30
TestSel1Reg = 0x31
TestSel2Reg = 0x32
TestPinEnReg = 0x33
TestPinValueReg = 0x34
TestBusReg = 0x35
AutoTestReg = 0x36
VersionReg = 0x37
AnalogTestReg = 0x38
TestDAC1Reg = 0x39
TestDAC2Reg = 0x3A
TestADCReg = 0x3B
Reserved31 = 0x3C
Reserved32 = 0x3D
Reserved33 = 0x3E
Reserved34 = 0x3F
serNum = []
def __init__(self, dev='/dev/spidev0.0', spd=1000000):
spi.openSPI(device=dev,speed=spd)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.OUT)
GPIO.output(self.NRSTPD, 1)
self.MFRC522_Init()
def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
def Write_MFRC522(self, addr, val):
spi.transfer(((addr<<1)&0x7E,val))
def Read_MFRC522(self, addr):
val = spi.transfer((((addr<<1)&0x7E) | 0x80,0))
return val[1]
def SetBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg)
self.Write_MFRC522(reg, tmp | mask)
def ClearBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg);
self.Write_MFRC522(reg, tmp & (~mask))
def AntennaOn(self):
temp = self.Read_MFRC522(self.TxControlReg)
if(~(temp & 0x03)):
self.SetBitMask(self.TxControlReg, 0x03)
def AntennaOff(self):
self.ClearBitMask(self.TxControlReg, 0x03)
def MFRC522_ToCard(self,command,sendData):
backData = []
backLen = 0
status = self.MI_ERR
irqEn = 0x00
waitIRq = 0x00
lastBits = None
n = 0
i = 0
if command == self.PCD_AUTHENT:
irqEn = 0x12
waitIRq = 0x10
if command == self.PCD_TRANSCEIVE:
irqEn = 0x77
waitIRq = 0x30
self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
self.ClearBitMask(self.CommIrqReg, 0x80)
self.SetBitMask(self.FIFOLevelReg, 0x80)
self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);
while(i<len(sendData)):
self.Write_MFRC522(self.FIFODataReg, sendData[i])
i = i+1
self.Write_MFRC522(self.CommandReg, command)
if command == self.PCD_TRANSCEIVE:
self.SetBitMask(self.BitFramingReg, 0x80)
i = 2000
while True:
n = self.Read_MFRC522(self.CommIrqReg)
i = i - 1
if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):
break
self.ClearBitMask(self.BitFramingReg, 0x80)
if i != 0:
if (self.Read_MFRC522(self.ErrorReg) & 0x1B)==0x00:
status = self.MI_OK
if n & irqEn & 0x01:
status = self.MI_NOTAGERR
if command == self.PCD_TRANSCEIVE:
n = self.Read_MFRC522(self.FIFOLevelReg)
lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
if lastBits != 0:
backLen = (n-1)*8 + lastBits
else:
backLen = n*8
if n == 0:
n = 1
if n > self.MAX_LEN:
n = self.MAX_LEN
i = 0
while i<n:
backData.append(self.Read_MFRC522(self.FIFODataReg))
i = i + 1;
else:
status = self.MI_ERR
return (status,backData,backLen)
def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []
self.Write_MFRC522(self.BitFramingReg, 0x07)
TagType.append(reqMode);
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR
return (status,backBits)
def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0
serNum = []
self.Write_MFRC522(self.BitFramingReg, 0x00)
serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)
if(status == self.MI_OK):
i = 0
if len(backData)==5:
while i<4:
serNumCheck = serNumCheck ^ backData[i]
i = i + 1
if serNumCheck != backData[i]:
status = self.MI_ERR
else:
status = self.MI_ERR
return (status,backData)
def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80);
i = 0
while i<len(pIndata):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
i = i + 1
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i = i - 1
if not ((i != 0) and not (n&0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData
def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)
i = 0
while i<5:
buf.append(serNum[i])
i = i + 1
pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if (status == self.MI_OK) and (backLen == 0x18):
print "Size: " + str(backData[0])
return backData[0]
else:
return 0
def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []
# First byte should be the authMode (A or B)
buff.append(authMode)
# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)
# Now we need to append the authKey which usually is 6 bytes of 0xFF
i = 0
while(i < len(Sectorkey)):
buff.append(Sectorkey[i])
i = i + 1
i = 0
# Next we append the first 4 bytes of the UID
while(i < 4):
buff.append(serNum[i])
i = i +1
# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)
# Check if an error occurred
if not(status == self.MI_OK):
print "AUTH ERROR!!"
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
print "AUTH ERROR(status2reg & 0x08) != 0"
# Return the status
return status
def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)
def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not(status == self.MI_OK):
print "Error while reading!"
i = 0
if len(backData) == 16:
print "Sector "+str(blockAddr)+" "+str(map(lambda x: "%X" % x, backData))
print "Matrikelnummer: %s" % ''.join(map(chr, backData[2:9]))
return ''.join(map(chr, backData[2:9]))
def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR
print str(backLen)+" backdata &0x0F == 0x0A "+str(backData[0]&0x0F)
if status == self.MI_OK:
i = 0
buf = []
while i < 16:
buf.append(writeData[i])
i = i + 1
crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
print "Error while writing"
if status == self.MI_OK:
print "Data written"
def MFRC522_DumpClassic1K(self, key, uid):
i = 0
while i < 64:
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
print "Authentication error"
i = i+1
def MFRC522_Init(self):
GPIO.output(self.NRSTPD, 1)
self.MFRC522_Reset();
self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)
self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()
class Display(object):
screen = None;
def __init__(self):
logger.info('Starting Display')
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
if disp_no:
logger.debug('I am running under X display = {0}'.format(disp_no))
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
#drivers = ['fbcon', 'directfb', 'svgalib']
#found = False
#for driver in drivers:
# # Make sure that SDL_VIDEODRIVER is set
# if not os.getenv('SDL_VIDEODRIVER'):
# os.putenv('SDL_VIDEODRIVER', driver)
# try:
# pygame.display.init()
# except pygame.error:
# print 'Driver: {0} failed.'.format(driver)
# continue
# found = True
# break
#if not found:
# raise Exception('No suitable video driver found!')
pygame.display.init()
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
logger.debug('Display size: %d x %d' % (size[0], size[1]))
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
pygame.mouse.set_visible(False)
# Clear the screen to start
self.screen.fill((0, 0, 0))
self.images = {}
logger.debug('Loading logo')
self.images['logo'] = pygame.image.load("logo.png")
screen_rect = self.screen.get_rect()
surf = pygame.transform.smoothscale(
self.images['logo'],
self.images['logo'].get_rect().fit(screen_rect)[2:4]
)
pos = surf.get_rect()
pos.centerx = screen_rect.centerx
self.screen.blit(surf, pos)
border = screen_rect.h * 0.1
self.draw = pygame.Surface((screen_rect.w-border*2, screen_rect.h - pos.h - border*2))
self.draw_pos = (border, pos.h + border)
self.screen.blit(self.draw, self.draw_pos)
# Render the screen
pygame.display.update()
# Initialise font support
logger.debug('Initializing fonts')
pygame.font.init()
self.font = pygame.font.Font(None, 400)
logger.debug('Loading rest of images')
self.images['ok'] = pygame.image.load("ok.png")
self.images['reading'] = pygame.image.load("reading.png")
self.images['error'] = pygame.image.load("error.png")
self.images['card'] = pygame.image.load("card.png")
self.images['network'] = pygame.image.load("network.png")
self.images['timing'] = pygame.image.load("timing.png")
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def status(self, obj, icon):
draw_r = self.draw.get_rect()
left = pygame.Surface((draw_r.w - draw_r.h * 0.75, draw_r.h))
left_c = pygame.transform.smoothscale(
obj,
obj.get_rect().fit(left.get_rect())[2:4]
)
left_p = left_c.get_rect()
left_p.centerx = left.get_rect().centerx
left_p.centery = left.get_rect().centery
left.blit(left_c, left_p)
self.draw.blit(left, (0, 0))
right = pygame.Surface((draw_r.h * 0.75, draw_r.h))
right_c = pygame.transform.smoothscale(
icon,
icon.get_rect().fit(right.get_rect().inflate(-(draw_r.h * 0.25), -(draw_r.h * 0.5)))[2:4]
)
right_p = right_c.get_rect()
right_p.centerx = right.get_rect().centerx
right_p.centery = right.get_rect().centery
right.blit(right_c, right_p)
self.draw.blit(right, (draw_r.w - draw_r.h * 0.75, 0))
self.screen.blit(self.draw, self.draw_pos)
pygame.display.update()
def wait(self):
text = self.font.render("MED UNI CARD", 1, (190, 190, 190))
self.status(text, self.images['card'])
def reading(self):
text = self.font.render("Wird gelesen", 1, (190, 190, 190))
self.status(text, self.images['reading'])
def failure(self, reason, icon):
text = self.font.render("Fehler: {}".format(reason), 1, (255, 52, 52))
self.status(text, self.images[icon])
def incoming(self):
text = self.font.render("Willkommen", 1, (81, 174, 50))
self.status(text, self.images['ok'])
def outgoing(self):
text = self.font.render("Auf Wiedersehen", 1, (81, 174, 50))
self.status(text, self.images['ok'])
# Create an instance of the PyScope class
scope = Display()
continue_reading = True
def handle_sighup(signum, frame):
pass
# Hook the signals
signal.signal(signal.SIGHUP, handle_sighup)
# Create an object of the class MFRC522
MIFAREReader = MFRC522()
# Read config file
conf = ConfigParser()
conf.read('config.ini')
lastuid = {
'seen': datetime.now(),
'uid': None
}
lastdelta = timedelta(seconds=int(config['attendance']['debounce']))
auth = HTTPBasicAuth(config['attendance']['user'], config['attendance']['password'])
url = config['attendance']['url']
nfc_key = list(map(lambda x: int(x, 0), config['attendance']['nfc_key'].split(',')))
scope.wait()
logger.info('Starting event loop')
while continue_reading:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
logger.info('ESC pressed ... shuting down')
continue_reading = False
pygame.quit()
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status != MIFAREReader.MI_OK:
scope.wait()
continue
logger.debug('Card detected')
# Get the UID of the card
(status, uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status != MIFAREReader.MI_OK:
logger.warn('Could not read card: {0}/{1}'.format(uid, status))
scope.failure('Lesefehler', 'error')
continue
if uid == lastuid.get('uid') and lastuid.get('seen') + lastdelta > datetime.now():
continue
scope.reading()
# Print UID
logger.info('Card read UID: %X:%X:%X:%X' % tuple(uid[:4]))
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 4, key, uid)
# Check if authenticated
if status == MIFAREReader.MI_OK:
matriculation = MIFAREReader.MFRC522_Read(4)
logger.info('Card {0} hast matriculation {1}'.format(uid, matriculation))
MIFAREReader.MFRC522_StopCrypto1()
try:
logger.debug('Sending request for {0}'.format(matriculation))
r = requests.post(url, json={'student': matriculation}, auth=auth, timeout=3)
logger.debug('Received response: {0}'.format(r))
if r.ok:
if r.json().get('direction') == 'in':
scope.incoming()
else:
scope.outgoing()
else:
logger.debug('Request to soon for {0}'.format(matriculation))
scope.failure('Buchung', 'timing')
lastuid = {
'seen': datetime.now(),
'uid': uid
}
except requests.exceptions.ConnectionError:
lastuid['uid'] = None
logger.debug('Request network error {0}'.format(matriculation))
scope.failure('Netzwerk', 'network')
else:
lastuid['uid'] = None
logger.debug('Request network error {0}'.format(matriculation))
scope.failure('Schlüssel', 'error')
time.sleep(1)