Beispiel #1
0
def get_user(id):
    try:
        id = int(id)
    except:
        print("Invalid ID")
        return {"error": "Invalid ID"}, 400

    if not session.get('logged_in') or session['user']["id"] != id:
        return {'error': 'Authentication failed'}, 401

    db = DBConnection()
    user_query = "select * from user where id={}".format(id)
    db.cursor.execute(user_query)
    data = db.cursor.fetchone()

    if not data:
        return {'error': 'User does not exists'}, 404

    print(data)
    response = {
        "id": data[0],
        "fname": data[1],
        "lname": data[2],
        "email": data[3],
        "type": data[5]
    }

    return response
Beispiel #2
0
def get_txns(id):
    if not session.get('logged_in'):
        return {'error': 'Authentication failed'}, 401

    try:
        uid = int(id)
    except:
        print("Invalid user ID")
        return {"error": "Invalid ID"}, 400

    txn_query = "select * from transactions where user={}".format(uid)

    db = DBConnection()
    try:
        db.cursor.execute(txn_query)
        result = db.cursor.fetchall()
    except Exception as e:
        print(e)
        return {"error": "Error while getting the transactions"}, 500

    response = []
    for item in result:
        temp = {
            "id": item[0],
            "type": item[1],
            "price": item[2],
            "qty": item[3],
            "date_time": item[4],
            "amount": item[5],
            "user": item[6],
            "stock": item[7]
        }
        response.append(temp)

    return jsonify(response)
Beispiel #3
0
def get_portfolio(id):

    try:
        uid = int(id)
        # request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid ID'}, 400

    if not session.get('logged_in') or session['user']['id'] != uid:
        return {'error': 'Authentication failed'}, 401
    # uid = request_body.get('id')
    print(uid)

    # if not uid:
    #     return {'error': 'User ID is required'}, 400

    portfolio_query = "select * from all_portfolio where USERID={}".format(uid)

    db = DBConnection()
    try:
        db.cursor.execute(portfolio_query)
        result = db.cursor.fetchall()
    except Exception as e:
        print(e)
        return {"error": "Error while getting the portfolio"}, 500

    response = []
    if len(result) > 0:
        u = {
            "User ID": result[0][0],
            "User Firstname": result[0][1],
            "Buying Power": result[0][6]
        }
        response.append(u)

        for item in result:
            temp = {
                "Ticker": item[2],
                "Share Price": item[3],
                "No. of Shares owned": item[4],
                "Value of these shares": item[5]
            }
            response.append(temp)
    else:
        profile_query = "select * from all_profiles where USERID={}".format(
            uid)
        try:
            db.cursor.execute(profile_query)
            result = db.cursor.fetchone()
        except Exception as e:
            print(e)
            return {"error": "Error while getting the user profiles"}, 500
        u = {
            "User ID": result[0],
            "User Firstname": result[1],
            "Buying Power": result[2]
        }
        response.append(u)

    return jsonify(response)
def get_price_history(id):
    if not session.get('logged_in'):
        return {'error': 'Authentication failed'}, 401

    try:
        id = int(id)
    except:
        print("Invalid ID")
        return {"error": "Invalid ID"}, 400

    stock = get_stock_by_id(id)

    if not stock:
        return {"error": 'Stock does not exists'}, 404

    price_history_query = "select datetime, price from price_history where stock={} ORDER BY datetime desc".format(
        id)

    db = DBConnection()
    db.cursor.execute(price_history_query)
    data = db.cursor.fetchall()

    response = []

    for item in data:
        temp = {}
        temp['datetime'] = item[0]
        temp['price'] = item[1]

        response.append(temp)

    return jsonify(response)
Beispiel #5
0
def get_stocks():
    if not session.get('logged_in'):
        return {'error': 'Authentication failed'}, 401

    stock_query = """select stock.id, current_price, available_stocks, company.id as companyID, name, total_stocks, 
    address, about, code_name from stock join company on stock.company=company.id"""

    db = DBConnection()
    try:
        db.cursor.execute(stock_query)
        result = db.cursor.fetchall()
    except Exception as e:
        print(e)
        return {"error": "Error while getting the companies"}, 500

    response = []

    for item in result:
        temp = {
            "id": item[0],
            "current_price": item[1],
            "available_stocks": item[2],
            "company": item[3],
            "name": item[4],
            "total_stocks": item[5],
            "address": item[6],
            "about": item[7],
            "code_name": item[8]
        }
        response.append(temp)

    return jsonify(response)
