Exemple #1
0
def ProcessCMD(cmd,number):
    SER.send('Starting remote command operations\r')
    if(cmd.find('REBOOT') != -1):
        msg = 'Rebooting via SMS commnad'
        SER.send(msg)
        SER.send('\r')
        Log.appendLog(msg)
        res = MDM.send('AT#REBOOT\r',0)
        res = MDM.receive(100)
        MOD.sleep(100)

    if(cmd.find('SOFTUPD') != -1):
        res = -1
        while (res == -1):
            res = FTPupdate.Main('updapp.pyo')
            MOD.sleep(10)
        res = MDM.receive(100)
        SER.send('Enabling Script\r')
        res = MDM.send('AT#ESCRIPT="updapp.pyo"\r',0)
        res = MDM.receive(100)
        MOD.sleep(100)
        SER.send('Rebooting\r')
        res = MDM.send('AT#REBOOT\r',0)
        res = MDM.receive(100)

    if(cmd.find('SALDO') != -1):
        SER.send('Requesting SALDO from TAE\r')
        res = SMS.sendSMS('333','SALDO')
        if(res == -1):
            return
        msg = -1
        while (msg == -1):
            SER.send('...Waiting for Message\r')
            msg = SMS.check4SMS()
        data = SMS.ReadMessage(msg)
        SMS.DelMessage(msg)
        if(data['phn'] == 'TAE'):
            SER.send('Message received from TAE\r')
            SER.send('Sending info to:')
            SER.send(number)
            SER.send('\r')
            res = SMS.sendSMS(number,data['sms'])

    if(cmd.find('GPSPOS') !=-1):
        data = gpsinfo.gpsData()
        if (data == -1):
            AI = MDM.send('AT$GPSAI\r',0)
            AI = MDM.receive(25)
            res = SMS.sendSMS(number,AI)
        else:
            pos = 'lat:'+str(data["latitud"])+'long:'+str(data["longitud"])+'nsats:'+data["gpssats"]
            res = SMS.sendSMS(number,pos)
            SER.send('Sending GPS info via SMS\r')
            SER.send('иии:')
            SER.send(pos)
            SER.send('\r')
            
            
        
    return
Exemple #2
0
def trackWatches():
    global postCache
    redditConfig = config['REDDIT']
    client_id = redditConfig['client_id']
    client_secret = redditConfig['client_secret']

    reddit = praw.Reddit(client_id=client_id,
                         client_secret=client_secret,
                         user_agent='Watch Tracker')

    watchesToLookFor = [
        "ORIS", "HYDROCONQUEST", "SEAMASTER", "SKX013", "MAX BILL", "C60",
        "TRIDENT", "OCEAN"
    ]
    for post in reddit.subreddit('watchexchange').stream.submissions():
        if post.id in postCache:
            logger.info("Post {0} found in cache".format(post.id))
            continue
        if any(tag in post.title.upper() for tag in watchesToLookFor):
            postCache.add(post.id)
            postTitle = post.title
            postText = post.selftext
            postDate = datetime.datetime.fromtimestamp(post.created)
            postRedirectUrl = post.url
            postSelfUrl = reddit.config.reddit_url + post.permalink
            authorComments = []
            for comment in post.comments:
                if comment.author and comment.author.name == post.author.name:
                    authorComments.append(comment.body)
            messageContents = "{0} - {1} {2} {3}".format(
                postTitle.encode('ascii', 'ignore'), postDate,
                postSelfUrl.encode('ascii', 'ignore'),
                postText.encode('ascii', 'ignore'))
            SMS.send(messageContents)
            logger.info(messageContents)
Exemple #3
0
    def read_message(self, msg):
        """Process an incoming text for this team. 'pass' or 'a <answer>'"""
        if re.search('^\s*pass\s*$', msg, re.I):
            return self.pass_clue()

        m = re.search('^\s*a\s*(.*?)\s*$', msg, re.I)
        if m:
            return self.guess(m.group(1))

        # What's this?
        SMS.send(self.phone, "I don't understand '%s'." % msg)
Exemple #4
0
def start():
    wh.update("No experiment right now. <br> How's it going anyway?",100)
    os.chdir('C:\\Users\\lvbt\\Documents')
    # Open a HTTP tunnel on the default port 80
    # <NgrokTunnel: "http://<public_sub>.ngrok.io" -> "http://*****:*****@gmail.com','TP-Exp-'+dt)
    os.system('python -m http.server 80')
Exemple #5
0
def sendMessage( receiver, subject, content, attachments=None, withSMS=None ):
	""" 쪽지함에 쪽지를 발송	
	"""
	#[TODO] To,CC,BCC에 대한 처리 필요 
	#[TODO] IF not logined !!
	
	smsList = []
	msgIDXs = []
	msgSave = { "Subject": subject, "Content": content, "Sender": Login.getID(), "SenderName": Login.getName() }
   
	if "<" in receiver:
		#ex) Address Parsing :: "정기영" <*****@*****.**>, "김태희" <*****@*****.**>  -> ["*****@*****.**",  "*****@*****.**"]
		addrsList = re.findall("\<([._,a-zA-Z0-9:\#\@]+)\>+", receiver)
	else:	 
		addrsList = [n.strip() for n in receiver.split(",")]
	
	for recID in addrsList:
		
		userData = Archive("User").getValues( "User.UserID == "+ recID, "Name,HandPhone" )
		if userData:
			msgSave["Receiver"] = recID
			
			result_IDX = Archive("MsgInBox").New(**msgSave)
			
			if result_IDX:
				msgIDXs.append( result_IDX )
				if userData["HandPhone"] and not userData["HandPhone"].replace("-","") in smsList:
					smsList.append( str(userData["HandPhone"].replace("-","")) )
				
				sentMsg = { "RelateIDX": result_IDX, "Subject": subject, "Content": content, "Receiver": recID, "ReceiverName": userData["Name"], "Sender": Login.getID() } 
				r = Archive("MsgSent").New( **sentMsg )
	
	if attachments:
		#[TODO] 임시 코드입니다. 멀티센딩에서 업된 파일에 대한 레퍼런스 카운트가 이상적이나 일단 그냥 복제형태로 갑니다.
		if type(attachments) == unicode:
			attachments = attachments.encode("utf8")
		
		uploadFile = Files.getRootDir() + attachments
		fileName = os.path.split(attachments)[1]
		
		if os.path.exists( uploadFile ):
			for ridx in msgIDXs:
				if str(ridx).isdigit():
					targetFile = "/data/message/%s.%s" % ( fileName, ridx )
					shutil.copy2( uploadFile, Files.getSpartaDir() + targetFile )
					msgMod = { "IDX" : ridx, "Attachments" : "%s" % fileName }
					r = Archive( "MsgInBox" ).New( **msgMod )
			os.remove(uploadFile)
	
	if withSMS and smsList:		   
		SMS.send( sendMsg=u"스팔타쪽지>"+msgSave["Subject"], recvList=smsList )
	
	return len(msgIDXs)
