cs161079 5 years ago
parent
commit
4f314c5dd1
  1. 5
      gatewayNode/data.json
  2. 7
      gatewayNode/parking.py
  3. BIN
      serverNode/__pycache__/serv.cpython-37.pyc
  4. 161
      serverNode/serv.py

5
gatewayNode/data.json

@ -1,4 +1,7 @@
{ {
"ip": "192.168.89.14", "ip": "192.168.89.14",
"port": "8080" "port": "8080",
"device": "1",
"username": "root",
"password": "root"
} }

7
gatewayNode/parking.py

@ -31,6 +31,11 @@ if json_data != "" and json_data != None:
ser.readline() ser.readline()
prev_status = "-1" prev_status = "-1"
device_session = requests.session()
data = """{"username" :""" + server_par['username'] + """, "password":""" + server_par['password'] + """, "device": """ + server_par['device'] + """}"""
s.post(url = API_ENDPOINT, data = data)
while 1: while 1:
park_status = ser.readline() park_status = ser.readline()
park_status_data = str(park_status).split("#") park_status_data = str(park_status).split("#")
@ -41,7 +46,7 @@ if json_data != "" and json_data != None:
try: try:
if parkingStatus != prev_status: if parkingStatus != prev_status:
data = """{"no":""" + parkingCode + ""","status":""" + parkingStatus + """}""" data = """{"no":""" + parkingCode + ""","status":""" + parkingStatus + """}"""
r = requests.post(url = API_ENDPOINT, data = data) r = s.post(url = API_ENDPOINT, data = data)
if parkingStatus == "0": if parkingStatus == "0":
print("parking reserved. RESPONSE :", r.status_code, "\n") print("parking reserved. RESPONSE :", r.status_code, "\n")
elif parkingStatus == "1": elif parkingStatus == "1":

BIN
serverNode/__pycache__/serv.cpython-37.pyc

Binary file not shown.

161
serverNode/serv.py