Beispiel #6
0
def get_stock_by_id(id):
    db = DBConnection()
    stock_query = """select stock.id, current_price, available_stocks, 
    company.id as companyID, name, total_stocks, address, about, code_name from stock join company on stock.company=company.id 
    where stock.id={}""".format(id)

    db.cursor.execute(stock_query)
    data = db.cursor.fetchone()

    if not data:
        return

    stock = {
        "id": data[0],
        "current_price": data[1],
        "available_stocks": data[2],
        "company": data[3],
        "name": data[4],
        "total_stocks": data[5],
        "address": data[6],
        "about": data[7],
        "code_name": data[8]
    }

    return stock
Beispiel #7
0
def create_wallet():
    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400
    user = request_body.get('user')

    if not user:
        return {'error': 'User ID is required'}, 400

    if not session.get('logged_in') or session['user']["id"] != user:
        return {'error': 'Authentication failed'}, 401

    wallet_amount = 0

    wallet = get_user_wallet(user)

    if wallet:
        return {'error': 'Wallet for user already exists'}, 400

    wallet_create_query = """insert into wallet (owner, wallet_amount) VALUES ('{}', '{}')""".format(
        user, wallet_amount)

    db = DBConnection()
    try:
        db.cursor.execute(wallet_create_query)
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        print(e)
        return {"error": "Error while creating the wallet for user"}, 500

    wallet = get_user_wallet(user)

    return wallet
Beispiel #8
0
def update_company(id):

    if not session.get('logged_in') or session['user']["type"] != "admin":
        return {'error': 'Authentication failed'}, 401

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    try:
        id = int(id)
    except:
        print("Invalid ID")
        return {"error": "Invalid ID"}, 400

    company = get_company_by_id(id)

    if not company:
        return {'error': 'Company does not exists'}, 404

    update_string = ''

    if request_body.get('name'):
        update_string += "name='{}'".format(request_body['name'])

    if request_body.get('total_stocks') is not None and type(
            request_body.get('total_stocks')) != str:
        update_string += "total_stocks={}".format(request_body['total_stocks'])

    if request_body.get('address'):
        if update_string:
            update_string += ", "
        update_string += "address='{}'".format(request_body['address'])

    if request_body.get('about'):
        if update_string:
            update_string += ", "
        update_string += "about='{}'".format(request_body['about'])

    if not update_string:
        return company
    else:
        update_string += ' '

    update_query = """Update company set {update} where id={id}""".format(
        update=update_string, id=id)
    print(update_query)
    db = DBConnection()
    try:
        db.cursor.execute(update_query)
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        print(e)
        return {"error": "Error while updating the company"}, 500

    company = get_company_by_id(id)

    return company
Beispiel #9
0
def get_companies():

    company_query = "select * from company"

    if not session.get('logged_in'):
        return {'error': 'Authentication failed'}, 401

    db = DBConnection()
    try:
        db.cursor.execute(company_query)
        result = db.cursor.fetchall()
    except Exception as e:
        print(e)
        return {"error": "Error while getting the companies"}, 500

    response = []

    for item in result:
        temp = {
            "id": item[0],
            "name": item[1],
            "code_name": item[2],
            "total_stocks": item[3],
            "address": item[4],
            "about": item[5]
        }
        response.append(temp)

    return jsonify(response)
