-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin_v1.py
242 lines (205 loc) · 8.37 KB
/
admin_v1.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
########################################################
########################################################
################ packages ##############################
import re
import os
import ast
import requests
import json
import csv
import collections
from random import randint
from flask_api import status
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError, OperationalError, SQLAlchemyError
from flask import Flask, jsonify, request, abort, redirect, url_for, session, Response, _request_ctx_stack, render_template
#################### init ###############################
app = Flask(__name__)
app.config['SECRET_KEY'] = "geofence api"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///geofence.db'
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
session_options = {'autocommit':False, 'autoflush':False}
db = SQLAlchemy(app)
###################### db ###############################
class Admin(db.Model):
__tablename__ = "admin"
a_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
admin_id = db.Column(db.String(), unique=True, index=True)
owns_fences = db.Column(db.String(), nullable=False)
def __init__(self, admin_id, owns_fences):
self.admin_id = admin_id
self.owns_fences = owns_fences
class Geofence(db.Model):
__tablename__ = "geofence"
fence_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
admin_id = db.Column(db.String(), nullable=False)
geof_id = db.Column(db.String(), unique=True, nullable=False)
fence_type = db.Column(db.String(), nullable=False)
radius = db.Column(db.String(), nullable=False)
centroid = db.Column(db.String(), nullable=False)
latitudes = db.Column(db.String(), nullable=False)
longitudes = db.Column(db.String(), nullable=False)
joined_devices = db.Column(db.String(), nullable=False)
boundary_buffer = db.Column(db.String(), nullable=False)
def __init__(self, geof_id, admin_id, fence_type, radius, centroid, latitudes, longitudes, joined_devices, boundary_buffer):
self.admin_id = admin_id
self.geof_id = geof_id
self.fence_type = fence_type
self.radius = radius
self.centroid = centroid
self.latitudes = latitudes
self.longitudes = longitudes
self.joined_devices = joined_devices
self.boundary_buffer = boundary_buffer
class Device(db.Model):
__tablename__ = "device"
user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
device_id = db.Column(db.String(), unique=True, index=True)
joined_fences = db.Column(db.String(), nullable=False)
#optional, dynamic:
latitude = db.Column(db.String(), nullable=False)
longitude = db.Column(db.String(), nullable=False)
status = db.Column(db.String(), nullable=False) #inside/outside for each fence subscribed to
def __init__(self, device_id, joined_fences, latitude, longitude, status):
self.device_id = device_id
self.joined_fences = joined_fences
self.latitude = latitude
self.longitude = longitude
self.status = status
db.create_all()
# def message():
# return "hi"
################ functions ####################
################# apis ##########################
@app.route('/')
def login():
return render_template('login.html')
@app.route('/admin_dashboard')
def adming_dashboard():
return render_template('admin_dashboard.html')
@app.route('/processLogin', methods=['POST'])
def processLogin():
# print("In here")
req = request.get_json()
admin_id = req['client_id']
session['current_user'] = admin_id
session['user_available'] = True
quer_res = db.session.query(Admin).filter_by(admin_id = admin_id).first()
ret = {}
ret['redirecturl'] = '/dashboard'
if(quer_res is None):
reg = Admin(admin_id, "admin")
db.session.add(reg)
db.session.commit()
ret['msg'] = "Successfully created!"
return jsonify(ret)
@app.route('/dashboard', methods=['GET'])
def dashboard():
print(session['current_user'])
if(session['user_available']):
return render_template('subscribe.html')
return redirect(url_for('logout'))
#Do rest/ajax on this
# @app.route('/updateDashboard', methods=['GET'])
# def processDashboard():
# if(session['user_available']):
# resu = db.session.query(Geofence).filter_by(admin_id=session['current_user'])
# ret = {}
# for row in resu:
# devices = row['joined_devices'].split('#')
# for device_id in devices:
# #resp = db.session.query(Device).filter_by(device_id=device_id)
# #ping client for location
# (lat, lon) = pingClient(device_id)
# ###########################################check lat, long #########################
# (status, dist, coords) = GetStatus(row['type'], row['centroid'], row['latitudes'], row['longitudes'], row['boundary_buffer'], (lat, lon), row['radius'])
# if status==1:
# dist = -dist
# ret[resu['geof_id']].append([device_id, status, dist, list(coords)])
# return jsonify(ret)
# return redirect(url_for('logout'))
@app.route('/createGfence', methods=['GET'])
def createGfence():
if(session['user_available']):
return render_template('gmap.html')
return redirect(url_for('logout'))
# @app.route('/processCreateGfence', methods=['POST'])
# def processCreateGfence():
# if(session['user_available']):
# ret = {}
# admin_id = (request.form['admin_id']).strip()
# geof_id = (request.form['geof_id']).strip()
# shape = (request.form['type']).strip()
# radius = (request.form['radius']).strip()
# ##############################check what type
# latitudes = request.form['latitudes']
# longitudes = request.form['longitudes']
# quer_res = db.session.query(Geofence).filter_by(geof_id = geof_id)
# if(quer_res.scalar() is None):
# #compute centroid and buffer distance
# centroid = Centroid(shape,latitudes,longitudes,radius)
# buffer_dist = CalculateBufferDistance(shape,latitudes,longitudes,radius)
# #################################check type of lat and long before join
# reg = Geofence(admin_id, geof_id, shape, radius, centroid, "#".join(latitudes), "#".join(longitudes), "", buffer_dist)
# db.session.add(reg)
# db.session.commit()
# else:
# return jsonify({'error' : 'Fence already exists !'})
# return redirect(url_for('logout'))
@app.route('/logout')
def logout():
session.clear()
session['user_available'] = False
session['current_user'] = ""
return redirect(url_for('home'))
@app.route("/save", methods=["POST"])
def save():
req = request.get_json()
# req = json.loads(req)
print(req)
tosave = dict()
tosave['admin_id'] = req['admin_id']
tosave['type'] = req['type']
tosave['radius'] = req['radius']
tosave['geof_id'] = req['geof_id']
if req['type'] != "circle":
latitude = []
longitude = []
locations = ast.literal_eval(req['locations'])
locations = list(locations)
# print(locations, type(locations))
for loc in locations:
latitude.append(loc[0])
longitude.append(loc[1])
tosave['latitudes'] = latitude
tosave['longitudes'] = longitude
else:
tosave['latitudes'] = req['latitude']
tosave['longitudes'] = req['longitude']
with open("common_resources/sample.json", "a") as outfile:
outfile.write("\n" + json.dumps(tosave))
return "Saved Succesfully"
"""
@app.route('/register', methods=['POST'])
def processCreateGfence():
if(session['user_available']):
ret = {}
admin_id = (request.form['admin_id']).strip()
geof_id = (request.form['geof_id']).strip()
shape = (request.form['type']).strip()
"""
# @app.route('/ping', methods=["GET"])
# def ping():
# def send():
# while 1:
# yield message()
# return Response(send(), mimetype = "text/event-stream")
@app.route('/health', methods=["POST"])
def health():
req = request.get_json()
print(req)
return "healthy!"
if __name__ == "__main__" :
app.run(debug=True)