def sensor_traffic_Handler_from_Client1(Topic, jsonData):
      try:
        json_Dict = json.loads(jsonData)
        traffic = json_Dict['traffic']
        directions = json_Dict['directions']
        select_minortraffic ="select direction from project_minortraffic"
        cursor.execute(select_minortraffic)
        trafficinfo = cursor.fetchall()
        if(trafficinfo[0][0] == directions) :
             postgres_insert_queryupdate="""update project_minortraffic set traffic= %s where direction =%s"""
             cursor.execute(postgres_insert_queryupdate, (traffic,trafficinfo[0][0]))
        elif(trafficinfo[2][0] == directions):
            postgres_insert_queryupdate2 = """update project_minortraffic set traffic= %s where direction =%s"""
            cursor.execute(postgres_insert_queryupdate2, (traffic, trafficinfo[2][0]))
        elif(trafficinfo[3][0] == directions):
            postgres_insert_queryupdate3 = """update project_minortraffic set traffic= %s where direction =%s"""
            cursor.execute(postgres_insert_queryupdate3, (traffic, trafficinfo[3][0]))

        else :
             postgres_insert_queryupdate3 = """update project_minortraffic set traffic= %s where direction =%s"""
             cursor.execute(postgres_insert_queryupdate3, (traffic, trafficinfo[1][0]))
         #postgres_insert_query1 = """ INSERT INTO project_minortraffic (direction, traffic) VALUES (%s,%s)"""
         #record1_to_insert = (directions, traffic)
        #   cursor.execute("Rollback")
         #cursor.execute(postgres_insert_query1, record1_to_insert)
        connection.commit()
        count = cursor.rowcount
        print(count, "Record inserted successfully into minortraffic table")
        return(directions)


      finally:
        print("Inserted successfully")
def sensor_accident_Handler_from_Client1(Topic, jsonData):
    try:
        json_Dict = json.loads(jsonData)
        accident = json_Dict['accident']
        Direction = json_Dict['direction']
        select_minoraccident = "select direction from project_minoraccident"
        cursor.execute(select_minoraccident)
        accidentinfo = cursor.fetchall()

        if (accidentinfo[0][0] == Direction):
            postgres_queryupdate_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
            cursor.execute(postgres_queryupdate_accident,
                           (accident, accidentinfo[0][0]))
        elif (accidentinfo[2][0] == Direction):
            postgres_queryupdate2_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
            cursor.execute(postgres_queryupdate2_accident,
                           (accident, accidentinfo[2][0]))
        elif (accidentinfo[3][0] == Direction):
            postgres_queryupdate3_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
            cursor.execute(postgres_queryupdate3_accident,
                           (accident, accidentinfo[3][0]))
        else:
            postgres_queryupdate4_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
            cursor.execute(postgres_queryupdate4_accident,
                           (accident, accidentinfo[1][0]))
        connection.commit()
        count = cursor.rowcount
        print(count, "Record inserted successfully in table")
        return (Direction)

    finally:
        print("Insert into minor accident table")
def get_weatherdetails():
  try:
    postgreSQL_select_Query="SELECT * FROM project_weather"
    #connection.rollback()
    cursor.execute(postgreSQL_select_Query)
    tuple1 = {}
    weatherdetails = cursor.fetchall()
    #print(len(weatherdetails))
    #rows = cursor.fetchall()
    #print(weatherdetails)
    #print("Total rows are:  ", len(rows))
    return(weatherdetails)

    #for row in rows:
     #   print("temperature: ", row[0])
      #  print("chances of rain: ", row[1])
       # print("humidity: ", row[2])
        #print("id: ", row[3])
        #print("\n")
        #tuple1 = row
    #return(tuple1)

    #for row in rows:
     # while row is not None:
      #  tuple1 = row
    #return (tuple1)


  finally:
    #closing database connection.
        #if(connection):
         #   cursor.close()
          #  connection.close()
           print("data fetched successfully")