Exemple #6
0
def Consumer(threadName,userId):
    daemon = True
    timeStamp = str(time.mktime(datetime.datetime.now().timetuple()))
    consumer = KafkaConsumer(group_id = timeStamp,
                             bootstrap_servers=['localhost:9092','localhost:9093','localhost:9094'],
                             api_version=(0,9),
                             consumer_timeout_ms=30000
                            )
    consumer.subscribe(['twitterStreaming'])
    for msg in consumer:
        kafakMessage = msg.value.decode("utf-8")
        SMS.sms(kafakMessage)
        line_bot_api.push_message(userId, TextSendMessage(text=kafakMessage))
Exemple #7
0
 def guess(self, answer):
     """Guess the answer to the current clue. If wrong, returns
     False. If right, removes the clue from self.clues(), stores a
     Success object and returns True."""
     c = self.current_clue()
     if answer.lower() == c.answer.lower():
         s = Success(hunt=self.hunt, team=self, clue=c)
         s.put()
         self._remove_clue()
         self.send_clue("Awesome! Next: ")
         return True
     else:
         SMS.send(self.phone, "Sorry; that's wrong!")
         return False
Exemple #8
0
def main():
    global postCache
    running = True
    while running:
        try:
            trackWatches()
        except KeyboardInterrupt:
            logger.info("Keyboard terminate received")
            running = False
        except Exception as e:
            logger.exception('run loop exeption: {0}'.format(e))
            time.sleep(10)
            SMS.send("Something went wrong with WatchTracker :(")
        finally:
            saveCache()
Exemple #9
0
 def _monitoring(self):
     print("DEBUG___SimManager monitoring")
     #for SMS
     sms = SMS.SMSManager()
     # anyone want to read
     # are there any problem
     while True:
         if not self.listenerQueue.empty():
             value = self.listenerQueue.get()
             print(value)
             if value == "+CPIN: READY":
                 #self._onInsertedSim()
                 #break
                 print("DEBUG___+CPIN: ready----------------")
                 pass
             elif value == "+CPIN: NOT READY":
                 print("DEBUG___+CPIN: NOT ready----------------")
                 self._onEjectSim()
                 break
             #SMS check
             elif value.find("CMTI") != -1:
                 print("DEBUG___Received new Message")
                 smsindex = sms.read_index(value)
                 smscontent = self.read_SMS(smsindex[1])
                 if "\"$\"" in smscontent:
                     #finish receive SMS
                     print("DEBUG___finish read SMS")
                 else:
                     #wait for finish
                     print("DEBUG___read next SMS")
             else:
                 print("DEBUG___no such command : ", value)
Exemple #10
0
 def _remove_clue(self):
     """Internal method used by answer and pass_clue"""
     self.clue_keys.pop(0)
     if self.finished():
         self.finish_time = datetime.now()
         result = SMS.send(self.phone, "You're finished! Return to base.")
     self.put()
     return True
def send_quote():
    # Now, we'll initialize the specific worksheet we want to work with;
    # in our case, this will be the quotes log. In this log, all the quotes
    # will be in column 1 of the 'QuoteDB' subsheet.
    # NOTE: Google Spreadsheets are indexed starting at 1, and
    # in Cartesian coordinate form e.g. for B1 -> (1, 2)

    gc = gspread.authorize(credentials)

    # Quote database
    quote_db = gc.open('Motivational Quotes Log').worksheet('QuoteDB')

    # Quote log that we will write to with data/time and quote information
    quote_db_log = gc.open('Motivational Quotes Log').worksheet('QuoteLog')

    # Some constants
    quote_col = 1
    db_size = len(quote_db.col_values(quote_col))

    # db_size + 1 due to 1-indexing, and + 1 again since we start at
    # index 2
    row_index = 2 + random.randrange(db_size)

    quote_of_the_day = quote_db.cell(row_index, quote_col).value

    # WRITING TO THE QUOTE LOG
    # This is simple. We already have the quote of the day in
    # quote_of_the_day. Now all we need to do is write that
    # information, along with the datetime onto the next successive
    # row in QuoteLog.
    # Format: DATETIME QUOTE
    date_string = date_string_today()
    quote_db_log.append_row([date_string, quote_of_the_day])

    # Now that we've appended that information to the quote log,
    # we can delete that quote row from the database

    quote_db.delete_row(row_index)

    # Debugging
    print(quote_of_the_day)
    print("Row Index: " + str(row_index))

    # Finally, to send the quote to the phone number in SMS
    SMS.send(quote_of_the_day)
Exemple #12
0
 def send_clue(self, note=''):
     """Send the current clue to the team by SMS, prepended by note."""
     msg = note
     if self.current_clue():
         msg += self.current_clue().question
     else:
         msg += 'No more clues!'
     result = SMS.send(self.phone, msg)
     return True if result == 200 else False
