def login_api(request): """The Login API checks to see if the user is trying to login with a valid Customer_Number and Password""" data = request.data json_data = json.loads(data) #If test is passed as an input and its true, we set the test flag as true to use the Testing database if "test" in json_data: test = json_data["test"] else: test = False Customer_Number = json_data["Customer_Number"] Password = json_data["Password"] #Validating the input to only process valid data. We return an error if the data is not valid valid_input = Validate_Input(json_data["Customer_Number"], json_data["Password"]) if not valid_input: return ('', 400) #bad request db_context = open_connection(test) cur = db_context.cursor() cur.execute( 'SELECT * FROM public."Customers" c WHERE c."Active" = true AND c."Customer_Number" = %s', (Customer_Number, )) result_set = cur.fetchall() result = [] #f the result_set is [], a user with the customer number doesnt exist and we return a 404 error if not result_set: close_connection(cur, db_context) return ('', 404) colnames = [desc[0] for desc in cur.description] customer = result_set[0] result = dict(zip(colnames, customer)) response = {} password_check = check_password(result['PasswordHash'], Password) if password_check: response['Customer_Id'] = result['Id'] # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the JSON object and the Http 200 status to show a success status return json.dumps(response), status.HTTP_200_OK else: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204)
def delete_device_api(request): data = request.data json_data = json.loads(data) Id = json_data['device_id'] valid_input = Validate_Input(Id) if (not valid_input): # return HTTP 400. Bad request return ('Invalid data, Please check the documentation', 400) if "test" in json_data: test = json_data["test"] else: test = False db_context = open_connection(test) cur = db_context.cursor() cur.execute('SELECT * FROM public."Devices" WHERE "Id" = %s', (Id, )) # Fetching the result result_set = cur.fetchall() if (result_set == []): # return HTTP 404. Device not found close_connection(cur, db_context) return ('', 404) # Executing the query cur.execute('UPDATE public."Devices" SET "Active" = False WHERE "Id" = %s', (Id, )) db_context.commit() # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the Http 200 status to show a succcess status return ('', 200)
def view_api(request): """The View API returns a list of all the devices assigned to a customer""" customer_Id = request.args.get('customer_Id') test = False if not customer_Id: # Reading the parameters from the body data = request.data json_data = json.loads(data) # Saving the parameters as string customer_Id = json_data["customer_Id"] # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False valid_input = Validate_Input(customer_Id) if not valid_input: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204) # Opening the connection to the database db_context = open_connection(test) cur = db_context.cursor() # Executing the query cur.execute( 'SELECT * FROM public."Customers" c, public."CustomerLocations" cl, public."Locations" l WHERE c."Id" = cl."CustomerId" AND cl."LocationId" = l."Id" And c."Id" = %s', (customer_Id, )) # Fetching the result result_set = cur.fetchall() result = [] if not result_set: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. close_connection(cur, db_context) return ('', 204) colnames = [desc[0] for desc in cur.description] result = dict(zip(colnames, result_set[0])) response = {} response['customer_details'] = { 'Customer_Number': result['Customer_Number'], 'Location_Id': result['LocationId'], 'Location_Name': result['Name'] } cur.execute( 'SELECT * FROM public."Customers" c, public."CustomerDevices" cp, public."Devices" p WHERE p."Active" = True AND c."Id" = cp."CustomerId" AND cp."DeviceId" = p."Id" AND c."Id" = %s', (customer_Id, )) # Fetching the result result_set_device_list = cur.fetchall() result_device_list = [] # Checking to see if there are any devices associated with the customer if result_set_device_list: colnames_device_list = [desc[0] for desc in cur.description] for row in result_set_device_list: result_device_list.append(dict(zip(colnames_device_list, row))) response['customer_devices'] = [] for row in result_device_list: response['customer_devices'].append({ 'Device_Id': row['DeviceId'], 'Device_Name': row['Name'] }) # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the JSON object and the Http 200 status to show a succcess status return json.dumps(response), status.HTTP_200_OK
def edit_device_api(request): data = request.data json_data = json.loads(data) Name = json_data['Name'] Compressor_status = json_data['Compressor_status'] Fan_status = json_data['Fan_status'] Temperature = json_data['Temperature'] Ip_Address = json_data['Ip_Address'] Serial_Number = json_data['Serial_Number'] Mac_Address = json_data['Mac_Address'] Communication_Frequency = json_data['Communication_Frequency'] Installation_Date = json_data['Installation_Date'] Write_Frequency = json_data['Write_Frequency'] Write_Time = json_data['Write_Time'] Reporting_Url = json_data['Reporting_Url'] valid_input = Validate_Input(Name, Compressor_status, Fan_status, Temperature, Ip_Address, Serial_Number, Mac_Address, Communication_Frequency, Installation_Date, Write_Frequency, Write_Time, Reporting_Url) if (not valid_input): # Returning the HTTP code 400. Bad request return ('Invalid data, Please check the documentation', 400) Temperature_alert = '1' if Temperature > 80 else '0' Timestamp = str(time.strftime("%m/%d/%Y %H:%M:%S")) # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False db_context = open_connection(test) cur = db_context.cursor() # Executing the query cur.execute('SELECT * FROM public."Devices" WHERE "Mac_Address" = %s AND "Serial_Number" = %s',(Mac_Address, Serial_Number)) # Fetching the result result_set_check = cur.fetchall() exists = True # Checking to see if the device exists if(result_set_check == []): exists = False if (exists): Compressor_status_string = str(Compressor_status) Fan_status_string = str(Fan_status) Temperature_string = str(Temperature) Communication_Frequency_string = str(Communication_Frequency) Write_Frequency_string = str(Write_Frequency) Write_Time_string = str(Write_Time) Active = 'true' colnames = [desc[0] for desc in cur.description] device = result_set_check[0] # Saving the result as a key, value pair result = dict(zip(colnames,device)) Id = str(result['Id']) cur.execute('UPDATE public."Devices" SET "Name"=%s, "Compressor_status"=%s, "Fan_status"=%s, "Temperature_alert"=%s, "Temperature"=%s, "Ip_Address"=%s, "Communication_Frequency"=%s, "Write_Frequency"=%s, "Write_Time"=%s, "Reporting_Url"=%s, "Timestamp"=%s, "Active"=%s Where "Id"= %s', (Name, Compressor_status_string, Fan_status_string, Temperature_alert, Temperature_string, Ip_Address, Communication_Frequency_string, Write_Frequency_string, Write_Time_string, Reporting_Url, Timestamp, Active, Id)) db_context.commit() # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the Http 200 status to show a succcess status return ('', 200) close_connection(cur, db_context) # Return the Http 404 status to show that the device does not exist return ('Device does not exist', 404)
def add_device_api(request): data = request.data json_data = json.loads(data) Name = json_data['Name'] Compressor_status = json_data['Compressor_status'] Fan_status = json_data['Fan_status'] Temperature = json_data['Temperature'] Ip_Address = json_data['Ip_Address'] Serial_Number = json_data['Serial_Number'] Mac_Address = json_data['Mac_Address'] Communication_Frequency = json_data['Communication_Frequency'] Installation_Date = json_data['Installation_Date'] Write_Frequency = json_data['Write_Frequency'] Write_Time = json_data['Write_Time'] Reporting_Url = json_data['Reporting_Url'] valid_input = Validate_Input(Name, Compressor_status, Fan_status, Temperature, Ip_Address, Serial_Number, Mac_Address, Communication_Frequency, Installation_Date, Write_Frequency, Write_Time, Reporting_Url) if (not valid_input): # Returning the HTTP code 400. Bad request return ('Invalid data, Please check the documentation', 400) Temperature_alert = '1' if Temperature > 80 else '0' Timestamp = str(time.strftime("%m/%d/%Y %H:%M:%S")) # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False db_context = open_connection(test) cur = db_context.cursor() # Executing the query cur.execute('SELECT * FROM public."Devices" WHERE "Mac_Address" = %s AND "Serial_Number" = %s', (Mac_Address, Serial_Number)) # Fetching the result result_set_check = cur.fetchall() exists = False # Checking to see if the device exists if(result_set_check != []): exists = True if (exists): # Returning the HTTP code 204. Bad request return ('Device already exists', 204) Active = 'true' Compressor_status_string = str(Compressor_status) Fan_status_string = str(Fan_status) Temperature_string = str(Temperature) Communication_Frequency_string = str(Communication_Frequency) Write_Frequency_string = str(Write_Frequency) Write_Time_string = str(Write_Time) cur.execute('INSERT INTO public."Devices"("Name", "Compressor_status", "Fan_status", "Temperature_alert", "Temperature", "Ip_Address", "Serial_Number", "Mac_Address", "Communication_Frequency", "Installation_Date", "Write_Frequency", "Write_Time", "Reporting_Url", "Timestamp", "Active") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);',(Name, Compressor_status_string, Fan_status_string,Temperature_alert, Temperature_string, Ip_Address, Serial_Number, Mac_Address, Communication_Frequency_string, Installation_Date, Write_Frequency_string, Write_Time_string, Reporting_Url, Timestamp , Active)) db_context.commit() # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the Http 200 status to show a succcess status return ('', 200)
def write_immediate_api(request): """The Write Immidiate API is used to log each transaction to the database""" data = request.data json_data = json.loads(data) # Saving the parameters as string mac = json_data["mac"] serial = json_data["serial"] # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False valid_input = Validate_Input(json_data["mac"], json_data["serial"]) if not valid_input: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204) # Appending the paramters to the query string db_context = open_connection(test) cur = db_context.cursor() # Executing the query cur.execute( 'SELECT * FROM public."Devices" WHERE "Mac_Address" = %s AND "Serial_Number" = %s', (mac, serial)) # Fetching the result result_set = cur.fetchall() if not result_set: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. close_connection(cur, db_context) return ('', 204) colnames = [desc[0] for desc in cur.description] device = result_set[0] # Saving the result as a key, value pair result = dict(zip(colnames, device)) device_Id = str(result['Id']) valid_input = True status_at_event_comp = str(json_data["status_at_event_comp"]) # status_at_event_comp can only accept 0 or 1. if int(status_at_event_comp) < 0 or int(status_at_event_comp) > 1: valid_input = False status_at_event_fan = str(json_data["status_at_event_fan"]) # status_at_event_fan can only accept 0 or 1. if int(status_at_event_fan) < 0 or int(status_at_event_fan) > 1: valid_input = False status_after_event_comp = str(json_data["status_after_event_comp"]) # status_after_event_comp can only accept 0 or 1. if int(status_after_event_comp) < 0 or int(status_after_event_comp) > 1: valid_input = False status_after_event_fan = str(json_data["status_after_event_fan"]) # status_after_event_fan can only accept 0 or 1. if int(status_after_event_fan) < 0 or int(status_after_event_fan) > 1: valid_input = False restart_chk_comp = str(json_data["restart_chk_comp"]) # restart_chk_comp can only accept 0 or 1. if int(restart_chk_comp) < 0 or int(restart_chk_comp) > 1: valid_input = False restart_chk_fan = str(json_data["restart_chk_fan"]) # restart_chk_fan can only accept 0 or 1. if int(restart_chk_fan) < 0 or int(restart_chk_fan) > 1: valid_input = False Timestamp = str(time.strftime("%m/%d/%Y %H:%M:%S")) if valid_input: cur.execute( 'INSERT INTO public."DeviceEvents" ("DeviceId", "Status_At_Event_Compressor", "Status_At_Event_Fan", "Status_After_Event_Compressor", "Status_After_Event_Fan", "Restart_Check_Compressor", "Restart_Check_Fan", "Timestamp") VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', (device_Id, status_at_event_comp, status_at_event_fan, status_after_event_comp, status_after_event_fan, restart_chk_comp, restart_chk_fan, Timestamp)) db_context.commit() # Closing the databse connection before returning the result close_connection(cur, db_context) if valid_input: # Return the Http 200 status to show a succcess status return ('', 200) else: # Return an Http 400 status to show a bad request because of invalid data return ('Invalid data, Please check the documentation', 400)
def read_api(request): """The Read API returns the current status of a device""" # Starting a timer start = int(round(time.time() * 1000)) # Reading the parameters from the body data = request.data json_data = json.loads(data) mac = json_data["mac"] serial = json_data["serial"] valid_input = Validate_Input(json_data["mac"],json_data["serial"]) if not valid_input: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204) # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False # Appending the paramters to the query string db_context = open_connection(test) cur = db_context.cursor() # Executing the query # pyscopg2 will sanitize your query cur.execute('SELECT * FROM public."Devices" WHERE "Mac_Address" = %s AND "Serial_Number" = %s', (str(mac), str(serial))) # Fetching the result result_set = cur.fetchall() result = [] # Checking to see if we recieve any data if not result_set: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. close_connection(cur, db_context) return ('', 204) colnames = [desc[0] for desc in cur.description] device = result_set[0] # Saving the result as a key, value pair result = dict(zip(colnames,device)) response = {} response['comm_freq'] = result['Communication_Frequency'] # Passing the value of the Write_Frequency to the write_freq_display function in order to display the appropriate message response['write_freq'] = write_freq_display(result['Write_Frequency']) response['write_length_time'] = result['Write_Time'] # Passing the value of the Compressor_status to the conpressor_status_display function in order to display the appropriate message response['demand_resp_code'] = conpressor_status_display(result['Compressor_status']) #0=No event /1=Compressor Off (6min)/2=Compressor Off (12min)/ 3=Comp&Fan Off (12min) response['demand_resp_time'] = '' #time H:M:S if not test: response['time'] = time.strftime("%H:%M:%S") #current time response['reporting_url'] = result['Reporting_Url'] #url to report to. (If change, update Chip) response['mac'] = json_data["mac"] response['serial'] = json_data["serial"] # calculating the delay in milliseconds end = int(round(time.time() * 1000)) if not test: response['delay'] = end - start #Delay in milli-seconds after the event. # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the JSON object and the Http 200 status to show a success status return json.dumps(response),status.HTTP_200_OK
def view_device_api(request): """The View Device API returns the current status of the device to load the dashboard""" customer_Id = request.args.get('customer_Id') device_Id = request.args.get('device_Id') test = False if not customer_Id and not device_Id: # Reading the parameters from the body data = request.data json_data = json.loads(data) # Saving the parameters as string customer_Id = str(json_data["customer_Id"]) device_Id = str(json_data["device_Id"]) # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False valid_input = Validate_Input(customer_Id, device_Id) if not valid_input: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204) # Opening the connection to the database db_context = open_connection(test) cur = db_context.cursor() # Executing the query cur.execute( 'SELECT * FROM public."CustomerDevices" cp, public."Devices" p WHERE cp."DeviceId" = p."Id" AND cp."CustomerId" = %s AND p."Id" = %s', (customer_Id, device_Id)) # Fetching the result result_set = cur.fetchall() result = [] if not result_set: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. close_connection(cur, db_context) return ('', 204) colnames = [desc[0] for desc in cur.description] result = dict(zip(colnames, result_set[0])) response = {} if test: result['Timestamp'] = None response['Device_details'] = { 'Device_Id': result['DeviceId'], 'Device_Name': result['Name'], 'Fan_status': result['Fan_status'], 'Temperature_alert': result['Temperature_alert'], 'Temperature': result['Temperature'], 'Ip_Address': result['Ip_Address'], 'Serial_Number': result['Serial_Number'], 'Mac_Address': result['Mac_Address'], 'Communication_Frequency': result['Communication_Frequency'], 'Installation_Date': result['Installation_Date'], 'Write_Frequency': result['Write_Frequency'], 'Write_Time': result['Write_Time'], 'Timestamp': result['Timestamp'] } # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the JSON object and the Http 200 status to show a success status return json.dumps(response), status.HTTP_200_OK
def write_api(request): """The Write API updates the current state of the device in the database""" data = request.data json_data = json.loads(data) # Saving the parameters as string mac = json_data["mac"] serial = json_data["serial"] # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False valid_input = Validate_Input(mac, serial) if not valid_input: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204) db_context = open_connection(test) cur = db_context.cursor() # Executing the query cur.execute('SELECT * FROM public."Devices" WHERE "Mac_Address" = %s AND "Serial_Number" = %s', (mac, serial)) # Fetching the result result_set = cur.fetchall() if (result_set == []): # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. close_connection(cur, db_context) return ('', 204) # Setting a flag to check if the inputs are valid and within bounds before writing to the database valid_input = True Compressor_status = str(json_data["comp_status"]) # Compressor_status can only accept 0 or 1. if int(Compressor_status) < 0 or int(Compressor_status) > 1: valid_input = False Fan_status = str(json_data["fan_status"]) # Fan_status can only accept 0 or 1. if int(Fan_status) < 0 or int(Fan_status) > 1: valid_input = False Temperature_alert = str(json_data["temp_alert"]) # Temperature_alert can only accept 0 or 1. if int(Temperature_alert) < 0 or int(Temperature_alert) > 1: valid_input = False Temperature = str(json_data["temp"]) Timestamp = str(time.strftime("%m/%d/%Y %H:%M:%S")) Mac_Address = json_data["mac"] Serial_Number = json_data["serial"] if valid_input: cur.execute('UPDATE public."Devices" SET "Compressor_status"=%s, "Fan_status"=%s, "Temperature_alert"=%s, "Temperature"=%s, "Timestamp"=%s WHERE "Mac_Address" = %s AND "Serial_Number" = %s', (Compressor_status,Fan_status,Temperature_alert,Temperature,Timestamp,Mac_Address,Serial_Number)) db_context.commit() # Closing the databse connection before returning the result close_connection(cur, db_context) if valid_input: # Return the Http 200 status to show a succcess status return ('', 200) else: # Return an Http 400 status to show a bad request because of invalid data return ('Invalid data, Please check the documentation', 400)
def view_device_logs_api(request): """The View Device Logs API returns the logs for a device""" # Reading the parameters from the argument device_Id = request.args.get('device_Id') from_date = request.args.get('from_date') to_date = request.args.get('to_date') test = False if device_Id == None: # Reading the parameters from the body data = request.data json_data = json.loads(data) # Saving the parameters as string device_Id = str(json_data["device_Id"]) if from_date in json_data: from_date = str(json_data["from_date"]) if to_date in json_data: to_date = str(json_data["to_date"]) # Checking to see if the test value is passed to the API, If test is true, the testing database is used if "test" in json_data: test = json_data["test"] else: test = False # Opening the connection to the database db_context = open_connection(test) cur = db_context.cursor() valid_input = Validate_Input(device_Id) if not valid_input: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. return ('', 204) if (test): cur.execute( 'SELECT * FROM public."DeviceEvents" e WHERE e."DeviceId" = %s AND e."Id"=1', (device_Id, )) else: cur.execute( 'SELECT * FROM public."DeviceEvents" e WHERE e."DeviceId" = %s', (device_Id, )) # Fetching the result result_set = cur.fetchall() result = [] if not result_set: # Returning the HTTP code 204 because the server successfully processed the request, but is not returning any content. close_connection(cur, db_context) return ('', 204) colnames = [desc[0] for desc in cur.description] for row in result_set: result.append(dict(zip(colnames, row))) response = [] for data in result: add_to_result = True # Checking to see if it is the testing enviornment if not test: timestamp = data['Timestamp'] if from_date and to_date: from_date_parse = from_date.split('-') # YYYY MM DD to_date_parse = to_date.split('-') # YYYY MM DD date_parse = timestamp.split('/') date_parse[2] = date_parse[2].split(' ')[0] # MM DD YYYY # If the date lies inbetween the from and to date, TRUE is returned add_to_result = date_check(from_date_parse, to_date_parse, date_parse) else: timestamp = None # If true, the data is added to the response object if add_to_result: response.append({ 'Id': data['Id'], 'Device_Id': data['DeviceId'], 'Status_At_Event_Compressor': data['Status_At_Event_Compressor'], 'Status_At_Event_Fan': data['Status_At_Event_Fan'], 'Status_After_Event_Compressor': data['Status_After_Event_Compressor'], 'Status_After_Event_Fan': data['Status_After_Event_Fan'], 'Restart_Check_Compressor': data['Restart_Check_Compressor'], 'Restart_Check_Fan': data['Restart_Check_Fan'], 'Temperature': data['Temperature'], 'Timestamp': timestamp }) # Closing the databse connection before returning the result close_connection(cur, db_context) # Return the JSON object and the Http 200 status to show a success status return json.dumps(response), status.HTTP_200_OK