-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
384 lines (296 loc) · 12.1 KB
/
server.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
from gevent import monkey
import json
from flask import Flask, request, Response, render_template, abort, url_for
import sqlite3
import gevent
from flask_httpauth import HTTPDigestAuth
import time
# Flask Variables
app = Flask(__name__)
monkey.patch_all()
auth = HTTPDigestAuth()
app.config['SECRET_KEY'] = 'Cycle Project: Wheels On Roll'
# Database Variables
DATABASE = 'file::memory:?cache=shared'
# Users to access app
# Users to be authenticated
users = {
"akshay": "revankar",
"salman": "shah",
"hrishi": "hiraskar"
}
# Helper Methods
def event_stream(cycle_id):
print("event stream request from cycle ", cycle_id)
ride_id = None
try:
while True:
# database query
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()
# Query to get user rfid number
id = (cycle_id, 0)
# TODO: Revisit this logic later
# cur.execute("SELECT * FROM rides WHERE cycle_id = ? and status = 0 and paid = 0", id)
cur.execute("SELECT * FROM rides WHERE cycle_id = ? and status = ?", id)
ride = cur.fetchone()
# when there is new entry with current id
if ride != None:
ride_id = ride[0]
# Query to get user rfid number
user_id = int(ride[2])
user_id = (user_id, )
# # TODO: Revisit this logic later
cur.execute("SELECT * FROM users WHERE id = ? ", user_id)
user = cur.fetchone()
rfid_no = user[4]
# TODO: store the ride id as var
# Send Event Stream
# yield rfid and ride id
yield 'event: user_request\ndata: %s\n\n' % json.dumps({"ride_id":ride_id, "rfid":rfid_no})
continue
if ride_id is None:
gevent.sleep(1)
continue
# TODO: Check if ride id is finished
# Loop until:
# 1. timeout -or-
# 2. user reinitiated the ride status
# And send corresponding event at event = 'post_ride'
# and status = 'continue' -or- 'stop' -or- 'timeout'
# Query to get user rfid number
id = (cycle_id, ride_id)
# TODO: Revisit this logic later
# cur.execute("SELECT * FROM rides WHERE cycle_id = ? and status = 0 and paid = 0", id)
cur.execute("SELECT * FROM rides WHERE cycle_id = ? and ride_id = ? and status = 2 or status = 3", id)
ride = cur.fetchone()
# print("Running ride", ride)
if ride != None:
count = 0
ride_status = True
while count < 600 or ride_status:
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()
# Query to get user rfid number
id = (cycle_id, ride_id, 3)
cur.execute("SELECT * FROM rides WHERE cycle_id = ? and ride_id = ? and status = ?", id)
ride = cur.fetchone()
# If user wants to continue the ride
if ride:
yield 'event: post_ride\ndata: %s\n\n' % json.dumps({"status": "continue"})
cur.execute("UPDATE rides SET status = 0 WHERE cycle_id = ? and status = ?", id)
else:
pass
id = (cycle_id, ride_id, -1)
cur.execute("SELECT * FROM rides WHERE cycle_id = ? and ride_id = ? and status = ?", id)
ride = cur.fetchone()
# If user wants to stop the ride
if ride:
yield 'event: post_ride\ndata: %s\n\n' % json.dumps({"status": "stop"})
else:
pass
gevent.sleep(1)
count += 1
yield 'event: post_ride\ndata: %s\n\n' % json.dumps({"status": "timeout"})
cur.execute("UPDATE rides SET status = 0 WHERE cycle_id = ? and ride_id = ? and status = 2 or status = 3", (cycle_id, ride_id))
# Every 1 second query database if new ride with tho
db.close()
gevent.sleep(1)
except Exception as e:
print(e)
pass
"""
Android Code ~ SS ~
"""
@app.route('/qr_code_receive', methods=['POST'])
def qr_code():
# print(str(json.dumps(request.json)))
email = request.json['email']
cycle_id = int(request.json['cycle_id'])
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()
# Query to get user rfid number
email_id = (email,)
cur.execute("SELECT * FROM users WHERE email = ? ",email_id)
user = cur.fetchone()
user_id = int(user[0])
if user == None:
return json.dumps({'success': False, 'message': 'Kill App Programmer'})
cycle_idi = (cycle_id,)
cur.execute("SELECT * FROM cycles WHERE id = ? ",cycle_idi)
cycle = cur.fetchone()
if cycle == None:
return json.dumps({'success': False, 'message': 'QR Code is wrong'})
rfid_number = user[4]
# Query to get user rfid number
# ride = (user_id, cycle_id[0],)
# cur.execute("INSERT INTO rides('user_id', 'cycle_id') VALUES(?, ?) ",ride)
# db.commit()
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
ride = (cycle_id, user_id, current_time)
cur.execute("INSERT INTO rides('cycle_id', 'user_id', 'start_time') VALUES(?, ?, ?) ",ride)
db.commit()
cur.execute("select * from rides where start_time = ?", (current_time,))
ride = cur.fetchone()
return json.dumps({'success': True, 'ride_id': ride[0]})
# Assign RFID to user
@app.route('/assign_rfid', methods=['POST'])
def assign_rfid_to_user():
pass
# Simple HTTP Login of the website
@app.route('/login', methods=['POST'])
def login():
# Evaluate Post Parameters from Login
# print(str(json.dumps(request.json)))
email = request.json['email']
password = request.json['password']
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()
email_id = (email,)
cur = cur.execute("SELECT * FROM users WHERE email = ? and rfid_no IS NOT NULL",email_id)
user = cur.fetchone()
# print(user)
if user is None:
return json.dumps({'success': False, 'message': 'Get your Smart Cycle Card'})
if password == user[3]:
return json.dumps({'success': True})
return json.dumps({'success': False, 'message': 'Email doesn\'t exist'})
# Simple Register User Option
@app.route('/register', methods=['POST'])
def register_user():
# Evaluate POST Parameters from Register
# print(str(json.dumps(request.json)))
name = request.json['username']
email = request.json['email']
password = request.json['password']
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()
user_record = (name, email, password)
cur.execute("INSERT INTO users(name, email, encrypted_password) VALUES(?, ?, ?) ",user_record)
db.commit()
return json.dumps({'success': True, 'message': 'Kindly contact administrator for Card to login'})
# Code to start ride by users
@app.route('/startride', methods=['POST'])
def start_ride():
# print(str((request.form))+'Hrishi Data')
status = request.form.get('status')
ride_id = request.form.get('ride_id')
if status == 'Accepted':
db = sqlite3.connect("file::memory:?cache=shared",
check_same_thread=False)
cur = db.cursor()
ride = (1, ride_id,)
cur.execute("UPDATE rides SET status = ? WHERE id = ?", ride)
db.commit()
return json.dumps({'status': 'success'})
# TODO: Mobile Logic will be done later
elif status=='Rejected':
db = sqlite3.connect("file::memory:?cache=shared",
check_same_thread=False)
cur = db.cursor()
ride = (-1, ride_id,)
cur.execute("UPDATE rides SET status = ? WHERE id = ?", ride)
db.commit()
return json.dumps({'status': 'failure'})
return json.dumps({'status': 'failure'})
@app.route('/stopride', methods=['POST'])
def stop_ride():
# print(str((request.form)) + 'Hrishi Data')
ride_id = request.form.get('ride_id')
# cycle_id = request.form.get('cycle_id')
db = sqlite3.connect("file::memory:?cache=shared",
check_same_thread=False)
cur = db.cursor()
ride = (2, ride_id,)
cur.execute("UPDATE rides SET status = ? WHERE id = ?", ride)
db.commit()
return json.dumps({'status': 'success'})
@app.route('/events')
def sse_request():
# Set response method to event-stream
return Response(event_stream(request.form.get('id' ,'')), mimetype='text/event-stream')
@app.route('/start_ride_polling', methods=['POST'])
def start_ride_polling():
# print(request.json)
ride_id = request.json['ride_id']
db = sqlite3.connect("file::memory:?cache=shared",
check_same_thread=False)
cur = db.cursor()
cur.execute("SELECT * FROM rides where id = ? and status = 1", (ride_id, ))
ride = cur.fetchone()
if ride:
return json.dumps({'success': True, 'accepted': True})
cur.execute("SELECT * FROM rides where id = ? and status = -1", (ride_id, ))
ride = cur.fetchone()
if ride:
return json.dumps({'success': True, 'accepted': False})
return json.dumps({'success': False})
@app.route('/stop_ride_polling', methods=['POST'])
def stop_ride_polling():
ride_id = request.json['ride_id']
latitude = request.json['latitude']
longitude = request.json['longitude']
print("latitute: ", latitude)
print("longitude: ", longitude)
db = sqlite3.connect("file::memory:?cache=shared",
check_same_thread=False)
cur = db.cursor()
cur.execute("SELECT * FROM rides where id = ?", (ride_id, ))
ride = cur.fetchone()
cycle_id = ride[1]
if latitude != ride[8] or longitude != ride[9] :
if latitude != -1 or longitude != -1:
cur.execute("UPDATE rides SET latitude = ?, longitude = ? WHERE id = ?",
(latitude, longitude, ride_id, ))
# Write location to file
file = open("gps_data/cycle" + str(cycle_id) + ".txt", "a")
file.write("{0},{1}\n".format(longitude, latitude))
file.close()
cur.execute("SELECT * FROM rides where id = ? AND status != 1", (ride_id, ))
ride = cur.fetchone()
db.commit()
if ride:
return json.dumps({'success': True})
return json.dumps({'success': False})
@app.route('/dump_location', methods=['POST'])
def dump_location():
ride_id = request.json['ride_id']
location_data = request.json['location_data']
file = open("gps_data/ride" + str(ride_id) + ".txt", "w")
file.write(location_data)
file.close()
return json.dumps({'success': False})
"""
Web App Code ~ SS ~
"""
# Load Users
@app.route('/load_users', methods=['POST'])
def load_users():
data = request.json['data']
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()
if data == "no_rfid_number":
user_data = cur.execute("SELECT * from users WHERE rfid_no IS NULL")
user_data = user_data.fetchall()
elif data == "rfid_number":
user_data = cur.execute("SELECT * from users where rfid_no IS NOT NULL")
user_data = user_data.fetchall()
return json.dumps(user_data)
# Authenticating users from Dictionary
@auth.get_password
def get_pw(username):
if username in users:
return users.get(username)
return None
@app.route('/about')
@auth.login_required
def about():
return render_template('about.html', name='Cycle Project - About')
@app.route('/')
@auth.login_required
def index():
return render_template('index.html', name='Cycle Project')
# Main Method in the Server code
if __name__ == '__main__':
# Set server address 0.0.0.0:5000/
app.run(host="0.0.0.0", port=5000, debug=True, threaded=True)