Beispiel #10
0
def register():
    session['logged_in'] = False

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    email = request_body.get('email')
    if not email:
        return {"error": "Email is required"}, 400
    db = DBConnection()
    email_exists_query = "select * from user where email='{}'".format(email)

    db.cursor.execute(email_exists_query)
    data = db.cursor.fetchone()
    if data:
        return {"error": "Email is already registered"}, 400

    if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
        return {"error": "Invalid email"}, 400

    try:
        fname = request_body['first_name']
        lname = request_body['last_name']
        password = request_body['password']
        user_type = request_body['type']
    except:
        print("Missing required field")
        return {"error": "Missing required field"}, 400

    salt = bcrypt.gensalt()
    password = bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')
    print(password)
    insert_query = """insert into user(fname, lname, email, password, type) 
                      values('{}', '{}', '{}', "{}", '{}')""".format(
        fname, lname, email, password, user_type)

    try:
        db.cursor.execute(insert_query)
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        print(e)
        return {"error": "Error while registring the user"}, 500

    retrieve_query = "select id, fname, lname, email, type from user where email='{}'".format(
        email)
    db.cursor.execute(retrieve_query)
    user_data = db.cursor.fetchone()

    user_data_json = {}
    user_data_json['id'] = user_data[0]
    user_data_json['fname'] = user_data[1]
    user_data_json['lname'] = user_data[2]
    user_data_json['email'] = user_data[3]
    user_data_json['type'] = user_data[4]

    return user_data_json
    def test_carPos_against_dbCoordinates(self):
        testState = False
        con = DBConnection()
        con.connectToDB()
        handler = GPSHandler()
        handler.setConnection(con)
        parser = JsonParser()
        parser.removeWantedAttribute("vehicle_speed")
        parser.addWantedAttribute("vehicle_speed",False)
        #list containing dictionaries
        list = parser.getResources("Resources/downtown-crosstown.json")
        #Go through the dataset - dictionary/line for line.
        for i in range(len(list)):

            time1 = list[i]["timestamp"]
            #if end of script is next, it means that we have read the last (lat,long) tuples in dataset.
            if("end_of_script" in list[i+1]):
                print("end_of_script")
                break
            else:
                #latitude always comes before longitude, in dataset.
                if(list[i]["name"]) == "latitude":
                    #print(list[i]["value"])
                    self.carLat = list[i]["value"]
                    #print("lat" + str(self.carLat))
                if(list[i+1]["name"]) == "longitude":
                    self.carLong = list[i+1]["value"]
                    #print("long" + str(self.carLong))

                #print("lat :" + str(self.carLat) + "    long : " + str(self.carLong))
                state = handler.compareCoordinates(self.carLat,self.carLong)
                print(state)
                if(state[0] == "A"):
                    print("que A")
                    testState = True
                elif(state[0] == "C"):
                    print("que C")
                    testState = True

                #time to sleep between next command --> virtual real time.
                time2 = list[i+1]["timestamp"]
                d = ((time2-time1)/1000000)
                #if(d >= 0):
                    #time.sleep(d)
        if(testState == False):
            self.fail()
Beispiel #12
0
def testModel(userId):
    print('Let us test the created model')
    db = DBConnection()
    dbUsername, dbPassword = db.getUserCredentials(userId)
    username = input('Enter username:\n').strip()
    if username != dbUsername:
        print('Removed the sample as username did not match')
        return
    print('Enter password:'******'data/user_input/{}/userData.csv'.format(userId),
                           header=0).tail(1)
    X = userData[[
        'release_codes', 'pp', 'pr', 'rp', 'rr', 'ppavg', 'pravg', 'rpavg',
        'rravg', 'total'
    ]]
    X = get_hashed_matrix(X)

    names = [
        "Isolation Forest Ensemble",
    ]

    classifiers = [
        IsolationForest(random_state=np.random.RandomState(42)),
    ]
    for name, clf in zip(names, classifiers):
        # print("\nLoading classifier : {}".format(name))
        clf = joblib.load('data/user_input/{}/userModel-{}.pkl'.format(
            userId, name))
        result = clf.predict(X)
        if result[0] == 1:
            print('Welcome')
        else:
            print('Stay away impostor!')


# testModel(114)
Beispiel #13
0
def enroll():
    db = DBConnection()
    success, dbId = db.addUserCredentials()
    if success != True:
        return False, None
    dbUsername, dbPassword = db.getUserCredentials(dbId)
    print('Starting the Enrollment process')
    counter = 0
    while counter < 2:
        print('Sample => {}'.format(counter + 1))
        username = input('Enter username:\n').strip()
        if username != dbUsername:
            print('Removed the sample as username did not match')
            continue
        print('Enter password:')
        user = linuxGetTimelog.User(dbId, dbUsername, dbPassword)
        success, date = user.startLogging()
        if success == True:
            extractFeatures(dbId, date)
            addToCSV(dbId, date)
            counter += 1
        sys.stdout.flush();
        tcflush(sys.stdin, TCIOFLUSH)
    db.closeConnection()
    global userId
    userId = dbId
    print("Enrollment Process over")
    return True, userId