def weatherinfo(weatherdetails):
    Temperaturedetails = (weatherdetails[0].split(':'))[1]
    Windspeed = (weatherdetails[1].split(':'))[1]
    Description = (weatherdetails[2].split(':'))[1]
    Feelslike = (weatherdetails[3].split(':'))[1]
    Humidity = (weatherdetails[4].split(':'))[1]
    Pressure = (weatherdetails[5].split(':'))[1]
    Visibility =(weatherdetails[6].split(':'))[1]
    if(weatherdetails[7]=="Brampton"):
       direction="South to North"
    elif(weatherdetails[7]=="Ottawa"):
       direction = "North to South"
    elif(weatherdetails[7]=="Montreal"):
        direction = "East to West"
    else:
        direction="West to East"

    #return(Temperaturedetails)
    #print(Description)
    #print(Feelslike)
    #print(Humidity)
    #print(Pressure)
    #print(Visibility)
    Temperature=findtemperature(Temperaturedetails)
    now = datetime.now()
    created_at = findcreated_at(now)
    #postgres_insert_queryweather = """ INSERT INTO public.project_weather(temperature, humidity, created_at, created_time, windspeed, pressure, "Visibility", feels_like, description,direction) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
    postgres_insert_queryweather= """update public.project_weather set temperature= %s,humidity =%s,created_at=%s,created_time=%s, windspeed=%s,pressure=%s,"Visibility"=%s,feels_like=%s,description=%s where direction=%s"""
    record1_to_insert = (Temperature[0],Humidity,created_at, now, Windspeed, Pressure, Visibility, Feelslike, Description,direction)
          #   cursor.execute("Rollback")
    cursor.execute(postgres_insert_queryweather, record1_to_insert)
    connection.commit()
    count = cursor.rowcount
def get_V2ISafety():
    try:
        select_Query_V2I = "SELECT * FROM project_intersectionwarning"
        cursor.execute(select_Query_V2I)
        rows_intersectionwarning = cursor.fetchall()
        return (rows_intersectionwarning)

    finally:
        print("Data fetched from intersectionwarning table")
def get_surfacedata():
    try:
        postgreSQL_select_Query_surface = 'SELECT "Surface_Condition", "Surface_temp" FROM public."RWIS"'
        cursor.execute(postgreSQL_select_Query_surface)
        rows_surface = cursor.fetchall()
        return (rows_surface)

    finally:
        print("Data fetched from minoraccident table")
def get_clientdirectionfromdb():
    try:
        postgreSQL_clientdirection = "SELECT * FROM client_directions"
        cursor.execute(postgreSQL_clientdirection)
        clientdirectioninfo = cursor.fetchall()
        return (clientdirectioninfo)

    finally:
        print("Data fetched from client_directions table")
def get_emergencyinfo():
    try:
        emergencyquery = 'SELECT * FROM "Emergency communication"'
        cursor.execute(emergencyquery)
        rows_emeregency = cursor.fetchall()
        return (rows_emeregency)

    finally:
        print("Data fetched from emergency table")
def get_latlonginfo():
    try:
        postgreSQL_latlonginfo = "SELECT * FROM client_latlong"
        cursor.execute(postgreSQL_latlonginfo)
        rows_latlong = cursor.fetchall()
        return (rows_latlong)

    finally:
        print("Data fetched from minoraccident table")
示例#10
0
def get_roadinfo():
    try:
        postgreSQL_select_Query = "SELECT * FROM project_roadinfo"
        cursor.execute(postgreSQL_select_Query)
        rows_roadinfo = cursor.fetchall()
        return (rows_roadinfo)

    finally:
        print("Data fetched from roadinfo table")
示例#11
0
def get_minoraccidents():
    try:
        postgreSQL_select_Query = "SELECT * FROM project_minoraccident"
        cursor.execute(postgreSQL_select_Query)
        rows_minoraccident = cursor.fetchall()
        return (rows_minoraccident)

    finally:
        print("Data fetched from minoraccident table")