def generateFrames():
    timePassed = time.mktime(datetime.datetime.now().timetuple())
    # read the frames
    ret, frame1 = cap.read()
    ret, frame2 = cap.read()
    while cap.isOpened():
        # find the absolute difference between the first and second frame
        diff = cv.absdiff(frame1, frame2)
        # convert the difference to gray scale mode
        gray = cv.cvtColor(diff, cv.COLOR_BGR2GRAY)
        # blur the gray scale: kernel size is the second argument, Sigma x value is the third
        blur = cv.GaussianBlur(gray, (5, 5), 0)
        # find the threshold, we give the threshold interval, and the tyoe
        _, thresh = cv.threshold(blur, 30, 255, cv.THRESH_BINARY)
        # dilate the threshold image to fill in all the holes, to find better contours
        dilated = cv.dilate(thresh, None, iterations=3)
        # find the contour
        contours, _ = cv.findContours(dilated, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
        # iterate through contours
        for contour in contours:
            # apply bounding rectangles for contours
            (x, y, w, h) = cv.boundingRect(contour)
            # if the area if smaller than the area of a person ignore, else we draw it
            if cv.contourArea(contour) < 5000:
                continue
            cv.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2)
            # print text on image if movement is observed
            cv.putText(frame1, "Status: {}".format('Movement detected'), (10, 20), cv.FONT_HERSHEY_SIMPLEX,
                      1, (0, 0, 255), 3)
        #add the current date to the streaming
        datet = str(datetime.datetime.now())
        cv.putText(frame1, datet, (10, 700), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0, 0), 2, cv.LINE_AA)
        ret, buffer = cv.imencode('.jpg',frame1)
        frame1 = buffer.tobytes()

        currentTime = time.mktime(datetime.datetime.now().timetuple())
        if currentTime - timePassed < 3:
            SMS.sendMessage()
        #update streaming and upload it
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame1 + b'\r\n')
        frame1 = frame2
        # read the new frame
        ret, frame2 = cap.read()
Exemple #14
0
 def deliver(cls, p, msg):
     """Given a phone number and a message, deliver the message to
     the appropriate team's read_message() method."""
     logging.debug("Asked to deliver '%s' to %s" % (msg, p))
     team = cls.find_by_phone(p)
     logging.debug("Found team: %s" % team.name)
     if team:
         return team.read_message(msg)
     else:
         # Er... message received from unknown number
         return SMS.send(p, "Sorry... I don't know who you are!")
Exemple #15
0
def FetchInfo(id):
    profile1 = PyMongo.getProfile1(id)
    #print profile1

    profile2 = PyMongo.getProfile2(id)
    #print profile2

    name = profile1[0]
    gender = profile1[1]
    city = profile2[0]
    age = profile2[1]
    purpose = profile2[2]
    time = profile2[3]
    sm = 0

    if (city == "Sangli"):
        sm += (10)
    elif (city == "Miraj"):
        sm += (30)
    elif (city == "Pune"):
        sm += (50)
    elif (city == "Mumbai"):
        sm += (70)
    #elif(60 < age < 80 or purpose == "Urgent"):
    #execfile('SMS.py')

    if (0 < age < 20):
        sm += 20
    elif (20 <= age < 40):
        sm += 40
    elif (40 <= age < 60):
        sm += 60

    if (purpose == "Meeting"):
        sm += 50
    elif (purpose == "Invitation"):
        sm += 30
    elif (purpose == "Personal"):
        sm += 10

    print sm
    print purpose
    print city
    print age

    if (sm > 150 or 60 < age < 80 or purpose == "Urgent"):
        SMS.SendSMS(name, gender, city, purpose, mobile="9604091697")

    else:
        new_profile1 = PyMongo.getProfile1(id)
        new_profile2 = PyMongo.getProfile2(id)
        PyMongo.SCInsert(id, sm, time)
        PyMongo.SCSchedule()
Exemple #16
0
def myapp():
    # for reddit api
    reddit = praw.Reddit(
        client_id=cred.keyring.get_password('client_ID', 'reddit_clientID'),
        client_secret=cred.keyring.get_password('client_pass',
                                                'reddit_clientPass'),
        user_agent='Enter your user agent here',
        username=cred.keyring.get_password('user_login', 'reddit_username'),
        password=cred.keyring.get_password('user_pass', 'reddit_pass'))

    subreddit1 = reddit.subreddit('Pmsforsale')
    new_subreddit1 = subreddit1.new(limit=100)

    title1 = 'PMSFORSALE: '
    title2 = 'Coins4Sale: '
    currentTime = time.time()
    for submission in new_subreddit1:
        if int(
                submission.created_utc
        ) > int(currentTime
                ) - 5 * 60:  # only run if there are new post in last 5 minutes
            if "WTS" in submission.title:
                title1 += str(submission.title + ' ' + submission.url + '\n\n')

    subreddit2 = reddit.subreddit('Coins4Sale')
    new_subreddit2 = subreddit2.new(limit=100)

    for submission in new_subreddit2:
        if int(
                submission.created_utc
        ) > int(currentTime
                ) - 5 * 60:  # only run if there are new post in last 5 minutes
            if "WTS" in submission.title:
                title2 += str(submission.title + ' ' + submission.url + '\n\n')

    # send text message
    if len(title1) > 0:
        SMS.send(title1)
    if len(title2) > 0:
        SMS.send(title2)
def check_price():
    # Updating prices
    for i in stockTickers:
        stockTickers[i] = round(si.get_live_price(i), 3)

    # Creating message to send
    stocksUpdate = """Apple: {appl}, Amazon: {amzn}  Microsoft: {msft} Facebook: {fb} Google: {goog} IBM: {ibm} Tesla: {tsla} Intel: {intel}, AMD:{amd}
    """.format(appl=stockTickers["aapl"],
               amzn=stockTickers["amzn"],
               msft=stockTickers["msft"],
               fb=stockTickers["fb"],
               goog=stockTickers["goog"],
               ibm=stockTickers["ibm"],
               tsla=stockTickers["tsla"],
               intel=stockTickers["intc"],
               amd=stockTickers["amd"])

    msg = f"Subject: {'Stock Prices'}\n\n{stocksUpdate}"

    # Sending message
    SMS.send(msg)
    print(stocksUpdate)