Beispiel #14
0
def get_user_wallet(id):
    db = DBConnection()
    wallet_query = "select * from wallet where owner={}".format(id)

    db.cursor.execute(wallet_query)
    data = db.cursor.fetchone()

    if not data:
        return

    wallet = {'id': data[0], 'owner': data[1], 'wallet_amount': data[2]}

    return wallet
Beispiel #15
0
def update_company_stocks(id):
    if not session.get('logged_in') or session['user']["type"] != "admin":
        return {'error': 'Authentication failed'}, 401

    try:
        id = int(id)
    except:
        print("Invalid ID")
        return {"error": "Invalid ID"}, 400

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    stock = get_stock_by_company(id)

    if not stock:
        return {'error': 'Stock does not exists'}, 404
    stockId = stock['id']
    db = DBConnection()

    current_price = request_body.get('current_price')
    available_stocks = request_body.get('available_stocks')

    if not current_price and not available_stocks:
        return {'error': 'Missing required fields'}, 400

    if current_price and available_stocks:
        return {'error': 'You can update only one parameter at a time'}, 400

    if current_price:
        db.cursor.callproc("updatePrice", (stockId, current_price))
    else:
        update_query = "update stock set available_stocks={} where id={}".format(
            available_stocks, stockId)
        try:
            db.cursor.execute(update_query)
            db.conn.commit()
        except Exception as e:
            db.conn.rollback()
            print(e)
            return {'error': "Error while updating the data"}, 500

    stock = get_stock_by_company(id)

    return stock
Beispiel #16
0
def create_company():

    if not session.get('logged_in') or session['user']["type"] != "admin":
        return {'error': 'Authentication failed'}, 401

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    name = request_body.get('name')
    code_name = request_body.get('code')

    if name is None or code_name is None:
        return {'error': 'Missing required field'}, 400

    company = get_company_by_code(code_name)

    if company:
        return {'error': 'Company code already used'}, 400

    total_stocks = request_body.get('total_stocks', 0)
    address = request_body.get('address', '')
    about = request_body.get('about', '')

    company_create_query = """insert into company (name, code_name, total_stocks, address, about) 
                            VALUES ('{name}', '{code_name}', {total_stocks}, '{address}', '{about}')""".format(
        name=name,
        code_name=code_name,
        total_stocks=total_stocks,
        address=address,
        about=about)

    db = DBConnection()
    try:
        db.cursor.execute(company_create_query)
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        print(e)
        return {"error": "Error while creating the company"}, 500

    company = get_company_by_code(code_name)

    return company
Beispiel #17
0
def get_company_by_id(id):
    db = DBConnection()
    company_query = "select * from company where id={}".format(id)

    db.cursor.execute(company_query)
    data = db.cursor.fetchone()

    if not data:
        return

    company = {
        'id': data[0],
        'name': data[1],
        'code_name': data[2],
        'total_stocks': data[3],
        'address': data[4],
        'about': data[5]
    }

    return company
Beispiel #18
0
def update_wallet(id):

    try:
        id = int(id)
    except:
        print("Invalid ID")
        return {"error": "Invalid ID"}, 400

    wallet = get_wallet_by_id(id)

    if not wallet:
        return {'error': 'Wallet does not exists'}, 404

    if not session.get(
            'logged_in') or session['user']["id"] != wallet['owner']:
        return {'error': 'Authentication failed'}, 401

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    wallet_amount = request_body.get('wallet_amount')

    if wallet_amount is None:
        return {'error': 'Missing required field'}, 400

    wallet_update_query = """update wallet set wallet_amount={} where id={}""".format(
        wallet_amount, id)

    db = DBConnection()
    try:
        db.cursor.execute(wallet_update_query)
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        print(e)
        return {"error": "Error while updating the wallet for user"}, 500

    wallet = get_wallet_by_id(id)
    return wallet
Beispiel #19
0
def create_stock():
    if not session.get('logged_in') or session['user']["type"] != "admin":
        return {'error': 'Authentication failed'}, 401

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    company = request_body.get('company')

    if company is None:
        return {'error': 'Missing required field'}, 400

    current_price = request_body.get('current_price', 0)
    available_stocks = request_body.get('available_stocks', 0)

    stock = get_stock_by_company(company)

    if stock:
        return {'error': 'Company stock already exists'}, 400

    stock_create_query = """insert into stock (company, current_price, available_stocks) VALUES
    ({company}, {current_price}, {available_stocks})""".format(
        company=company,
        current_price=current_price,
        available_stocks=available_stocks)

    db = DBConnection()
    try:
        db.cursor.execute(stock_create_query)
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        print(e)
        return {"error": "Error while creating the stock"}, 500

    stock = get_stock_by_company(company)

    return stock