示例#12
0
def get_minortraffic():
    try:
        postgreSQL_minortraffic = "SELECT * FROM project_minortraffic"
        cursor.execute(postgreSQL_minortraffic)
        rows_minortraffic = cursor.fetchall()
        return (rows_minortraffic)

    finally:
        print("Data fetched from minortraffic table")
示例#13
0
def get_weatherdetails():
    try:
        postgreSQL_select_Query = "SELECT * FROM project_weather"
        cursor.execute(postgreSQL_select_Query)
        tuple1 = {}
        weatherdetails = cursor.fetchall()
        return (weatherdetails)

    finally:
        print("data fetched successfully")
def get_clientdirectionfromdb():
  try:
    postgreSQL_clientdirection="SELECT * FROM client_directions"
    cursor.execute(postgreSQL_clientdirection)
    clientdirectioninfo = cursor.fetchall()
    #print(clientdirectioninfo[0][0])
    #print(clientdirectioninfo[0][1])
    #print("Total rows are:  ", len(rows_roadinfo))
    return(clientdirectioninfo)

  finally:
    print("Data fetched from client_directions table")
def sensor_accident_Handler_from_Client1(Topic, jsonData):
  try:
     json_Dict = json.loads(jsonData)
     accident = json_Dict['accident']
     Direction = json_Dict['direction']
     select_minoraccident = "select direction from project_minoraccident"
     cursor.execute(select_minoraccident)
     accidentinfo = cursor.fetchall()
     #print(accidentinfo[0])
     if (accidentinfo[0][0] == Direction):
         postgres_queryupdate_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
         cursor.execute(postgres_queryupdate_accident, (accident, accidentinfo[0][0]))
     elif(accidentinfo[2][0] == Direction):
         postgres_queryupdate2_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
         cursor.execute(postgres_queryupdate2_accident, (accident, accidentinfo[2][0]))
     elif (accidentinfo[3][0] == Direction):
         #print(accidentinfo[3][0])
         postgres_queryupdate3_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
         cursor.execute(postgres_queryupdate3_accident, (accident, accidentinfo[3][0]))
     else:
         postgres_queryupdate4_accident = """update project_minoraccident set minor_accident= %s where direction =%s"""
         cursor.execute(postgres_queryupdate4_accident, (accident, accidentinfo[1][0]))
     connection.commit()
     count = cursor.rowcount
     print(count, "Record inserted successfully in table")
     return(Direction)

  # traffic = json_Dict['traffic']
  # if (Topic=='client1/accident'):
  # accident = json_Dict['accident']
  # print(accident)
  # print("hello" + jsonData)
  # subscribed_message=['jsonData']
  # print(subscribed_message)
  # for i in range(5, 100):
  # print(i)
  # directions="East to West"
  # directions = get_loc1()
  # msg = [("accident on lane 5 : Switch to lane 3"), ("accident on lane 5 : Switch to lane 10"),("accident on lane 5 : Switch to lane 15")]
  # total_message_client1 = len(msg)
  # total_message_client1 = len(jsonData)
  # for j in range(1, total_message_client1):
  # for subscribed_message in jsonData:
  # directions = "East to West"
  # postgres_insert_query = """ INSERT INTO project_minoraccident (direction, minor_accident) VALUES (%s,%s)"""
  # record_to_insert = (Direction, accident)
  # cursor.execute(postgres_insert_query, record_to_insert)

  finally:
    print("Insert into minor accident table")
示例#16
0
def register_page():

    if request.method == "POST":

        log = already_exist(login_filter(request.form.get("login")))
        password = password_filter(request.form.get("password"))
        copypassword = request.form.get("copypassword")

        if log is not None:
            if password == copypassword and password is not None:
                cursor.execute("""
                        INSERT INTO bhacklogins (login, password) VALUES ('{}', '{}')
                        """.format(str(log), str(password)))
                con.commit()
                return redirect("/login")
            else:
                flash("Password does not match!", "danger")
                return render_template("reg.html")

    return render_template("reg.html")
示例#17
0
def already_exist(login):
    user_info = cursor.execute("""
        SELECT login FROM bhacklogins where login = '******'
        """.format(login))
    user_info = cursor.fetchall()
    print(user_info)

    if len(user_info) != 0:
        flash("Username already exist@", "danger")
        return None
    else:
        return login
示例#18
0
def sensor_clientlocation_from_Client1(Topic, client_loc):
    try:
        client_info = client_loc.split(':')
        select_clientdirectioninfo = 'select "Name" from client_directions'
        cursor.execute(select_clientdirectioninfo)
        directioninfo = cursor.fetchall()
        if (client_info[0] == directioninfo[0][0]):
            print(client_info[0] + "Row already present")
        elif (client_info[0] == directioninfo[1][0]):
            print(client_info[0] + "Row already present")
        else:
            postgres_insert_query1 = """ INSERT INTO client_directions ("Name" , client_direction) VALUES (%s,%s)"""
            record1_to_insert = (client_info[0], client_info[1])
            cursor.execute(postgres_insert_query1, record1_to_insert)
            connection.commit()
            count = cursor.rowcount
            print(count,
                  "Record inserted successfully into client_directions table")
    finally:
        print("Inserted successfully")
        return (directioninfo[0][0])
示例#19
0
def sensor_clientlatlong_from_Client1(Topic, client_latlong):
    try:
        now = datetime.now()
        client_latlong = client_latlong.split(':')
        clientinfo = "select client_name from client_latlong"
        cursor.execute(clientinfo)
        client_nameinfo = cursor.fetchall()
        client_namelist = [item for t in client_nameinfo for item in t]
        if (client_latlong[0] in client_namelist):
            postgres_update_client_latlong = """update public.client_latlong set latitude= %s, longitude =%s ,created_time= %s where client_name=%s"""
            cursor.execute(
                postgres_update_client_latlong,
                (client_latlong[1], client_latlong[2], now, client_latlong[0]))

        else:
            insert_client_latlong = """ INSERT INTO public.client_latlong (client_name,latitude,longitude,created_time) VALUES (%s,%s,%s,%s)"""
            recordclientlatlong_to_insert = (client_latlong[0],
                                             client_latlong[1],
                                             client_latlong[2], now)
            cursor.execute(insert_client_latlong,
                           recordclientlatlong_to_insert)
        connection.commit()
        count = cursor.rowcount
        print(count, "Record inserted successfully into client_latlong table")
    finally:
        print("Inserted successfully")
示例#20
0
def login():
    if len(session.items()) > 1:
        return redirect("/mainPage")
    else:
        if request.method == "POST":
            log = login_filter(request.form.get("login"))
            password = password_filter(request.form.get("password"))

            login_inf = cursor.execute("""
            SELECT password FROM bhacklogins WHERE password = '******' and login = '******'
            """.format(password, log))
            login_inf = cursor.fetchall()

            # print(login_inf)

            if len(login_inf) == 0:
                return render_template("login.html")
            else:
                session["authenticated"] = True
                session["login"] = log
                return redirect("/mainPage")

        return render_template("login.html")
示例#21
0
def roadcond():
    postgreSQL_select_Query_roadcond = 'SELECT "Alert Message", "Road_Condition" FROM public."RoadConditions";'
    cursor.execute(postgreSQL_select_Query_roadcond)
    rows_surface = cursor.fetchall()
    return (rows_surface)
示例#22
0
dft = df.loc[:, ['SURFACE_CONDITION', 'SURFACE_TEMP', 'SURFACE_COND_NO']]

#print(dft)

road_cond = []