@ -7,6 +7,7 @@ from json import dumps
import json import json
from flask_cors import CORS from flask_cors import CORS
import mysql.connector import mysql.connector
import os
# ================================================================== # ==================================================================
# ================================================================== # ==================================================================
@ -15,6 +16,9 @@ import mysql.connector
app = Flask(__name__) app = Flask(__name__)
CORS(app) CORS(app)
# create the secret key for session
app.secret_key = os.urandom(24)
# creating an API object # creating an API object
api = Api(app) api = Api(app)
@ -33,17 +37,17 @@ myCursor = mydb.cursor()
# Define a function that gets the parking status # Define a function that gets the parking status
# for all parking codes. # for all parking codes.
def getParkings(): def getParkings():
parks = [] parks = []
myCursor.execute("SELECT * FROM PARKING") myCursor.execute("SELECT * FROM PARKING")
myRes = myCursor.fetchall() myRes = myCursor.fetchall()
for res in myRes: for res in myRes:
if res[1] == 1: if res[1] == 1:
parks.append({"no": res[0], "status": True}) parks.append({"no": res[0], "status": True})
else: else:
parks.append({"no": res[0], "status": False}) parks.append({"no": res[0], "status": False})
return parks return parks
def isMember(username, password): def isMember(username, password):
myCursor.execute("SELECT * FROM USERS") myCursor.execute("SELECT * FROM USERS")
@ -57,6 +61,12 @@ def isMember(username, password):
return isValid return isValid
def isAuthenticated():
if 'device_id' in session:
return True
else:
return False
# ================================================================== # ==================================================================
# making a class for a particular resource # making a class for a particular resource
@ -64,64 +74,95 @@ def isMember(username, password):
# they are automatically mapped by flask_restful. # they are automatically mapped by flask_restful.
# other methods include put, delete, etc. # other methods include put, delete, etc.
class Parking(Resource): class Parking(Resource):
def get(self): def get(self):
parks = getParkings() try:
return parks, 200 parks = getParkings()
except mysql.connector.errors.DatabaseError as e:
mydb.reconnect(attempts=1, delay=0)
return parks, 200
class ParkingStatus(Resource): class ParkingStatus(Resource):
def get(self): def get(self):
return """<html> return """<html>
<head><title>ERROR</title></head> <head><title>ERROR</title></head>
<body><h1>Not get at '/parkingStatus'.</h1></body> <body><h1>Not get at '/parkingStatus'.</h1></body>
</html>""" </html>"""
def post(self): def post(self):
# Gets the data into as a JSON Object from HTTP request. if isAuthenticated():
data = json.loads(request.data) # Gets the data into as a JSON Object from HTTP request.
data = json.loads(request.data)
# SQL get all Parking places status.
parks = getParkings() try:
# SQL get all Parking places status.
currentParking = {} parks = getParkings()
for park in parks: except mysql.connector.errors.DatabaseError as e:
if park['no'] == data['no']: mydb.reconnect(attempts=1, delay=0)
currentParking = park
break; currentParking = {}
for park in parks:
thereIs = False if park['no'] == data['no']:
toUpdate = False currentParking = park
try: break;
if currentParking['status'] != data['status']:
toUpdate = True thereIs = False
thereIs = True toUpdate = False
except IndexError: try:
# handle Index Error if currentParking['status'] != data['status']:
thereIs = False toUpdate = True
toUpdate = False thereIs = True
except KeyError: except IndexError:
# handle the KeyError # handle Index Error
thereIs = False thereIs = False
toUpdate = False toUpdate = False
except KeyError:
if not thereIs: # handle the KeyError
# Make a new insert entry for a new Parking Code. thereIs = False
values = (int(data['no']), int(data['status'])) toUpdate = False
myCursor.execute("INSERT INTO PARKING (PARKING_CODE, PARKING_STATUS) VALUES (%s, %s)", values)
mydb.commit() try:
parks = getParkings() if not thereIs:
elif toUpdate: # Make a new insert entry for a new Parking Code.
# Make an Update status for Parking Code that availability changed. values = (int(data['no']), int(data['status']))
values = (int(data['status']), int(data['no'])) myCursor.execute("INSERT INTO PARKING (PARKING_CODE, PARKING_STATUS) VALUES (%s, %s)", values)
myCursor.execute("UPDATE PARKING SET PARKING_STATUS=%s WHERE PARKING_CODE=%s", values) mydb.commit()
mydb.commit() parks = getParkings()
parks = getParkings() elif toUpdate:
# Make an Update status for Parking Code that availability changed.
return currentParking, 201 values = (int(data['status']), int(data['no']))
myCursor.execute("UPDATE PARKING SET PARKING_STATUS=%s WHERE PARKING_CODE=%s", values)
mydb.commit()
parks = getParkings()
except mysql.connector.errors.DatabaseError as e:
mydb.reconnect(attempts=1, delay=0)
return currentParking, 201
else:
return "Error! You aren't authenticated. [POST] /authenticate first.", 403
class Authenticate(Resource):
def post(self):
try:
#Get the credencial from body of request.
data = json.loads(request.data)
if data['username'] != None and data['password'] != None and data['device'] != None:
isValid = isMember(data['username'], data['password'])
if isValid:
session['device_id'] = data['device']
else:
return "Not Authenticatiove device", 403
else:
return "Error authentication", 403
except mysql.connector.errors.DatabaseError as e:
mydb.reconnect(attempts=1, delay=0)
# ================================================================== # ==================================================================
# adding the defined resources along with their corresponding urls to REST APIs # adding the defined resources along with their corresponding urls to REST APIs
api.add_resource(Parking, '/') api.add_resource(Parking, '/')
api.add_resource(ParkingStatus, '/parkingStatus') api.add_resource(ParkingStatus, '/parkingStatus')
api.add_resource(Authenticate, '/authenticate')
# ================================================================== # ==================================================================
# driver function # driver function

Loading…
Cancel
Save