Beispiel #20
0
def sell():

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    user = request_body.get('user')
    print(user)

    if not user:
        return {'error': 'User ID is required'}, 400

    if not session.get('logged_in') or session['user']["id"] != user:
        return {'error': 'Authentication failed'}, 401

    try:
        stock = request_body['stock_id']
        qty = request_body['quantity']
    except:
        print("Missing required field")
        return {"error": "Missing required field"}, 400
    print(stock)
    print(qty)

    db = DBConnection()
    stock_exists_query = "select * from company where code_name='{}'".format(
        stock)

    db.cursor.execute(stock_exists_query)
    data = db.cursor.fetchone()
    if not data:
        return {"error": "Stock assigned to sell does not exist"}, 400

    try:
        db.cursor.callproc("sellStock", (stock, qty, user))
    except:
        return {"error": "Selling Failed"}, 400

    return {"Success": "Selling Request Completed Successfully "}, 200
Beispiel #21
0
def login():
    try:
        request_body = json.loads(request.data)
    except:
        return {"error": "Invalid request body"}, 400

    try:
        email = request_body['email']
        password = request_body['password']
    except:
        print("Missing required field")
        return {"error": "Missing required field"}, 400

    db = DBConnection()
    email_exists_query = "select * from user where email='{}'".format(email)

    db.cursor.execute(email_exists_query)
    data = db.cursor.fetchone()

    if not data:
        return {'error': 'Invalid email or password'}, 401

    stored_pwd = data[4]
    if not bcrypt.checkpw(password.encode('utf-8'),
                          stored_pwd.encode('utf-8')):
        print("Invalid password")
        return {'error': "Authentication failed"}, 401

    session['logged_in'] = True

    response = {
        "id": data[0],
        "fname": data[1],
        "lname": data[2],
        "email": data[3],
        "type": data[5]
    }
    session['user'] = response

    return response
Beispiel #22
0
def deposit():

    try:
        request_body = json.loads(request.data)
    except:
        return {"error": 'Invalid request body'}, 400

    user = request_body.get('user')
    print(user)

    if not user:
        return {'error': 'User ID is required'}, 400

    if not session.get('logged_in') or session['user']["id"] != user:
        return {'error': 'Authentication failed'}, 401

    try:
        dep_amt = request_body.get('deposit_amount')
    except:
        print("Missing required field")
        return {"error": "Missing required field"}, 400

    print(dep_amt)
    if dep_amt <= 0:
        return {"error": "Deposit at least 1 dollar"}, 400

    db = DBConnection()
    data = get_user_wallet(user)
    if not data:
        return {"error": "There's no wallet related to this User"}, 400

    try:
        db.cursor.callproc("depositAmount", (dep_amt, user))
    except:
        return {"error": "Deposit Failed"}, 400

    return {"Success": "Deposit Request Completed Successfully "}, 200
Beispiel #23
0
def main():
    '''
    WideAwake main process.
    '''

    #Variables to testuser to Database
    testuserID = "69"
    testcarID = "80085"
    testWeather = "DET REGNER :( "
    #set global variables gshHandler and connection. This will be tried to initialized, if successfull wideawake is online, else offline-mode.
    gsmHandler = None
    connection = None
    offlineConnection = None


    #Create a controller/object to controll the interface. Uncomment this when LED interface is connected
    #ledKontroll = LEDcontrols.LEDcontrols()
    #ledKontroll.setUpLeds(ledKontroll.leds)

    # data to calc acceleration
    currentTime = 0
    currentSpeed = 0

    # Data to check emergencies
    emergency = False
    emergencyTime = 0

    try:
        try:
            #gsmHandler = GSMHandler()
            #connect to database
            connection = DBConnection()
            connection.connectToDB()
            #ledKontroll.safe(True)
        except UnusableSystemException as e:
            print(str(e))
            #Since this exception occured, it means that there is something wrong with the gsmHandler. It could not
            #connect to the gsm module, or the connection did not connect correctly. Notify user that in offline mode.
            #ledKontroll.safe(False)
            raise e # rais this to exit the try online, and go to expect offline
        except Exception as e:
            print(str(e))
            #ledKontroll.safe(False)
            raise e # rais this to exit the try online, and go to expect offline


        #Uploads latest verson of database (retrived data) to the local database

        localdbConnection = SQLLite("Resources/WideAwakeCoordinates.db")
        localdbConnection.establishConnection()
        RefreshCacheLocal(connection, localdbConnection).start()

        #Initialize a GPSHandler, and set the connection to the external/cloud database, GPShandler also calculates the distance between car and slippery spot.
        handler = GPSHandler()
        handler.setConnection(connection)
        #Creates a testobject with the testdata
        car = Car()



        #Iterates through the testdata, when connected to cloud database
        while(car.next()):
            if(car.ABS):
                try:
                    """Takes the coordinates of the car and current timestamp and pushes it to the database """
                    #Should eventually change query to something else
                    date = datetime.datetime.now()
                    print(type(car.long[1]))
                    #inserts a testuserID, testcarID, weather_condition, coordinates as a timestamp and the current date and time. This is a temporary query and may be subject to change
                    queryToDB = "(INSERT INTO Coordinates(Latitude, longitude, timestamp) VALUES ( + n\
                    %s, %s, %s )) "
                    (car.lat[0] ,car.long[0] , date.strftime( "%m/%d/%y/%H/%M/%S"))
                    localdbConnection.executeInsertStatement(queryToDB)
                    print("Complete query")
                except Exception as e:
                    print(str(e))
                    raise e

            #Checks if the car is in a state of emergency
            if emergency:
                """
                if emergencyButton.isPressed():
                    emergency = False
                else if emergencyTime = car.timestamp[0] + 30:
                    gsmHandler.sendThatShit("Collision at longditude: ", car.long[0],", latitude: ", car.lat[0], ".")
                """
                pass

            #Every 300 line of testdate, check if the car has accelerated more the halv the current speed
            #if so, put it in a state of emergency(a crash might have happened)
            if car.tripCounter%300 == 0: #This is just under 2 seconds time
                prevTime = currentTime
                currentTime = car.timestamp[0]
                prevSpeed = currentSpeed
                currentSpeed = car.speed[0]
                try:
                    acc = (currentSpeed - prevSpeed)/(currentTime - prevTime)

                    if abs(acc) > abs(currentSpeed/2) and abs(currentSpeed) > 15:
                        emergency = True

                except ZeroDivisionError:
                    pass

            #every 50 line of testdata, check if the car is close to a slippery road
            if(car.tripCounter % 50 == 0):
                carSpeed = car.speed[0]
                if(carSpeed > 5):
                    #Detect if there is dangerous road condition ahead
                    gpsState = handler.compareCoordinates(car.lat[0], car.long[0])
                    if (gpsState[0] == 'A'):
                        print("DANGER")
         #               ledKontroll.dangerMode(True)
                    elif(gpsState[0] == 'C'):
                        print("Warning")
          #              ledKontroll.warningMode()
                    elif(gpsState[0] == 'N'):
                        print("Carry on")
           #             ledKontroll.safe(True)


    except:
        print("Kunne ikke koble til database")
        #Creates a testobject with thestData
        offlineCar = Car()

        #Connects to local dataabase
        offlineConnection = SQLLite("Resources/WideAwakeCoordinates.db")
        offlineConnection.establishConnection()

        #Initialize a offline GPShandler, that connects to the local database, and calculates distance between car and slippery spot.
        offlineHandler = GPSHandler()
        offlineHandler.setConnection(offlineConnection)

        #iterates through testdata, when connected to local database
        while(offlineCar.next()):
            if emergency:
                """
                if emergencyButton.isPressed():
                    emergency = False
                else if emergencyTime = car.timestamp[0] + 30:
                    gsmHandler.sendThatShit("Collision at longditude: ", car.long[0],", latitude: ", car.lat[0], ".")
                """
                pass

            if offlineCar.tripCounter % 300 == 0:  # This is just under 2 seconds time
                prevTime = currentTime
                currentTime = offlineCar.timestamp[0]
                prevSpeed = currentSpeed
                currentSpeed = offlineCar.speed[0]
                try:
                    acc = (currentSpeed - prevSpeed) / (currentTime - prevTime)

                    if abs(acc) > abs(currentSpeed / 2) and abs(currentSpeed) > 15:
                        emergency = True

                except ZeroDivisionError:
                    pass

            if(offlineCar.tripCounter % 50 == 0):
                carSpeed = offlineCar.speed[0]
                if(carSpeed > 5):
                    #Detect if there is's a dangerous road condition ahead.
                    gpsState = offlineHandler.offlineCompareCoordinates(offlineCar.lat[0], offlineCar.long[0])
                    if (gpsState[0] == 'A'):
                        print("DANGER")
         #               ledKontroll.dangerMode(True)
                    elif(gpsState[0] == 'C'):
                        print("Warning")
          #              ledKontroll.warningMode()
                    elif(gpsState[0] == 'N'):
                        print("Carry on")
           #             ledKontroll.safe(True)




    finally:
        #closes connection to cloud-database
        if(not connection == None):
            connection.closeConnection()
        #closes the gsmHandler
        if(not gsmHandler == None):
            gsmHandler.closeModem()
        #closes the offlineConnetion to the local database
        if(not offlineConnection == None):
            offlineConnection.closeConnection()
 def test_connection(self):
     con1 = DBConnection()
     self.assertTrue(con1.connectToDB()) #true if connection is established
     con1.closeConnection()
 def test_PullFromDB(self):
     con4 = DBConnection()
     con4.connectToDB()
     self.assertTrue(con4.pullFromDB())
     con4.closeConnection()
 def test_pushDuplicate(self):
     con3 = DBConnection()
     con3.connectToDB()
     self.assertFalse(con3.pushToDB(str(63.424156),str(10.393827))) #testing for duplicate coordinates to elgseterbrua. Should return false, because they are in the
     con3.closeConnection()
 def test_pushNoDuplicate(self):
     con2 = DBConnection()
     con2.connectToDB()
     self.assertTrue(con2.pushToDB(str(32.123466),str(33.123456))) #make sure these are uniqe (not in db).
     con2.closeConnection()
from Manager import Manager
from dbConnection import DBConnection
from flask import Flask
from flask import request
import requests


app = Flask(__name__)
# creating the device object
lotManager = Manager()

# create the database connection for it
managerCon = DBConnection()



if managerCon.createConnection():
    print("Conection successful")

print("Lots avaliable are: "+str(lotManager.lotsAvailable))

# write the API's for it
@app.route("/")
def home():
    return "Home app of the Manager App"

@app.route("/receiveStateChange")
def receiveStateChange():
    device = 'None'
    device = request.args.get('device')
    if device == 'lot':
Beispiel #29
0
from Device import Device
from dbConnection import DBConnection
from flask import Flask
from datetime import datetime
import requests
from status_led import status_change_led

app = Flask(__name__)
# creating the device object
lotSensor = Device()

# create the database connection for it
deviceCon = DBConnection()
if deviceCon.createConnection():
    print("Conection successfully")


def setupApp():
    # setting up the base tables for the database
    deviceCon.setupTables()

    # registering the lot with the manager
    requests.get('http://*****:*****@app.route("/")
def home():
    return "Home app of the Device App"
Beispiel #30
0
from Device import Device
from dbConnection import DBConnection
from flask import Flask
from flask import request
from datetime import datetime
from status_led import status_change_led
import requests

app = Flask(__name__)
# creating the device object
lotSensor = Device()

# create the database connection for it
deviceCon = DBConnection()
if deviceCon.createConnection():
    print("Conection successful")

# setting up the base tables for the database
deviceCon.setupTables()


# write the API's for it
@app.route("/")
def home():
    return "Home app of the Device App"


@app.route("/receiveStateChange")
def receiveStateChange():
    lotSensor.receiveStateChange()
    #timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Beispiel #31
0
from user import User
from dbConnection import DBConnection
import pytest
import argparse
from csv import reader
import base64
import os
import hashlib

db = DBConnection()


def main():
    with open('MOCK_DATA.csv', 'r') as read_obj:
        # pass the file object to reader() to get the reader object
        csv_reader = reader(read_obj)

    testUsers(csv_reader)


def test_connection():
    # assume rethinkdb is running, otherwise connection will fail
    with db.createConnection("database.db") as conn:
        assert conn.is_open() == True


def testUsers(userRows):
    header = next(userRows)

    if header != None:
        for elem in userRows:
 def test_parameter(self):
     con = DBConnection()
     con.connectToDB()
     handler = GPSHandler()
     state = handler.setConnection(con)
     self.assertTrue(state)