Skip to content

Instantly share code, notes, and snippets.

@dasguptaanika
Last active January 21, 2018 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dasguptaanika/1fa98a2fde9a97776090b703d9fe4d38 to your computer and use it in GitHub Desktop.
Save dasguptaanika/1fa98a2fde9a97776090b703d9fe4d38 to your computer and use it in GitHub Desktop.
Main Leap Motion API Program - Requires Some Extra Modules to be Installed.
################################################################################
# Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. #
# Leap Motion proprietary and confidential. Not for distribution. #
# Use subject to the terms of the Leap Motion SDK Agreement available at #
# https://developer.leapmotion.com/sdk_agreement, or another agreement #
# between Leap Motion and you, your company or other organization. #
################################################################################
import Leap, sys, thread, time, serial, smtplib, hashlib, getpass
import pymysql.cursors
loginEmail = str(raw_input("Enter Email: "))
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='toaster_secure',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
loginPswd = str(raw_input("Enter Password: "))
try:
with connection.cursor() as cursor:
#Read a Single record
sql = "SELECT `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, (loginEmail))
presult = str(cursor.fetchone())
finally:
connection.close()
#Splice presult
presult = str(presult[presult.index(":")+4:presult.index("}")-1])
h = hashlib.new("sha512")
h.update(loginPswd)
if h.hexdigest() == presult:
print "logged in!"
else:
print "Wrong password"
exit()
ser = serial.Serial("COM4", baudrate = 9600, timeout = 1)
bone0Startfile = open("bone0Startfile.txt","r+")
bone1Startfile = open("bone1Startfile.txt","r+")
bone0Startfile1 = open("bone0Startfile1.txt","r+")
bone1Startfile1 = open("bone1Startfile1.txt","r+")
gridInterval0 = 40
gridInterval1 = 20
realframeid = 0
userInput = raw_input("Record Password or Enter Password?").lower()
numberOfIncorrects = 0
numberOfCorrects = 0
passFrames = open("passFrames.txt","r+")
recordFrames = open("recordFrames.txt","r+")
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='toaster_secure',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
#Read a Single record
sql = "SELECT `username` FROM `users` WHERE `email`=%s"
cursor.execute(sql, (loginEmail))
presult = str(cursor.fetchone())
user = str(presult[presult.index(":")+4:presult.index("}")-1])
finally:
connection.close()
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
def sendValues(text):
ser.write(text.encode("utf-8"))
def converttolist1(a):
a = a.replace(")", "")
a = a.replace("(", "")
a = a.replace(" ", "")
a = a.replace("\n", "")
#print a
results = a.split(',')
#print results
if len(results) == 3:
result = map(float, results)
return result
else:
return None
def sendEmail():
global loginEmail
global user
currenttime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='toaster_secure',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "INSERT INTO `{}`(`status`, `reg_date`) VALUES (%s, %s)".format(user)
cursor.execute(sql, ("fail", currenttime))
connection.commit()
finally:
connection.close()
mail = smtplib.SMTP("smtp.gmail.com", 587)
mail.ehlo()
mail.starttls()
mail.login('purpletoasters17@gmail.com', 'Purple Toaster')
mail.sendmail('purpletoasters17@gmail.com', loginEmail, "Someone has attempted to open your safe!" + "\nSent at: " + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()))
mail.close()
class SampleListener(Leap.Listener):
finger_names = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']
bone_names = ['Metacarpal', 'Proximal', 'Intermediate', 'Distal']
def on_init(self, controller):
print "Initialized"
def on_connect(self, controller):
print "Connected"
def on_disconnect(self, controller):
# Note: not dispatched when running in a debugger.
print "Disconnected"
def on_exit(self, controller):
print "Exited"
def converttolist(self, a):
a = a.replace(")", "")
a = a.replace("(", "")
a = a.replace(" ", "")
a = a.replace("\n", "")
#print a
results = a.split(',')
#print results
try:
result = map(float, results)
except ValueError:
pass
def on_frame(self, controller):
global realframeid
global userInput
global numberOfCorrects
global numberOfIncorrects
global gridInterval0
global gridInterval1
# Get the most recent frame and report some basic information
frame = controller.frame()
print "Frame id: %d, timestamp: %d, hands: %d, fingers: %d" % (
realframeid, frame.timestamp, len(frame.hands), len(frame.fingers))
# Get hands
for hand in frame.hands:
## handType = "Left hand" if hand.is_left else "Right hand"
##
## print " %s, id %d, position: %s" % (
## handType, hand.id, hand.palm_position)
##
## # Get the hand's normal vector and direction
## normal = hand.palm_normal
## direction = hand.direction
##
## # Calculate the hand's pitch, roll, and yaw angles
## print " pitch: %f degrees, roll: %f degrees, yaw: %f degrees" % (
## direction.pitch * Leap.RAD_TO_DEG,
## normal.roll * Leap.RAD_TO_DEG,
## direction.yaw * Leap.RAD_TO_DEG)
## # Get arm bone
## arm = hand.arm
## print " Arm direction: %s, wrist position: %s, elbow position: %s" % (
## arm.direction,
## arm.wrist_position,
## arm.elbow_position)
# Get fingers
for finger in hand.fingers:
#if self.finger_names[finger.type] == "Index" or self.finger_names[finger.type] == "Thumb" or self.finger_names[finger.type] == "Middle": #(indent next lines till line 132)
print "%s finger, id: %d, length: %fmm, width: %fmm" % (
self.finger_names[finger.type],
finger.id,
finger.length,
finger.width)
# Get bones
#for b in range(0, 4): (indent next regions)
#1st Bone
bone = finger.bone(0)
print "Bone: %s, start: %s, end: %s, direction: %s" % (
self.bone_names[bone.type],
bone.prev_joint,
bone.next_joint,
bone.direction)
if userInput == 'record':
bone0Startfile.write(str(bone.prev_joint) + "\n")
else:
bone0Startfile1.write(str(bone.prev_joint) + "\n")
#2nd Bone
bone = finger.bone(2)
print "Bone: %s, start: %s, end: %s, direction: %s" % (
self.bone_names[bone.type],
bone.prev_joint,
bone.next_joint,
bone.direction)
if userInput == 'record':
bone1Startfile.write(str(bone.prev_joint) + "\n")
else:
bone1Startfile1.write(str(bone.prev_joint) + "\n")
"""else:
a = str(bone1Startfile.readline())
#print a
bone1StartPos = self.converttolist(a)
recordedbone1StartPos = self.converttolist(str(bone.prev_joint))
#print bone1StartPos
#print recordedbone1StartPos
if abs(int(bone1StartPos[0])) - abs(int(recordedbone1StartPos[0])) <= gridInterval and abs(int(bone1StartPos[2])) - abs(int(recordedbone1StartPos[2])) <= gridInterval and abs(int(bone1StartPos[1])) - abs(int(recordedbone1StartPos[1])) <= gridInterval:
print "Correct."
numberOfCorrects += 1
else:
print "Incorrect Password."
numberOfIncorrects += 1"""
realframeid += 1
if not frame.hands.is_empty:
print ""
def recordPass():
global realframeid
global passFrames
# Create a sample listener and controller
listener = SampleListener()
controller = Leap.Controller()
if(controller.is_connected == False):
print("Waiting for controller...");
while(not(controller.is_connected)):
time.sleep(1);
print("Controller Connected.")
# Keep this process running until Enter is pressed
print "Press Enter to record password."
print "Tip: Record with large motions for most secure passwords!"
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
# Have the sample listener receive events from the controller
controller.add_listener(listener)
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
# Remove the sample listener when done
controller.remove_listener(listener)
passFrames.write(str(realframeid))
bone0Startfile.close()
passFrames.close()
def enterPass():
global realframeid
global numberOfCorrects
global numberOfIncorrects
global passFrames
global bone0Startfile1
global bone1Startfile1
global gridInterval0
global gridInterval1
listener = SampleListener()
controller = Leap.Controller()
if(controller.is_connected == False):
print("Waiting for controller...");
while(not(controller.is_connected)):
time.sleep(1);
print("Controller Connected.")
# Keep this process running until Enter is pressed
print "Press Enter to enter password."
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
# Have the sample listener receive events from the controller
controller.add_listener(listener)
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
# Remove the sample listener when done
controller.remove_listener(listener)
listOfFrame0Dif = []
listOfFrame1Dif = []
listOfPass0Frames = []
listOfPass0Frames1 = []
listOfPass1Frames = []
listOfPass1Frames1 = []
listOfRecorded0Frames = []
listOfRecorded0Frames1 = []
listOfRecorded1Frames = []
listOfRecorded1Frames1 = []
rightFrames = int(passFrames.readline())
bone0Startfile1.close()
recordFrames = int(file_len("bone0Startfile1.txt"))
bone0Startfile1 = open("bone0Startfile1.txt", "r+")
recordedFrames = recordFrames
bone1Startfile1.close()
recordedFrames1 = int(file_len("bone1Startfile1.txt"))
bone1Startfile1 = open("bone1Startfile1.txt", "r+")
for frameLEAP in range(min(rightFrames,recordedFrames,recordedFrames1)):
listOfPass0Frames1.append(converttolist1(bone0Startfile.readline()))
listOfRecorded0Frames1.append(converttolist1(bone0Startfile1.readline()))
listOfPass1Frames1.append(converttolist1(bone1Startfile.readline()))
listOfRecorded1Frames1.append(converttolist1(bone1Startfile1.readline()))
for x in range(len(listOfPass0Frames1)):
if listOfPass0Frames1[x] != None:
if not(any(i is None for i in listOfPass0Frames1[x])):
if len(listOfPass0Frames1[x]) == 3:
listOfPass0Frames.append(listOfPass0Frames1[x])
for x in range(len(listOfPass1Frames1)):
if listOfPass1Frames1[x] != None:
if not(any(i is None for i in listOfPass1Frames1[x])):
if len(listOfPass1Frames1[x]) == 3:
listOfPass1Frames.append(listOfPass1Frames1[x])
for x in range(len(listOfRecorded0Frames1)):
if listOfRecorded0Frames1[x] != None:
if not(any(i is None for i in listOfRecorded0Frames1[x])):
if len(listOfRecorded0Frames1[x]) == 3:
listOfRecorded0Frames.append(listOfRecorded0Frames1[x])
for x in range(len(listOfRecorded1Frames1)):
if listOfRecorded1Frames1[x] != None:
if not(any(i is None for i in listOfRecorded1Frames1[x])):
if len(listOfRecorded1Frames1[x]) == 3:
listOfRecorded1Frames.append(listOfRecorded1Frames1[x])
if recordedFrames > rightFrames + 200 or recordedFrames < rightFrames - 200:
numberOfCorrects = 0
Distances0X = []
Distances0Y = []
Distances0Z = []
Distances1X = []
Distances1Y = []
Distances1Z = []
"""print listOfPass0Frames
print listOfRecorded0Frames
"""
rightFrames = len(listOfPass0Frames)
rightFrames1 = len(listOfPass1Frames)
recordedFrames = len(listOfRecorded0Frames)
recordedFrames1 = len(listOfRecorded1Frames)
for frameLEAP in range(min(rightFrames,rightFrames1,recordedFrames,recordedFrames1)):
listOfFrame0Dif.append([listOfPass0Frames[frameLEAP][0]-listOfRecorded0Frames[frameLEAP][0],listOfPass0Frames[frameLEAP][1]-listOfRecorded0Frames[frameLEAP][1],listOfPass0Frames[frameLEAP][2]-listOfRecorded0Frames[frameLEAP][2]])
Distances0X.append(listOfFrame0Dif[frameLEAP][0])
Distances0Y.append(listOfFrame0Dif[frameLEAP][1])
Distances0Z.append(listOfFrame0Dif[frameLEAP][2])
AverageDistance0X = mean(Distances0X)
AverageDistance0Y = mean(Distances0Y)
AverageDistance0Z = mean(Distances0Z)
gridInterval0X = abs(gridInterval0) + abs(AverageDistance0X)
gridInterval0Y = abs(gridInterval0) + abs(AverageDistance0Y)
gridInterval0Z = abs(gridInterval0) + abs(AverageDistance0Z)
'''for frameLEAP in range(min(rightFrames,rightFrames1,recordedFrames,recordedFrames1)):
listOfRecorded0Frames[frameLEAP][0] = listOfRecorded0Frames[frameLEAP][0] + AverageDistance0X
listOfRecorded0Frames[frameLEAP][1] = listOfRecorded0Frames[frameLEAP][1] + AverageDistance0Y
listOfRecorded0Frames[frameLEAP][2] = listOfRecorded0Frames[frameLEAP][2] + AverageDistance0Z'''
for frameLEAP in range(min(rightFrames,rightFrames1,recordedFrames,recordedFrames1)):
if abs(listOfPass0Frames[frameLEAP][0]-listOfRecorded0Frames[frameLEAP][0]) < gridInterval0X and abs(listOfPass0Frames[frameLEAP][1]-listOfRecorded0Frames[frameLEAP][1]) < gridInterval0Y and abs(listOfPass0Frames[frameLEAP][2]-listOfRecorded0Frames[frameLEAP][2]) < gridInterval0Z:
numberOfCorrects +=1
else:
numberOfIncorrects +=1
for frameLEAP in range(min(rightFrames,rightFrames1,recordedFrames,recordedFrames1)):
listOfFrame1Dif.append([listOfPass1Frames[frameLEAP][0]-listOfRecorded1Frames[frameLEAP][0],listOfPass1Frames[frameLEAP][1]-listOfRecorded1Frames[frameLEAP][1],listOfPass1Frames[frameLEAP][2]-listOfRecorded1Frames[frameLEAP][2]])
Distances1X.append(listOfFrame1Dif[frameLEAP][0])
Distances1Y.append(listOfFrame1Dif[frameLEAP][1])
Distances1Z.append(listOfFrame1Dif[frameLEAP][2])
AverageDistance1X = mean(Distances1X)
AverageDistance1Y = mean(Distances1Y)
AverageDistance1Z = mean(Distances1Z)
gridInterval1X = abs(gridInterval1) + abs(AverageDistance1X)
gridInterval1Y = abs(gridInterval1) + abs(AverageDistance1Y)
gridInterval1Z = abs(gridInterval1) + abs(AverageDistance1Z)
'''for frameLEAP in range(min(rightFrames,rightFrames1,recordedFrames,recordedFrames1)):
listOfRecorded1Frames[frameLEAP][0] = listOfRecorded1Frames[frameLEAP][0] + AverageDistance1X
listOfRecorded1Frames[frameLEAP][1] = listOfRecorded1Frames[frameLEAP][1] + AverageDistance1Y
listOfRecorded1Frames[frameLEAP][2] = listOfRecorded1Frames[frameLEAP][2] + AverageDistance1Z'''
for frameLEAP in range(min(rightFrames,rightFrames1,recordedFrames,recordedFrames1)):
if abs(listOfPass1Frames[frameLEAP][0]-listOfRecorded1Frames[frameLEAP][0]) < gridInterval1X and abs(listOfPass1Frames[frameLEAP][1]-listOfRecorded1Frames[frameLEAP][1]) < gridInterval1Y and abs(listOfPass1Frames[frameLEAP][2]-listOfRecorded1Frames[frameLEAP][2]) < gridInterval1Z:
print "Correct."
numberOfCorrects +=1
else:
print "Incorrect."
numberOfIncorrects +=1
print numberOfCorrects
print numberOfIncorrects
def main():
global loginEmail
if userInput == 'record':
recordPass();
print "Password recorded. Press enter to close."
try:
sys.stdin.readline()
except KeyboardInterrupt:
exit()
elif userInput == 'enter':
enterPass();
if 2*numberOfIncorrects < numberOfCorrects:
return "You passed!"
input()
else:
return "You failed..."
input()
else:
print('Invalid Input.')
input();
if __name__ == '__main__':
FinalResult = main();
print FinalResult
if FinalResult == "You failed...":
sendEmail()
if FinalResult == "You passed!":
sendValues("2")
raw_input("Press enter to lock safe again.")
sendValues("1")
ser.close()
input();
bone0Startfile.close()
bone0Startfile1.close()
bone1Startfile.close()
bone1Startfile1.close()
recordFrames.close()
passFrames.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment