예제 #1
0
def startThreads():
    mic.threshold,vibration.threshold,motion.threshold,light.threshold = thresholds.sound,thresholds.vibration,thresholds.motion,thresholds.light
    thL = threading.Thread(target=light)
    thMic = threading.Thread(target=mic)
    thMot = threading.Thread(target=motion)
    thPV = threading.Thread(target=vibration)
    thL.start(),thMic.start(),thMot.start(),thPV.start()
    thL.join(),thMic.join(),thMot.join(),thPV.join()
    
    c.light,c.mic,c.motion,c.vibration = light.lightDelta,mic.thresh,motion.average,vibration.average
    
    s.state, s.stateTitle = getStates(light.state,mic.state,motion.state,vibration.state)
    
    date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    putToFirebase(date, mic.state,vibration.state, motion.state,light.state,mic.threshold,vibration.threshold,motion.threshold,light.threshold,s.stateTitle, 0, 0, phone.number)
    
    
    lcd.setOption('State',s.stateTitle)
    lcd.setLCDState(s.state)
    
    redLight.write(0),blueLight.write(0)
    if s.state != 3:
        buzzer.playSound(s.state)
    elif s.state == 2:
        changLightState(blueLight),blueLight.write(1)
        buzzer.playSound(s.state)
    elif s.state == 3:
        bot.send_message(149374407,'PARTY HARD!!!')
        sms.sendSMS(phone.number)
        buzzer.playSound(s.state)
        changLightState(redLight),redLight.write(1)
예제 #2
0
def checkRate():
    try:
        content = htmlHandle.get(url,'')
        content = BeautifulSoup.BeautifulSoup(content)
        
        for tr in content.findAll('tr',{'class':'row-container-upper'}):
            tds = tr.findAll('th')
            for i,td in enumerate(tds):
                times = td.contents[0]
                dic[i] = times.strip()
        
        for tr in content.findAll('tr',{'class':'row-container-percentage'}):
            tds = tr.findAll('td')
            for i,td in enumerate(tds):
                rate = td.contents[0]
                dic[dic[i]] = rate.strip()
                print dic[i],dic[dic[i]]
                del dic[i]
        if dic[u'18期'] == '0%':
            sms.sendSMS("MBP免18期手续费啦!",6)
            sys.exit()
        elif dic[u'24期'] == '0%':
            sms.sendSMS("MBP免24期手续费啦!",6)
            sys.exit()
    except Exception, e:
        print e
예제 #3
0
def checkRate():
    try:
        content = htmlHandle.get(url, '')
        content = BeautifulSoup.BeautifulSoup(content)

        for tr in content.findAll('tr', {'class': 'row-container-upper'}):
            tds = tr.findAll('th')
            for i, td in enumerate(tds):
                times = td.contents[0]
                dic[i] = times.strip()

        for tr in content.findAll('tr', {'class': 'row-container-percentage'}):
            tds = tr.findAll('td')
            for i, td in enumerate(tds):
                rate = td.contents[0]
                dic[dic[i]] = rate.strip()
                print dic[i], dic[dic[i]]
                del dic[i]
        if dic[u'18期'] == '0%':
            sms.sendSMS("MBP免18期手续费啦!", 6)
            sys.exit()
        elif dic[u'24期'] == '0%':
            sms.sendSMS("MBP免24期手续费啦!", 6)
            sys.exit()
    except Exception, e:
        print e
예제 #4
0
def sos():
    if 'userid' in session:

        userid = session.get('userid')
        cursor.execute(
            """SELECT `name` FROM `users` WHERE `userid` = '{}'""".format(
                userid))
        name = cursor.fetchall()
        name = name[0][0]
        cursor.execute(
            """SELECT `ec1` FROM `users` WHERE `userid` = '{}'""".format(
                userid))
        ec1 = cursor.fetchall()
        number1 = ec1[0][0]
        cursor.execute(
            """SELECT `ec2` FROM `users` WHERE `userid` = '{}'""".format(
                userid))
        ec2 = cursor.fetchall()
        number2 = ec2[0][0]
        #print(number1)
        sms.sendSMS(number1, number2, name)
        #sms.sendSMS(number2,name)
        return redirect('/home')

    else:
        print('failed')
