-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.py
117 lines (104 loc) · 3.58 KB
/
controller.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
import sys
import json
import logging
from time import sleep
from threading import Thread
import requests
import settings
from MFRC522.MFRC522 import AuthError
from reader import read_card
def heart_beat():
if not hasattr(settings, 'HEART_BEAT_PATH'):
return
if settings.HEART_BEAT_PATH is None:
while True:
sleep(10)
while True:
try:
res = requests.head(settings.HEART_BEAT_PATH, timeout=1)
logging.debug(res)
except Exception as e:
logging.error('[Network Error] %s' % e)
finally:
sleep(10)
def reader():
logging.info('start to waiting for cards')
while True:
# checking content
# function card
try:
fb = settings.FUNCTION_BLOCK
card = read_card(block=fb, key=settings.KEYS[fb])
except AuthError:
pass
except Exception as e:
logging.error(e)
else:
if card is not None:
logging.info('get command "%s"' % card.content)
settings.RUN(card.content)
# staff card
try:
sb = settings.STAFF_BLOCK
card = read_card(block=sb, key=settings.KEYS[sb])
except AuthError:
pass
except Exception as e:
logging.error(e)
else:
if card is not None:
logging.info("get staff card (%s)" % card.cid)
try:
logging.info("get staff card (%s)" % card.content)
username = card.content.split(':')[0]
password = card.content.split(':')[1]
except:
logging.error('Wrong format of staff card')
continue
try:
res = requests.post(settings.STAFF_PATH, data={
'username': username,
'password': password,
})
logging.debug(res)
except Exception as e:
logging.error('[Network Error] %s' % e)
else:
if res.status_code != 200:
logging.warn(res.text)
sleep(3) # sleep 3 seconds after reading sucess
# student card
try:
sb = settings.STUDENT_BLOCK
card = read_card(block=sb, key=settings.KEYS[sb])
except AuthError:
pass
except Exception as e:
logging.error(e)
else:
if card is not None:
logging.info("get student card (%s)" % card.content[0:9])
try:
res = requests.post(settings.VOTE_PATH, data={
'student_id': card.content[0:10],
'card_id': card.cid,
settings.VOTE_TOKEN_NAME: settings.VOTE_TOKEN
})
logging.debug(res)
except Exception as e:
logging.error('[Network Error] %s' % e)
else:
if res.status_code != 200:
logging.warn(res.text)
sleep(3) # sleep 3 seconds after reading sucess
# fequency of scanning
sleep(settings.LATENCY)
if __name__ == '__main__':
heart_beat_thread = Thread(target=heart_beat, daemon=True)
heart_beat_thread.start()
reader_thread = Thread(target=reader, daemon=True)
reader_thread.start()
try:
heart_beat_thread.join()
except (KeyboardInterrupt, SystemExit):
sys.exit()