Exemple #18
0
def on_message(client, userdata, msg):
    global hvac_power, last_temp, last_temp_set, security_power, last_home_motion
    message_payload = msg.payload
    new_message = msg.topic
    if new_message == 'home/temperature_power':
        #print 'Temperature Status: ' + msg.payload
        if msg.payload == 'on':
            hvac_power = 'on'
        else:
            hvac_power = 'off'
        controlHVAC()

    elif new_message == 'home/temperature_set':
        #print 'Temperature Setting: ' + msg.payload
        last_temp_set = int(msg.payload)
        controlHVAC()

    elif new_message == 'home/temperature_sensor':
        #print 'Temperature: ' + msg.payload
        last_temp = int(msg.payload)
        controlHVAC()

    elif new_message == 'home/light_intensity':
        if int(msg.payload) > 80:
            client.publish('home/blind_status', 'open')
            last_light_status = 'off'
            client.publish('home/light_power', 'off')

    elif new_message == 'home/security_motion':
        dt = datetime.datetime.now()
        time = dt.strftime('%d %b %Y') + ' | ' + dt.strftime('%I:%M %p')
        client.publish('home/last_motion_detected', time)
        SMS.send_message('Motion Detected, Security Alarm Triggered')
        client.publish('home/security_light', 'on')
    elif new_message == 'home/home_motion':
        last_home_motion = datetime.datetime.now()
    else:
        print(new_message, msg.payload)
 def addNewContainer(self, containername):
     if containername == Names.Containers["SMS"]:
         self.myContainers[containername] = SMS.SMS(containername, self)
     elif containername == Names.Containers["RPDU"]:
         self.myContainers[containername] = RPDU.RPDU(containername, self)
     elif containername == Names.Containers["UD"]:
         self.myContainers[containername] = UD.UD(containername, self)
     elif containername == Names.Containers["WSP"]:
         self.myContainers[containername] = WSP.WSP(containername, self)
     elif containername == Names.Containers["WBXML"]:
         self.myContainers[containername] = WBXML.WBXML(containername, self)
     elif containername == Names.Containers["SIMCMD"]:
         self.myContainers[containername] = SIMCmd.SIMCmd(
             containername, self)
     elif containername == Names.Containers["MMS"]:
         self.myContainers[containername] = MMS.MMS(containername, self)
     elif containername == Names.Containers["ENVELOPE"]:
         self.myContainers[containername] = Envelope.Envelope(
             containername, self)
Exemple #20
0
def SCSchedule():
    l = []

    for obj in db.sc.find():
        l.append(obj)

    #print(l)
    m = []
    m = sorted(l[2:], key=lambda x: x['p'], reverse=True)
    #l.sort(key=attrgetter('p'),reverse=True)
    #print "hello m"
    #print m

    n = []
    n.append(l[0])
    if len(l) >= 2:
        n.append(l[1])
    for i in m:
        n.append(i)
    #print "hello n"
    #print(n)
    #db.sc.remove({},{justOne:True},reverse=True)

    #db.sc.remove({},{justOne:True})

    db.sc.remove()
    token = 1
    for obj in n:
        #print(obj[1])
        #db.sc.insert_one(dict(obj[0]),dict(obj[1]),dict(obj[3]),dict(obj[4]))
        str1 = obj['uid']
        #str2=str(obj['i'])
        str3 = str(obj['p'])
        str4 = str(obj['at'])
        db.sc.insert_one({'uid': float(str1), 'p': float(str3), 'at': str4})
        profile = getProfile1(int(str1))
        #print(profile + str1 )
        mobile = profile[2]
        SMS.SendSMS(profile[0], profile[1], '', token, mobile)
        token += 1
Exemple #21
0
                [1]) and PreviousCheck[queryList[i]] is False:
                messageToSend = messageToSend + str(queryList[i]) + ", " + str(
                    stockResults[i]) + '\n'
                stockEnteredAcceptedRange = True
                PreviousCheck[queryList[i]] = True
            else:
                print(queryList[i] +
                      "Not Within designated Range or already notified")
        #print("==============RESULTS================")
        #print(stockResults)
        #print(messageToSend)
        #print(PreviousCheck)
        #print("==============END=RESULTS============")
        #input()
        if stockEnteredAcceptedRange:
            print("text me")
            SMS.send(messageToSend, phoneNumber, usrnm, pswrd, carrier)
    except ValueError:
        print(
            str(ValueError) +
            "could not properly decode 'StockData.txt'. Is the file missing or poorly formatted?"
        )

    timeElapsed = time.perf_counter() - startSystemTime
    print("Time Elapsed Finding Prices: " + str(timeElapsed) + " seconds.")
    print("Time until next Update: " +
          str((intervalWaitTime * 60 - timeElapsed) / 60) + " minutes")
    print(
        "####################################################################")
    print()
    time.sleep(intervalWaitTime * 60 - timeElapsed)
Exemple #22
0
def Mainloop():
	MAX_ERRORS = 3
	UPDATE_TIME = 3600
	TIMEOUT_CMD = 500

	wd.feed()
	
	res = SER.set_speed('9600')
	imei = utils.getimei()
	time = Log.uptime()
	smsmsg = time + ' Starting Unit: ' + imei
	res = MDM.receive(20)
	res = scmd.sendCmd('AT+CMGF', '1', 50)
	res = 1
	
	if(res != 1):
		Log.ReportError('Error Sending Init MSG')
	else:
		msg= 'Starting Unit:' + imei
		Log.appendLog(msg)
		printdbg.printSER(msg)
		

	res = scmd.sendCmd('at+cfun','5',10)
	serv_data = -1
	
	while 1:	
		hname = gprs.gethname()
		printdbg.printSER(hname)
		NUpdate = timers.timer(0)
		NUpdate.start(3)
		print "Ready to start main loop"
		Mto = timers.timer(0)
		Mto.start(120)
		while 1:
			wd.feed()
			printdbg.printSER("Doing GPS")
			data =gpsinfo.gpsData() 
			if data == -1:
				errmsg = "GPS Error"
				printdbg.printSER("GPS ERROR")
				#Log.ReportError(errmsg)
###############################################################################
###########STATIC UPDATE ROUTINE###############################################
###############################################################################
			try:
				if (NUpdate.isexpired() and data != -1):
					print "ready to static update"
					Log.ReportError('Doing timeout Update')
					data["dyn"] = "0"
					Chronos.set_LockFlag()
					res = gprs.updateloop(hname,data,MAX_ERRORS)
					gp = gprs.disGPRS()
					NUpdate.start(3600)
					if res == -1:
						break
					serv_data = data
			except (Exception, StandardError, SystemError, RuntimeError):
				msg = 'Expception in Static Update: '
				Log.appendLog(msg)
				print "exception in static update"

###############################################################################
############END OF STATIC UPDATE ROUTINE#######################################
###############################################################################				
				
			data = gpsinfo.gpsData()
			if data == -1:
				errmsg = "GPS Error"
				#Log.ReportError(errmsg)
###############################################################################
###############DYNAMIC UPDATE ROUTINE##########################################
###############################################################################
			try:
				if serv_data != -1 and data!= -1 and \
				    utils.dist(serv_data["latitud"],data["latitud"],serv_data["longitud"],data["longitud"]) > 5000:
					Log.ReportError('Dynamic Routine Update')
					data["dyn"] = "1"
					res = gprs.updateloop(hname,data,MAX_ERRORS)
					if res == -1:
						Log.ReportError('Error in updateloop')
						break
					serv_data = data
					NUpdate.start(300)

			except (Exception, StandardError, SystemError, RuntimeError):
				msg = 'Expception in Dynamic Update '
				Log.appendLog(msg)
				print "exception in dynamic update"
				
##############################################################################
##############END OF DYNAMIC UPDATE ROUTINE###################################
##############################################################################
##############################################################################
##############Start revision of wireless alert##		
			try:
				SER.send('SWICHT_LED\r')
				if(Chronos.check_PannicFlag() == 1):
					print 'Doing Pannic Update'
					data["dyn"] = "2"
					res = gprs.updateloop(hname,data,MAX_ERRORS)
					if res == -1:
						Log.ReportError('Error in updateloop')
						break
					else:
						Chronos.reset_PannicFlag()
					serv_data = data
					NUpdate.start(10)

				if(Chronos.check_LockFlag() == 0 and serv_data["dyn"] == "1"):
					data["dyn"] = "3"
					res = gprs.updateloop(hname,data,MAX_ERRORS)
					if res == -1:
						Log.ReportError('Error in updateloop')
						break
					serv_data = data
					NUpdate.start(10)
				

			except (Exception, StandardError, SystemError, RuntimeError):
				msg = 'Expception in Dynamic Update '
				Log.appendLog(msg)

##############################################################################
###############SMS CHECK######################################################
			try:
				msg = SMS.check4SMS()
				if(msg != -1):
					data = {}
					data = SMS.ReadMessage(msg)
					SER.send('New message from:')
					SER.send(data['phn'])
					SER.send('\r')
					SER.send('SMS Contents:')
					SER.send(data['sms'])
					SER.send('---END OF SMS\r')
					SMS.DelMessage(msg)
					CmdMnger.ProcessCMD(data['sms'],data['phn'])
					
			except (Exception, StandardError, SystemError, RuntimeError):
				msg = 'Expception in SMS'
				Log.appendLog(msg)
				print "exception in SMS check"

##############################################################################
###############SMS Delete######################################################
			try:
				if (Mto.isexpired()):
					res = DelSMS.delAll()
					Mto.start(432000)
				
			except (Exception, StandardError, SystemError, RuntimeError):
				msg = 'Expception in SMS'
				Log.appendLog(msg)
				print "exception in SMS delete"
				
	return
#!/usr/bin/python3
# ^ that should be the path to your python

import SMS  # should be another .py file in this same directory
import sys  # I believe this comes pre-packaged with python3, but you might have to install it

SMS.send(sys.argv[1]
         )  # all this script does is pass argv[1] into SMS's send() method
Exemple #24
0
    for each_time in times:
        if each_time.text != 'SHIFT TIME':
            shift_times.append(
                each_time.text
            )  #identical element with 'SHIFT TIME' text so I just get the right element by making sure it's anything but this

    for i in range(len(shift_locations_scrape)):
        shift_dates += [date.text[28:]
                        for date in dates]  #giving a date for each time

    index += 1
    driver.refresh()  #refreshes page since I couldn't get out of modal

    while len(driver.find_elements_by_css_selector('.spinner')) > 0:
        time.sleep(3)
    time.sleep(
        2
    )  # Todo: find more effiecient way to wait for shift-info elements to be loaded in

formatted_list = []
for i in range(len(shift_locations)):
    formatted_list.append(shift_dates[i] + ' ' + shift_locations[i] + ' ' +
                          shift_times[i])

for i in range(len(formatted_list)):
    message = formatted_list[i]
    SMS.send('\n' + message)

for datewe in shift_dates:
    print(datewe)
Exemple #25
0
import Cliente, Factura, SMS, Call, CallInternational

if __name__ == "__main__":
    # principal:
    cli = Cliente.Cliente("Juan Perez", 600998833, "56.777.888G")
    fact = Factura.Factura("30/09/2016", "16/0001", cli)
    fact.addDetalle(SMS.SMS("1/09/2016", "14:15", 808585585, 0.05))
    fact.addDetalle(SMS.SMS("10/09/2016", "08:09", 608585445, 0.05))
    fact.addDetalle(SMS.SMS("12/09/2016", "12:58", 608564585, 0.05))
    fact.addDetalle(SMS.SMS("19/09/2016", "14:15", 208585585, 0.05))

    fact.addDetalle(Call.Call("9/09/2016", "14:15", 208585585, 0.025, 0.023))
    fact.addDetalle(Call.Call("19/09/2016", "4:15", 208585585, 0.025, 0.08))
    fact.addDetalle(Call.Call("29/09/2016", "16:15", 208555585, 0.025, 0.12))

    fact.addDetalle(
        CallInternational.CallInternational("2/09/2016", "09:15", 208555585,
                                            0.025, 0.12, 1))

    fact.generar()
Exemple #26
0
def sendMessage( receiver, receiverCC, receiverBCC, subject, content, attachments=None, withSMS=None ):
	""" 쪽지함에 쪽지를 발송"""
	
	#[TODO] IF not logined !!

	withEmail = True

	emailList = []
	smsList = []
	msgIDXs = []

	receiverTo = getReceiver(receiver)
	receiverCc = getReceiver(receiverCC)
	receiverBcc = getReceiver(receiverBCC)
	
	# 쪽지 내용 저장
	msg = Msg()
	msg.SenderID = unicode(Login.getID())
	msg.SenderName = unicode(Login.getName())
	msg.Subject = unicode(subject)
	msg.Content = unicode(content)
	msg.withSMS = unicode(withSMS)
	msg.CreateDate = datetime.datetime.now() 
	
	Session.add(msg)
	Session.commit()
	
	# To들에게 보내기
	setMsgReceiver(receiverTo, msg.idx, "0")
	# CC들에게 보내기
	setMsgReceiver(receiverCc, msg.idx, "1")
	# BCC들에게 보내기
	setMsgReceiver(receiverBcc, msg.idx, "2")

	# SMS 발송 관련 처리
	if withSMS:
		smsList = list()
		receiverList = receiverTo + receiverCc +receiverBcc
		for msg_receiver in receiverList:
			if type(msg_receiver) != dict:
				continue
			smsList.append(msg_receiver["HandPhone"])

		if len(smsList) > 0:
			SMS.send(sendMsg=u"[sparta] %s" % msg.Content[:70], recvList=smsList)
	
	if withEmail:
		senderData = getReceiver("<%s>" % Login.getID())[0]["GwID"]
		emailList = list()
		receiverList = receiverTo + receiverCc +receiverBcc
		for msg_receiver in receiverList:
			if type(msg_receiver) != dict:
				continue			
			if str(msg_receiver["GwID"]).startswith("D"):
				emailList.append( str(msg_receiver["GwID"])+"@idea.co.kr" )
		if len(emailList) > 0:
			sendEmail("*****@*****.**" % senderData, msg.Subject, msg.Content, recvList=emailList)
   
	if attachments:
		objUpload = Upload()
		objUpload.MsgInitialize()
		
		for attach_item in attachments:
			new_file = objUpload.upload_file_move(attach_item)

			rowMsgAttach = MsgAttach()
			rowMsgAttach.Msg_IDX = unicode(msg.idx)
			rowMsgAttach.OriginalFileName = unicode(new_file["O_PATH"])
			rowMsgAttach.NewFileName = unicode(new_file["D_PATH"])
			rowMsgAttach.FileSize = unicode(new_file["SIZE"])

			Session.add(rowMsgAttach)

		Session.commit()
	return len(receiverTo)
Exemple #27
0
 def __init__(self, com_port):
     self.com = com_port
     self.phone = None
     self.wait = defines.wait_time
     self.sms_module = SMS.SendSMS(self.com)
     self.log_file = new_log_file(defines.at_log)
Exemple #28
0
def sendLunchMenu(menu):
    mess = SMS(username, password)
    result = mess.send(phonenumber, menu)

    if result <> "0":
        raise LunchrException("Couldn't send message: " + menu, "The reason returned was: " + result)
Exemple #29
0
    try:
        ph.verify(given_hash, password)
        break
    except:
        print('your password is incorrect')

# Get flight number
while 1:
    ConfermationNum = input('Confermation Number: ')
    if len(ConfermationNum) != 6:
        print('Error, input your confermation number again...')
    else:
        break

# Setting up an sms server
sms_creds = SMS.SMSLoginCreds().from_json(SMS_CREDS_DIR)
server = SMS.SMSServer(sms_creds, SMS_NUMBER, carrier=SMS_CARRIER)

# Getting Encrypted Creds
file = open(UNITED_CREDS_DIR, 'r')
creds = json.loads(file.read())
creds['l'] = decrypt(password, creds['l'].encode('ISO-8859-1')).decode('utf8')
print('decrypted login')
creds['p'] = decrypt(password, creds['p'].encode('ISO-8859-1')).decode('utf8')
print('decrypted password')
file.close()

# Starting Chrome
driver = webdriver.Chrome()
driver.get('https://www.united.com/ual/en/us/account/account/signin')
Exemple #30
0
def main():
    path = "/home/ashley/thesis"
    internet_connection = False
    DEVNULL = open(os.devnull, 'wb')

    print "------------------------------------------------------------------------"
    sys.stdout.flush()
    sys.stderr.write(
        "------------------------------------------------------------------------\n"
    )

    #Preemptively create debug file in case of major issue
    call(["touch", path + "debug"])

    flags = []

    i2c = i2c_link.I2CConnection()
    dw = data_writer.DataWriter()

    #Check if mobile broadband USB is connected
    if call(["ls /dev/tty* | grep USB"],
            shell=True,
            stderr=DEVNULL,
            stdout=DEVNULL) != 0:
        sys.stderr.write("ERROR: Modem is not connected. Exiting\n")
        return 3
    sms = SMS.SMS()

    #Start the internet connection
    if DEBUG:
        print "Starting Internet connection"
        sys.stdout.flush()
    call(["sudo", path + "/internet.sh"])

    if call(["ping", "-c", "4", "www.google.com.au"],
            stderr=DEVNULL,
            stdout=DEVNULL) == 0:
        internet_connection = True
    else:
        internet_connection = False
        sys.stderr.write("Ping failed. No internet connection\n")

    dbHelper = Dropbox.DropboxHelper()

    #Sychronise time
    if DEBUG:
        print "Attempting to update time"
        sys.stdout.flush()
    if internet_connection and call(["sudo sntp -s 0.au.pool.ntp.org"],
                                    shell=True) != 0:
        sys.stderr.write("Cannot sychronise time\n")

    now = datetime.datetime.now()
    if DEBUG:
        print now.ctime()
        sys.stdout.flush()
        sys.stderr.write(now.ctime() + '\n')

    #Update config file
    if DEBUG:
        print "Updating Dropbox"
        sys.stdout.flush()
    try:
        if internet_connection:
            dbHelper.get_file('config.ini', path + '/config.ini')
    except rest.ErrorResponse as details:
        sys.stderr.write(
            "MONITORING: Error getting config file from Dropbox\n" +
            str(details) + '\n')
        pass
    except rest.RESTSocketError as details:
        sys.stderr.write(
            "MONITORING: Error getting config file from Dropbox\n" +
            str(details) + '\n')
        pass

    #Parse config file
    if DEBUG:
        print "Reading config file"
    config = monitor_config.Config()
    config.read_config_file()
    i2c.update_off_period(config.off_time)

    prevData = dw.get_previous_datapoints(5)  #TODO: Add max
    if DEBUG:
        print "Getting and validating datapoint"

    for retries in range(10):
        #Get sensor readings
        datapoint = i2c.get_distance()
        print "Raw datapoint = " + str(datapoint)
        now = datetime.datetime.now()

        if datapoint < 0 and retries < 9:
            time.sleep(config.retry_time)  #Try again later
            continue
        elif datapoint == -1:
            #No or invalid response
            sys.stderr.write("Problem with ultrasonic sensor\n")
            if call(["ls " + path + " | grep error_alarm"],
                    shell=True,
                    stderr=DEVNULL,
                    stdout=DEVNULL) != 0:
                call(["touch", path + "/error_alarm"])
                msg = "Problem with sensor for tank {0} @ {1}".format(
                    config.name, now.strftime("%H:%M %d/%m/%Y"))
                sms.sendMessage(config.master, msg)
            else:
                print "Muted alarm"
            return 1
        elif datapoint == -2:
            #No echo recieved
            print "Exceeded max retries with ultrasonic sensor. Tank may be full, very empty or the sensor needs to be checked"
            #Check for previous extrapolated data
            extraps = 0
            for i in range(1, len(prevData) + 1):
                dp = prevData[-i]
                if isinstance(dp,
                              list) and len(dp) > 2 and 'extrapolated' in dp:
                    extraps = extraps + 1
                else:
                    extraps = 0
                if extraps > 3:
                    sys.stderr.write(
                        "Too many extrapolated datapoints in a row. Exiting without writing datapoint to file.\n"
                    )
                    if call(["ls " + path + " | grep error_alarm"],
                            shell=True,
                            stderr=DEVNULL,
                            stdout=DEVNULL) != 0:
                        call(["touch", path + "/error_alarm"])
                        msg = "Problem with sensor for tank {0} @ {1}".format(
                            config.name, now.strftime("%H:%M %d/%m/%Y"))
                        sms.sendMessage(config.master, msg)
                    else:
                        print "Muted alarm"
                    return 2
            #If ok to, set datapoint to be previous datapoint
            datapoint = prevData[-1][1]
            print "Setting datapoint to {0} from {1}".format(
                prevData[-1][1], prevData[-1][0].strftime("%H:%M %d/%m/%Y"))
            flags.append('extrapolated')
        elif datapoint >= 0:
            datapoint = 100 - (
                (float(datapoint) - config.sensorheightabovewater) /
                config.maxwaterheight * 100)  #Convert to perentage
            call(["rm", path + "/error_alarm"], stderr=DEVNULL, stdout=DEVNULL)
        break

    #Check if any alerts need to be sent
    prevData = dw.get_previous_datapoints(24)
    oneDay = datetime.timedelta(days=1)
    prevAlarms = 0
    for dp in prevData:
        if dp[0] > (now -
                    oneDay) and len(dp) > 2 and 'alarm' in dp:  #TODO: fix this
            prevAlarms = prevAlarms + 1
    if datapoint < config.low_water_level:
        if DEBUG:
            print "Low water alarm"
        if now.time() < config.quiet_time_start and now.time(
        ) > config.quiet_time_end and prevAlarms < config.max_alarms_per_day:
            flags.append('alarm')
        else:
            print "Muted alarm due to max alarms in a day or it is quiet time"
            print "Previous alarms = " + str(
                prevAlarms) + " before start_time  = " + str(now.time(
                ) < config.quiet_time_start) + "after end_time  = " + str(
                    now.time() < config.quiet_time_end)
            flags.append('muted')

    #Write datapoint to file
    if DEBUG:
        print "Writing data to file"
    filename = dw.write_datapoint(datapoint, flags)

    #Write datafile to dropbox
    if DEBUG:
        print "Updating datafile in Dropbox"
    try:
        if internet_connection:
            dbHelper.put_file(filename, filename, True)
    except rest.ErrorResponse as details:
        sys.stderr.write("MONITORING: Error updating datafile in Dropbox\n" +
                         str(details) + '\n')
        pass
    except rest.RESTSocketError as details:
        sys.stderr.write("MONITORING: Error updating datafile in Dropbox\n" +
                         str(details) + '\n')
        pass

    #Send datapoint to Xively
    if DEBUG:
        print "Sending data to Xively"
    if datapoint > -1:
        try:
            xively = Xively.XivelyHelper()
            if not xively.get_datastream("test"):
                xively.create_datastream("test", "test")
            xively.put_datapoint(datapoint)
        except Exception as details:
            sys.stderr.write("XIVELY: Error writing to feed\n" + str(details) +
                             '\n')

    #TODO: SMS stuff here
    if 'alarm' in flags:
        sms.sendCommand("")
        #Read the \r\n
        dummy = sms.serialReadline(eol='\n')
        #Read response
        response = sms.serialReadline().strip()
        if response != "OK":
            print "Not ready to send message"
            del sms
            return 3
        msg = "ALERT: Water level at {0:.2f}% in {1} tank @ {2}".format(
            datapoint, config.name, now.strftime("%H:%M %d/%m/%Y"))
        for no in config.white_list:
            sms.sendMessage(no, msg)

    #Send stopping and shutdown command
    return 0

    #Need to make function to check for new SMS's
    """
    Can call and immediately hang up. First check for new SMS's, then check number it came from.
    Then check first part of message and if it is "You missed a call from"
    then send most recent data.
    +CMTI: "ME", 0
    Need to delete message

    Do I need a mute SMS function? Yes I do in case it gets annoying
    So check for new message. Check if number is on the whitelist.
    if msg.lower().strip(' .?,!-:;()$%#"') == "mute":
        #Mute all msgs for the next 8 hours
    To show muting is enabled, create a file and check its last modification time
    using os.path.getmtime(<file>)
    Then add the "muted" to the flags
    """
    """
Exemple #31
0
def test_sms():
    SMS.storage_alert(65)
    item = {"Name": "Potatoes", "ID": 1234567, "Expiry": 2017 - 11 - 19}
    SMS.expiry_alert(item, 80)
sub = "buildapcsales"
subreddit = reddit.subreddit(sub)
start_time = time.time()
count = 0

if not os.path.isfile("posts_replied_to.txt"):
    posts_replied_to = []
else:
    with open("posts_replied_to.txt", "r") as f:
        posts_replied_to = f.read()
        posts_replied_to = posts_replied_to.split("\n")
        posts_replied_to = list(filter(None, posts_replied_to))

for submission in subreddit.stream.submissions():
    if submission.id not in posts_replied_to:
        price = 0
        title = submission.title
        int(filter(title.isdigit, price))

        if price > 500:
            count += 1
            print("Found turnips\n Sending...")
            message = ("\n{0} \n\n\n {1}".format(submission.title,
                                                 submission.url))
            SMS.send4(message)
            print("\n ::Sent:: \n Turnips Sent: {0}\n\n".format(str(count)))

            with open("posts_replied_to.txt", "w") as f:
                for post_id in posts_replied_to:
                    f.write(post_id + "\n")
Exemple #33
0
import SMS


SMS.send("hello my dear adam, this is adam from the cloud looking to send a message via email")
Exemple #34
0
import time

cap = cv2.VideoCapture(0)
length = 0
seconds = 1

message_sent = {'sent': False, 'time': time.time() - 5 * 60}

matchers = {'bus', 'school', 'public', 'transportation'}

phone = '2677508123'
email = '*****@*****.**'
password = '******'

if __name__ == "__main__":
    sms = SMS(phone, email, password)
    sms.send('Program Starting!')
    winsound.Beep(440, 200)
    while (1):
        # Take each frame

        _, frame = cap.read()
        k = cv2.waitKey(5) & 0xFF
        cv2.imwrite(os.path.join(os.path.dirname(__file__), 'frame.jpg'),
                    frame)

        if length % (30 * seconds) == 0:
            thread = threading.Thread(target=find_labels)
            thread.start()

        image = putText(frame, label_list)
Exemple #35
0
         minsLeft = int(scraper.getTimeLeft(i).split(":")[0])
         if firstTeamName + " vs. " + secTeamName not in alreadyPrinted:
             print("Tracked index " + str(i) + ": ")
             print("[Madness Notifier]\n(" + firstTeamSeed + ")" + firstTeamName + " - " + str(firstTeamScore)
                                  + "\nvs\n(" + secTeamSeed + ")" + secTeamName + " - " + str(secTeamScore)
                                  + "\nwith " + str(minsLeft) + " mins to go in the " + half + " half")
             alreadyPrinted.append(firstTeamName + " vs. " + secTeamName)
             print()
             print(str(len(alreadyPrinted)) + " games have been tracked!")
             print()
         if ("2" in half):
             if (firstTeamScore - secTeamScore <= 8 and firstTeamScore >= secTeamScore) or (secTeamScore - firstTeamScore <= 8 and secTeamScore >= firstTeamScore):
                 if (minsLeft <= 4):
                     if (firstTeamName + " vs. " + secTeamName not in alreadyNotified):
                         # It is a game deemed worth watching, now we msg ourselves to let us know
                         print("Game is " + firstTeamName + " vs " + secTeamName)
                         print("Half is " + half)
                         print("Minsleft is " + str(minsLeft))
                         SMS.send("[Madness Notifier]\n(" + firstTeamSeed + ")" + firstTeamName + " - " + str(firstTeamScore)
                                  + "\nvs\n(" + secTeamSeed + ")" + secTeamName + " - " + str(secTeamScore)
                                  + "\nwith " + str(minsLeft) + " mins to go")
                         print("Message has been sent")
                         print()
                         alreadyNotified.append(firstTeamName + " vs. " + secTeamName)
     except Exception as e:
         continue
 sleep(20)  # Sleeps every 20 seconds
 if startDate.day != datetime.datetime.now().day:
     startDate = datetime.datetime.now()
     alreadyNotified = list()
     alreadyPrinted = list()
import SMS, getpass

if __name__ == '__main__':
    # email = input("email: ") #'*****@*****.**'
    # password = getpass.getpass(prompt="password: "******"The end is near"

    SMS.send_message(email=email, password=password, message=message)