예제 #5
0
def main():
    trash_filename = "trash.jpg"
    try:
        cam = initCamera()
        while True:
            """
            """
            score = 0
            for i in range(5):
                takePhoto(cam, trash_filename)
                data = (post_imageV2("TrashIdentifier_968106762", trash_filename, ibm_auth))
                print(data['images'][0]['classifiers'][0]['classes'][0]['score'])
                score += (data['images'][0]['classifiers'][0]['classes'][0]['score'])
            
            score /= 5
            print(score)

            if score > 0.20:
                print("Is trash")
                sendSMS("Garbage can is full!!!!", "+16465411524")
                time.sleep(2)

            else:
                print("Not trash")

    except KeyboardInterrupt:
        print("Quitting Application")
예제 #6
0
def startThreads():
    mic.threshold, vibration.threshold, motion.threshold, light.threshold = thresholds.sound, thresholds.vibration, thresholds.motion, thresholds.light
    thL = threading.Thread(target=light)
    thMic = threading.Thread(target=mic)
    thMot = threading.Thread(target=motion)
    thPV = threading.Thread(target=vibration)
    thL.start(), thMic.start(), thMot.start(), thPV.start()
    thL.join(), thMic.join(), thMot.join(), thPV.join()

    c.light, c.mic, c.motion, c.vibration = light.lightDelta, mic.thresh, motion.average, vibration.average

    s.state, s.stateTitle = getStates(light.state, mic.state, motion.state,
                                      vibration.state)

    date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    putToFirebase(date, mic.state, vibration.state, motion.state, light.state,
                  mic.threshold, vibration.threshold, motion.threshold,
                  light.threshold, s.stateTitle, 0, 0, phone.number)

    lcd.setOption('State', s.stateTitle)
    lcd.setLCDState(s.state)

    redLight.write(0), blueLight.write(0)
    if s.state != 3:
        buzzer.playSound(s.state)
    elif s.state == 2:
        changLightState(blueLight), blueLight.write(1)
        buzzer.playSound(s.state)
    elif s.state == 3:
        bot.send_message(149374407, 'PARTY HARD!!!')
        sms.sendSMS(phone.number)
        buzzer.playSound(s.state)
        changLightState(redLight), redLight.write(1)
예제 #7
0
def validatepin(request):
    if 'machine' not in request.session:
        return redirect('/user/')
    if 'cardnumber' not in request.session:
        return redirect('/user/card/')
    if 'pinverified' in request.session:
        return redirect('/user/options/')
    atmcard = ATM_Card.objects.get(atmcard_num=request.session['cardnumber'])
    username = atmcard.name
    request.session['username'] = username

    if request.method == 'POST':
        try:
            cardpin = request.POST['pincode']
            if int(atmcard.pin) == int(cardpin):
                request.session['pinverified'] = True
                request.session.set_expiry(300)

                if atmcard.two_factor:
                    request.session['passcode'] = random.randint(1000, 9999)
                    print request.session['passcode']
                    sms.sendSMS(atmcard.phone_num,
                                'PASSCODE:%d' % request.session['passcode'])
                    return redirect('/user/validatepasscode')
                return redirect('/user/options')
            if 'pinattempt' not in request.session:
                request.session['pinattempt'] = 1
            else:
                request.session[
                    'pinattempt'] = request.session['pinattempt'] + 1

            if request.session['pinattempt'] == 1:
                pinmessage = 1
            elif request.session['pinattempt'] == 2:
                pinmessage = 2
            else:
                pinmessage = 3
                atmcard.card_status = False
                atmcard.save()
                request.session.flush()
        except:
            e = sys.exc_info()[1]
            if 'pinattempt' not in request.session:
                request.session['pinattempt'] = 1
            else:
                request.session[
                    'pinattempt'] = request.session['pinattempt'] + 1
            if request.session['pinattempt'] == 1:
                pinmessage = 1
            elif request.session['pinattempt'] == 2:
                pinmessage = 2
            else:
                pinmessage = 3
                atmcard.card_status = False
                atmcard.save()
                request.session.flush()
    return render_to_response('finale/pincode.html', locals())
예제 #8
0
파일: views.py 프로젝트: bhargav/SE-ATM
def validatepin(request):
	if 'machine' not in request.session:
		return redirect('/user/')
	if 'cardnumber' not in request.session:  
		return redirect('/user/card/')
	if 'pinverified' in request.session:       
		return redirect('/user/options/')
	atmcard = ATM_Card.objects.get(atmcard_num=request.session['cardnumber'])
	username = atmcard.name
	request.session['username'] = username        
	
	if request.method == 'POST': 
		try:
			cardpin = request.POST['pincode']         
			if int(atmcard.pin) == int(cardpin):         
				request.session['pinverified'] = True
				request.session.set_expiry(300)

				if atmcard.two_factor:
					request.session['passcode']=random.randint(1000,9999)
					print request.session['passcode']
					sms.sendSMS(atmcard.phone_num, 'PASSCODE:%d' % request.session['passcode'])
					return redirect('/user/validatepasscode')       
				return redirect('/user/options')
			if 'pinattempt' not in request.session:
				request.session['pinattempt'] = 1
			else:
				request.session['pinattempt'] = request.session['pinattempt'] + 1
			
			if request.session['pinattempt'] == 1:
					pinmessage = 1
			elif request.session['pinattempt'] == 2:
					pinmessage = 2
			else:
					pinmessage = 3
					atmcard.card_status = False
					atmcard.save()
					request.session.flush()
		except:
			e = sys.exc_info()[1]
			if 'pinattempt' not in request.session:
				request.session['pinattempt'] = 1
			else:
				request.session['pinattempt'] = request.session['pinattempt'] + 1
			if request.session['pinattempt'] == 1:
					pinmessage = 1
			elif request.session['pinattempt'] == 2:
					pinmessage = 2
			else:
					pinmessage = 3
					atmcard.card_status = False
					atmcard.save()
					request.session.flush()	  			
	return render_to_response('finale/pincode.html', locals())
예제 #9
0
파일: ahps.py 프로젝트: mejaz/ahps-office
def sendTextAll():

    if request.method == 'POST':

        msg = request.json['msg']
        nmbr = "91%s" % request.json['number']

        resp = sendSMS(
            '*****@*****.**',
            '74aa54055b30ad864d6e3fe04d69987204d91c1378cabcd6e3ca47a034d6744f',
            str(nmbr).strip(), 'TXTLCL', msg, 'true')

        print resp

        respDict = json.loads(resp)
        print type(respDict)

        if 'errors' in respDict:

            errMsg = "%s - %s" % (respDict['status'],
                                  respDict['errors'][0]['message'])

            return json.dumps(errMsg)
        else:

            return json.dumps(respDict['status'])
예제 #10
0
def contact(phone_number, country):
    country_data = extract_data()[country]
    try:
        result = sendSMS(phone_number, country, country_data)
        print(result)
        response = jsonify("Success!")
    except:
        response = jsonify(
            "Failed to send message - SMS API may be overloaded")

    response.headers.add("Access-Control-Allow-Origin", "*")
    return response
예제 #11
0
파일: app.py 프로젝트: keshavn93/carpool
def getFromPool():
    key = request.json["key"]["value"]
    pickupLat = request.json["PickUp"]["Latitude"]
    pickupLng = request.json["PickUp"]["Longitude"]
    destLat = request.json["Destination"]["Latitude"]
    destLng = request.json["Destination"]["Longitude"]
    jsonResult = pool.getFromPool(pickupLat, pickupLng, destLat, destLng,
                                  treeOfCities, dictMap)
    try:
        phoneNumber = str(jsonResult["key"])
        message = "Please contact " + str(
            key) + ". The driver will pick you up at the specified location."
        sms.sendSMS(phoneNumber, message)
        pickUpLat, pickUpLng, pickUpKey = jsonResult["pickup"]
        pool.delPickUpFromPool(pickUpLat, pickUpLng, pickUpKey, treeOfCities,
                               dictMap)
        pickUpLat, pickUpLng, pickUpKey = jsonResult["dest"]
        pool.delDestFromPool(pickUpLat, pickUpLng, pickUpKey, treeOfCities,
                             dictMap)
        return json.dumps(jsonResult)
    except:
        return "No matching found", status.HTTP_500_INTERNAL_SERVER_ERROR
예제 #12
0
    def POST(self):
        input = web.input(mobile = None)

        if input.mobile == None:
            return output(110)

        if len(input.mobile) != 11 or (not re.compile(r'^[1-9][0-9]+$').match(input.mobile)):
            return output(120)

        db = getDb()
        results = db.select('user', vars = {'mobile' : input.mobile},
                            where = "login_name=$mobile", what = "user_id,type")

        is_register = True
        length = len(results)
        if length == 0:
            is_register = False
        else:
            user = results[0]
            if user.type == '6':
                is_register = False
        if not is_register:
            verify_code = random.randint(100000, 999999)
            status = sendSMS(input.mobile, "%d,3" % (verify_code,))
            if status == 1:
                return output(421)
            elif status == 2:
                return output(701)

            t = db.transaction()
            try:
                if length == 0:
                    user_id = db.insert('user', login_name = input.mobile, type = '6')
                else:
                    user_id = user.user_id
                results = db.select('verify', vars = {'id':user_id}, where = "user_id=$id")
                if len(results) == 0:
                    db.insert('verify', user_id = user_id, verify_code = str(verify_code),
                              add_time = int(time.mktime(time.localtime())))
                else:
                    db.update('verify', vars = {'id':user_id},
                              where = "user_id=$id", verify_code = str(verify_code),
                              add_time = int(time.mktime(time.localtime())))
                t.commit()
            except:
                t.rollback()
                return output(700)

            return output(200, {'verify_code_md5' : encrypt(str(verify_code))})
        else:
            return output(420)
예제 #13
0
def interpreter(text, msisdn, v_num):
    send_to = msisdn  # user number
    send_from = v_num  # virtual number provided by Nexmo

    # default reply assuming unknown phrase
    print('Message: "%s" from %s' % (text, msisdn))
    reply = 'I don\'t know how to interpret that. Try asking me to sign up or add a new context.'

    # intent = register
    regPhr = ['register', 'join', 'Register', 'Join', 'sign up', 'Sign up']
    for phrase in regPhr:
        if phrase in text:
            v_num = rentSMS()
            response = dynamo_put(msisdn, v_num)
            v_nums = dynamo_get(msisdn)
            reply = "Hello, %s. Your virtual number(s): %s" % (msisdn, v_nums)
            """
                Do something with new user registration
            """

    # intent = context2
    cxtPhr = [
        'Context', 'context', 'create context', 'Create context',
        'add context', 'Add context', 'new context', 'New context'
    ]
    for phrase in cxtPhr:
        if phrase in text:
            v_nums = dynamo_get(msisdn)
            reply = "Hello, %s. Your virtual number(s): %s" % (msisdn, v_nums)
            """
                Do something with context
            """

    # format for outgoing bot texts
    outgoing = "---- Safe Chat ----\n~~ v%s ~~\n\n%s" % (VER, reply)

    sent = sendSMS(send_to, send_from, outgoing)
    return sent
예제 #14
0
    def POST(self):
        input = web.input(mobile = None)

        if input.mobile == None:
            return output(110)

        db = getDb()
        results = db.select('user', vars = {'mobile' : input.mobile},
                            where = "login_name=$mobile and type!='6'", what = "user_id")
        if len(results) == 0:
            return output(422)

        user_id = results[0].user_id

        verify_code = random.randint(100000, 999999)
        status = sendSMS(input.mobile, "%d,3" % (verify_code,))
        if status == 1:
            return output(421)
        elif status == 2:
            return output(701)

        t = db.transaction()
        try:
            results = db.select('verify', vars = {'id':user_id}, where = "user_id=$id")
            if len(results) == 0:
                db.insert('verify', user_id = user_id, verify_code = str(verify_code),
                          add_time = int(time.mktime(time.localtime())))
            else:
                db.update('verify', vars = {'id':user_id}, where = "user_id=$id",
                          verify_code = str(verify_code), add_time = int(time.mktime(time.localtime())))
            t.commit()
        except:
            t.rollback()
            return output(700)

        return output(200, {'verify_code_md5' : encrypt(str(verify_code))})
예제 #15
0
        elif confidence < 90 and confidence >= 78:
            sp1 = pyttsx3.init()
            sp1.say(
                "Sorry, your face can not be recognized. Do you want us to send an OTP to your phone ? "
            )
            sp1.runAndWait()
            mic = sr.Microphone()
            r = sr.Recognizer()
            with mic as source:
                audio = r.listen(source)
                text = r.recognize_google(audio)
            print(text)

            if text == 'YES' or text == 'Yes' or text == 'yes':
                print("hi")
                OTP = sms.sendSMS()
                time.sleep(5)
                while True:
                    try:
                        mic1 = sr.Microphone()
                        r1 = sr.Recognizer()
                        sp = pyttsx3.init()
                        sp.say("Please speak the OTP sent on your phone")
                        sp.runAndWait()
                        with mic1 as source:
                            print("Please enter the OTP sent on your phone :")
                            audio = r1.listen(source)
                            text1 = r1.recognize_google(audio)
                        print(text1)

                        if text1 == OTP:
예제 #16
0
def mainFunc():
    #path to webdrive in use
    browser = webdriver.Chrome(executable_path="/usr/bin/chromedriver")

    website_URL = "https://www.facebook.com/"
    browser.get(website_URL)
    # user name or e-mail
    username = "******"

    #getting password from text file - create your own to test
    with open('test.txt', 'r') as myfile:
        password = myfile.read().replace('\n', '')

    #Confirmation
    print("Let's Begin")

    #find the username/email entry field
    element = browser.find_elements_by_xpath('//*[@id ="email"]')
    element[0].send_keys(username)

    #Confirmation
    print("Username Entered")

    element = browser.find_element_by_xpath('//*[@id ="pass"]')
    element.send_keys(password)

    #Confirmation
    print("Password Entered")

    #logging in
    log_in = browser.find_elements_by_id('loginbutton')
    log_in[0].click()

    print("Login Successfull")
    website_URL = "https://www.facebook.com/events/birthdays/"
    browser.get(website_URL)
    #implicit wait in case the connection is slow
    browser.implicitly_wait(2)
    #load the birthday check function into a variable to test
    names_list = birthdayCheck()
    print(names_list)
    #Iterate through the list of names returned from the DB
    for f_name, l_name in names_list:
        #test each tuple named pair for a birthday on the page
        birthdays = (browser.find_elements_by_link_text("%s %s" %
                                                        (f_name, l_name)))
        if len(birthdays) > 0:

            phone = grabPhone(f_name, l_name)
            email_ = grabEmail(f_name, l_name)

            if len(phone) > 0:
                sendSMS(f_name, phone)
                print(f'Phone number found: {phone}')
                print('SMS Sent')
            else:
                print('No Phone number')
            if len(email_) > 0:
                emailSequence(f_name, l_name, email_)
                print(f'Email found: {email_}')
                print('Email Sent')
            else:
                print('No email')

        else:
            print('Not their birthday')
    browser.close()
예제 #17
0
	if count==0:
		prevState = currState
		currState = GPIO.input(sensorPin)
		if currState != prevState:
			if currState:
				print "A MOTION HAS BEEN DETECTED !!! Recording Started!"
				logging.warning("A MOTION HAS BEEN DETECTED !!! Recording Started!")
				fileName = datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
				try:
					cam.start_preview()
					cam.start_recording(fileName)
					print (fileName)
				except Exception, Argument:
					logging.error(Argument)
					sms.sendSMS(num1,msg_prob)
					sms.sendSMS(num2,msg_prob)
			else:
				print "MOTION STOPPED! Recording Stopped!"
				logging.info("Recording Stopped! %s" % fileName)
				try:
					cam.stop_preview()
					cam.stop_recording()
				except Exception, Argument:
					logging.error(Argument)
					sms.sendSMS(num1,msg_prob)
					sms.sendSMS(num2,msg_prob)
				else:
					try:
						print "Sending Mail Notification..."
						subprocess.call("mail -s 'Motion Detected' [email protected] < /home/pi/message.txt", shell=True)
예제 #18
0
            print "Sending Mail Notification..."

            subprocess.call(
                "mail -s 'Motion Detected' [email protected] < /home/pi/message.txt",
                shell=True)

            print "Complete"

            print "Uploading the footage to Dropbox..."

            dropboxUpload(fileName)

            print "Complete"

            print "Sending SMS Notification..."

            sms.sendSMS('xxxxxxxxxx')

            sms.sendSMS('xxxxxxxxxx')

            subprocess.call(
                "mail -s 'Motion Detected' [email protected] < /home/pi/message.txt",
                shell=True)

            print "Complete"

            print "SMS Notification generally takes upto 1-2 minutes"

            print "But Sometimes due to heavy newtork traffic it can take upto 10 mins"
예제 #19
0
def main():
    updated_rating = getUpdatedRating()
    global current_rating
    if current_rating != updated_rating:
        sendSMS(current_rating, updated_rating)
        current_rating = updated_rating
예제 #20
0
import requests
import json
import sms
import time
import sys
from pytz import timezone
from datetime import datetime

device = sys.argv[1]

url = "https://www.apple.com/kr/shop/retail/pickup-message?pl=true&searchNearby=true&store=R692&parts.=" + device

response = requests.get(url).json()
store = response['body']['stores'][0]
reservationUrl = store['reservationUrl']
availability = store['partsAvailability'][device]['storeSelectionEnabled']
text = store['partsAvailability'][device]['storePickupQuote']

if availability:
    sms.sendSMS()
    print("true " + datetime.now(timezone('Asia/Seoul')).strftime('%c') + '\n')
else:
    print("false " + datetime.now(timezone('Asia/Seoul')).strftime('%c') +
          '\n')