for i, row in df.iterrows():
    sc = df['SURFACE_COND_NO']
    st = df['SURFACE_TEMP']
    rcd = fis.road_condition(sc[i], st[i])
    mpl.rc('figure', max_open_warning=0)
    road_cond.append(rcd)
    coefficient = round(road_cond[i], 2)
    if (coefficient < 0.3):
        postgreSQL_insert_RC = 'UPDATE public."RoadConditions" SET "µ(slipperycoefficient)"=%s where "Road_Condition"=%s'
        cursor.execute(postgreSQL_insert_RC, (coefficient, "Very Slippery"))
    elif (0.3 <= coefficient < 0.5):
        postgreSQL_insert_RC = 'UPDATE public."RoadConditions" SET "µ(slipperycoefficient)"=%s where "Road_Condition"=%s'
        cursor.execute(postgreSQL_insert_RC, (coefficient, "Slippery"))
    elif (coefficient >= 0.5):
        postgreSQL_insert_RC = 'UPDATE public."RoadConditions" SET "µ(slipperycoefficient)"=%s where "Road_Condition"=%s'
        cursor.execute(postgreSQL_insert_RC, (coefficient, "Normal"))
    connection.commit()
    time.sleep(5)
    #print(sc[i], st[i], round(road_cond[i], 2))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(sc, st, road_cond, c='r', marker='o')
ax.set_xlabel('Surface condition')
示例#23
0
def store_settings():
    cursor.execute("""
                SELECT permit FROM bhacklogins WHERE login = '******'
                """.format(session['login']))
    inf = cursor.fetchall()[0]
    print(inf)
    if 'user' in inf:
        return redirect("/mainPage")
    elif 'admin' in inf:
        cursor.execute("""
        SELECT login FROM bhacklogins
        """)
        get_all_logins = cursor.fetchall()
        for items in range(len(get_all_logins)):
            get_all_logins[items] = str(get_all_logins[items]).replace(
                "(", "").replace(")", "").replace("'", "").replace(",", "")

        if request.method == "GET":
            try:
                md5_login = hashlib.md5(b"%b" % bytes(
                    unquote(str(request.query_string.decode()).split("=")[1]),
                    "utf-8")).hexdigest()
                if unquote(str(request.query_string.decode()).split("=")
                           [1]) in get_all_logins:
                    global md5_login_user
                    md5_login_user = hashlib.md5(b"%b" % bytes(
                        unquote(
                            str(request.query_string.decode()).split("=")[1]),
                        "utf-8")).hexdigest()
                    check_for_exist(md5_login=md5_login_user)
                    return render_template("admin_storage_template.html",
                                           render_login=get_all_logins,
                                           ld=os.listdir(parent_dir +
                                                         f"/{md5_login}"))
                else:
                    print(
                        unquote(
                            str(request.query_string.decode()).split("=")[1]))
                    rf = read_existed_file(
                        path=parent_dir + f"/{md5_login_user}" +
                        f"/{unquote(str(request.query_string.decode()).split('=')[1])}"
                    )
                    return render_template(
                        "admin_storage_template.html",
                        render_login=get_all_logins,
                        ld=os.listdir(parent_dir + f"/{md5_login_user}"),
                        read_file=rf,
                        fname=unquote(
                            str(request.query_string.decode()).split("=")[1]))
            except Exception:
                return redirect(
                    f"/mainPage/storage?{get_all_logins[0]}={get_all_logins[0]}"
                )
        elif request.method == "POST":
            if "del_storage" in request.form:
                try:
                    del_alg(
                        md5_login=md5_login_user,
                        file=unquote(
                            str(request.query_string.decode()).split("=")[1]))
                    return render_template("admin_storage_template.html",
                                           render_login=get_all_logins,
                                           ld=os.listdir(parent_dir +
                                                         f"/{md5_login_user}"))
                except Exception:
                    pass
        return render_template("admin_storage_template.html",
                               render_login=get_all_logins)
示例#24
0
def main_page():
    cursor.execute("""
            SELECT permit FROM bhacklogins WHERE login = '******'
            """.format(session['login']))
    inf = cursor.fetchall()[0]
    print(inf)
    if 'user' in inf:
        is_authenticated = session.get("authenticated")
        if not is_authenticated:
            return redirect("/login")

        if 'visits' not in session:
            session['visits'] = 0

        md5_login = hashlib.md5(b"%b" %
                                bytes(session['login'], "utf-8")).hexdigest()
        readed_bytes = ""
        alg_name = None
        check_for_exist(md5_login=md5_login)

        query_string = request.query_string.decode()

        if query_string:
            alg_name = str(query_string).split("=")[1]
            # print(alg_name)

        if request.method == "POST":
            cursor.execute("""
                SELECT create_new_files FROM bhacklogins
                """)
            inf = cursor.fetchone()
            if 0 in inf:
                if "logoutAlg" in request.form:
                    session.clear()
                    return redirect("/")
                else:
                    return redirect("/mainPage")
            elif 1 in inf:
                if "saveAlg" in request.form:
                    get_info = request.form.get("code_area_blog")
                    # print(request.form.get("alg_name_top"))
                    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    save_file(
                        path=parent_dir +
                        f"/{md5_login}/{str(request.form.get('alg_name_top')).replace(' ', '')}"
                    )
                    return redirect(f"/mainPage?{query_string}")
                elif "deleteAlg" in request.form:
                    del_alg(md5_login=md5_login, file=alg_name)
                    session.update()
                    return redirect("/mainPage")
                elif "new_one" in request.form:
                    session['visits'] = session.get('visits') + 1
                    check_for_exist(md5_login=md5_login)
                    create_file(session['visits'],
                                path=os.path.join(parent_dir, md5_login))
                elif "logoutAlg" in request.form:
                    session.clear()
                    return redirect("/")
                elif "compile_code" in request.form:
                    save_bin_file_to_user_bin_dir(md5login=md5_login,
                                                  filename=alg_name)
                    compile_output = run_saved_bin_and_delete(md5_login)
                    if alg_name is not None:
                        readed_bytes = read_existed_file(
                            path=parent_dir + f"/{md5_login}/{alg_name}")
                    return render_template("algorithm_template.html",
                                           ld=os.listdir(parent_dir +
                                                         f"/{md5_login}"),
                                           name=session['login'],
                                           get_name=alg_name,
                                           rb=readed_bytes,
                                           comp_outp=compile_output)

        elif request.method == "GET":
            try:
                if alg_name is not None:
                    if alg_name in query_string:
                        readed_bytes = read_existed_file(
                            path=parent_dir + f"/{md5_login}/{alg_name}")
            except Exception:
                return redirect("/mainPage")

        return render_template("algorithm_template.html",
                               ld=os.listdir(parent_dir + f"/{md5_login}"),
                               name=session['login'],
                               get_name=alg_name,
                               rb=readed_bytes)

    elif "admin" in inf:
        cursor.execute("""
                        SELECT reg_new_one,create_new_files FROM bhacklogins where login = '******'
                        """.format(session['login']))
        new_inf = cursor.fetchall()

        if request.method == "POST":
            if "new_reg" in request.form:
                if new_inf[0][0] == 0:
                    cursor.execute("""
                    UPDATE bhacklogins set reg_new_one = 1
                    """)
                    con.commit()
                elif new_inf[0][0] == 1:
                    cursor.execute("""
                    UPDATE bhacklogins set reg_new_one = 0
                    """)
                    con.commit()

            elif "change_stored" in request.form:
                if new_inf[0][1] == 0:
                    cursor.execute("""
                    UPDATE bhacklogins set create_new_files = 1
                    """)
                    con.commit()
                elif new_inf[0][1] == 1:
                    cursor.execute("""
                    UPDATE bhacklogins set create_new_files = 0
                    """)
                    con.commit()

        cursor.execute("""
            SELECT reg_new_one,create_new_files FROM bhacklogins where login = '******'
            """.format(session['login']))
        new_inf = cursor.fetchall()
        return render_template("registration_template.html",
                               md=new_inf[0][0],
                               upd=new_inf[0][1])
示例#25
0
def get_clientcordinates(clientname):
    getting_client_coordinates = "SELECT * FROM public.client_latlong where client_latlong.client_name=%s"
    connectedclientname = [clientname]
    cursor.execute(getting_client_coordinates, connectedclientname)
    rows_coordinates = cursor.fetchall()
    return (rows_coordinates)