forked from amiv/bier-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
executable file
·200 lines (164 loc) · 7.1 KB
/
core.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
#!/usr/bin/env python
"""
Heart of the Bier-Automat. Will connect to the LegiLeser and decide if you get a beer.
is also responsible for starting all the (future) fancy stuff
"""
import MySQLdb as mdb
import ConfigParser
import datetime as dt
import legireader
import amivid
import visid
import os.path
import urllib
debug = True
def amivAuth(rfid):
"""Checks if the user may get a beer sponsored by AMIV
:param rfid: Legi-Code of user
:returns: tuple (user,bool) where the first value says returns the user-login (or None) and the second if he may get a beer
"""
#Connect to amivid and get user object
aid = amivid.AmivID(apikey=config.get("amivid", "apikey"),secretkey=config.get("amivid", "secretkey"),baseurl=config.get("amivid", "baseurl"))
user = aid.getUser(rfid)
if not user:
return(None,False)
login = user['nethz']
#Use login-name to check if he may get a beer
#Old: API-Query beer = aid.getBeer(login)
#New: Take it from the user object
beer = user['apps']
#return result, first bool says if user was found, second if he may get a beer)
if (debug): print "Debug: Beer-Count %s"%(beer['beer'])
return (login,int(beer['beer']) > 0)
def visAuth(rfid):
"""Checks if the user may get a beer sponsored by AMIV
:param rfid: Legi-Code of user
:returns: tuple (user,bool) where the first value says returns the user-login (or None) and the second if he may get a beer
"""
#Get secret key
#config = ConfigParser.RawConfigParser()
#config.readfp(open('core.conf'))
#Connect to visid and get user object
vid = visid.VisID(baseurl=config.get("visid", "baseurl"))
user = vid.getUser(rfid)
if not user:
return(None,False)
login = user['nethz']
#Use login-name to check if he may get a beer
beer = vid.getBeer(login)
#return result, first bool says if user was found, second if he may get a beer)
return (login,int(beer['beer']) > 0)
def __getAuthorization(rfid):
"""Here later the real auth must be done, returning None, "AMIV", "VIS" or "MONEY" (or whatever)
:param rfid: Integer holding the Legi-Card-Number
:returns: Tuple of Username and auth. organization (can be 'noBeer') or (None,'notRegistered') if not registered
"""
returnString = 'notRegistered'
returnUser = None
#Ask AMIV for auth
aA = amivAuth(rfid)
if aA[0]:
if aA[1]:
return (aA[0],'amiv')
else:
returnUser = aA[0]
returnString = 'noBeer'
#Ask VIS if not true from AMIV
vA = visAuth(rfid)
if vA[0]:
if vA[1]:
return (vA[0],'vis')
else:
returnUser = vA[0]
returnString = 'noBeer'
return (returnUser,returnString)
def sendToScreen(var, value):
"""Sends a value using POST to the local (flask) server, used to communicate with the GUI"""
serverUrl = "http://localhost:5000/_checkLegi"
request = {var: value}
try:
reply = urllib.urlopen(serverUrl+"?"+urllib.urlencode(request)).read()
except IOError:
print "Could not connect to local webserver"
return
if (debug): print "sendToScreen with %s: %s, reply was %s"%(var,value,reply)
def showCoreMessage(page, code=None, sponsor=None, user=None):
"""Displays a HTML-page on the Display in the core-part, showing the basic info if a legi was accepted"""
if page == 'authorized':
#Template for sending the info to the display
#sendToScreen('beerState','authorized')
print "%s authorized by %s, press the button!"%(user,sponsor)
if page == 'notAuthorized':
print "Not authorized, user was: %s"%(user)
if page == 'notRegistered':
print "Not registered, legi was: %s"%(code)
if page == 'freeBeer':
print "%s got a free beer, sponsored by %s"%(user,sponsor)
def startApp(appname):
"""Starts a custom app"""
pass
if __name__ == "__main__":
debug = True
#Load Config Parameters
config = ConfigParser.RawConfigParser()
config.readfp(open(os.path.dirname(__file__) + '/core.conf')) #changed this as well because not right directory otherwise (Fadri)
dbuser = config.get("mysql", "user")
dbpass = config.get("mysql", "pass")
dbdatabase = config.get("mysql", "db")
dbtable = config.get("mysql", "table")
dbhost = config.get("mysql", "host")
print "ConfigFile core.conf read"
#Connect to Log-DB
conn = mdb.connect(dbhost,dbuser,dbpass,dbdatabase)
cursor = conn.cursor()
#Initialize connection to LegiLeser
lr = legireader.LegiReader() #Also accepts device, baud and waittime parameters
print "Connection to LegiReader established"
authorize = None
lastUser = 0
lastUserTime = dt.datetime.min
#Start endless-loop
try:
while 1:
#Wait for new Legi or Button, read it
#print "Waiting for User Input (reading a Legi)"
(legi,button) = lr.getLegiOrButton()
#print "Detected User Input - Legi=%s, Button=%s"%(legi,button)
#check if legi may get a beer
if legi:
#For debug: Time the auth-query
#starttime = dt.datetime.now()
authorize = __getAuthorization(legi)
#print "Auth-Time: %s"%(dt.datetime.now()-starttime)
if authorize[1] == 'amiv' or authorize[1] == 'vis':
showCoreMessage('authorized',sponsor=authorize[1],user=authorize[0])
lastUserTime = dt.datetime.now()
lastUser = authorize[0]
#Activate free beer
lr.setFreeBeer()
elif authorize[1] == 'noBeer':
showCoreMessage('notAuthorized',user=authorize[0])
elif authorize[1] == 'notRegistered':
showCoreMessage('notRegistered',code=legi)
else:
print >>sys.stderr, "Authorization failed"
elif button and authorize:
#A Button was pressed, check if a legi was read in the last two seconds
if (dt.datetime.now()-lastUserTime < dt.timedelta(seconds=5)):
#Show that a free beer was server
showCoreMessage('freeBeer',sponsor=authorize[1],user=authorize[0])
#Log it
queryString = "INSERT INTO %s(username, org, time, slot) VALUES (%%s,%%s,NOW(),%%s)"%(dbtable)
cursor.execute(queryString,
(lastUser,authorize[1], button))
#Un-Authorize user
authorize = None
else:
#Something else happened, send it to the Debug-Output and continue
if (debug): print "Did not detect anything useful while reading"
continue
finally:
#Process crashed or it was terminated, close open connections
if (debug): print "Program stopped, cleaning up..."
cursor.close()
conn.close()