Exemplo n.º 1
0
 def set_repo(self, text):
     self.text = []
     self.textbox.do_command(ord(ctrl('a')))
     self.textbox.do_command(ord(ctrl('k')))
     for char in text:
         self.textbox.do_command(self.handle_input(ord(char)))
     self.no_ut_refresh()
Exemplo n.º 2
0
 def handle_input(self, input):
     input = self.translate_input(input)
     if input in range(curses.KEY_F0, curses.KEY_F10) or \
             input == curses.KEY_UP or input == curses.KEY_DOWN:
         logging.debug("Got special key, breaking")
         self.input = input
         return ord(ctrl('g'))
     else:
         self.input = None
     if input is not None and isprint(input):
         self.text_buff.append(chr(input))
         self.text.append(input)
         if not self.is_valid():
             if len(self.text) > 0:
                 self.text.pop()
                 length = len(self.text_buff)
                 temp_buff = self.text_buff[:length-49]
                 self.set_repo(self.text_buff[length-49:])
                 length = len(self.text_buff)
                 self.text_buff = temp_buff + self.text_buff[length-49:]
         if self.masked:
             input = self.masked_char
     elif input == curses.KEY_BACKSPACE or input == ord(ctrl('H')):
         if len(self.text) > 0:
             self.text.pop()
             self.text_buff.pop()
   
     return input
Exemplo n.º 3
0
    def __init__(self):
        super(Editor, self).__init__()
        self._redraw_scheduled = False

        self._document = TextDocument()
        self._filename = None

        # A simple dictionary mapping key-presses to callables.
        self.key_bindings = {
            ctrl('q'): self.quit,
            ctrl('s'): self.save,
            '\n': self.insert_newline,
            curses.KEY_ENTER: self.insert_newline,
            ctrl('h'): self.backspace,
            curses.KEY_BACKSPACE: self.backspace,
            curses.KEY_DC: self.delete,
            curses.KEY_DOWN: self.move_down,
            curses.KEY_NPAGE: self.move_page_down,
            curses.KEY_UP: self.move_up,
            curses.KEY_PPAGE: self.move_page_up,
            curses.KEY_LEFT: self.move_left,
            curses.KEY_RIGHT: self.move_right,
            curses.KEY_HOME: self.move_home,
            curses.KEY_END: self.move_end,
        }

        # The scroll position within the document is represented as the cell
        # location of the upper-left corner
        self.scroll = CellLocation(0, 0)

        # Desired cell cursor position after motion
        self.desired_x = 0

        # Flag indicating desired x should be updated
        self._update_desired_x = True
Exemplo n.º 4
0
 def send_sms(self, message, telephoneNumber):
     """Send a SMS"""
     #self._connection.open()
     self._connection = serial.Serial(self._device, self._speed, timeout=self._timeout)  # open port
     self._connection.write('AT+CMGF=1\r\n')
     self._connection.write('AT+CMGS="%s"\r\n' % telephoneNumber)
     self._connection.write(ascii.ctrl('m'))                        # end session
     self._connection.write(message)                                # message
     self._connection.write(ascii.ctrl('z'))                        # end session
     #self._connection.open()
     res = self._connection.readlines()
     self._connection.close()
     self._connection = None
     return res
Exemplo n.º 5
0
 def gsm_sms_send(self, number, message):
     ret = self.gsm_send_AT_command('AT+CMGS="'+number+'",145')
     if '>' in ret:
         ret = self.gsm_send_AT_command(message+ascii.ctrl('z'))
         if 'OK' in ret:
             return True
     return False
Exemplo n.º 6
0
def sendsms(phoneNumber, text):
	ser = serial.Serial('/dev/ttyUSB1', 460800, timeout=1)
	print ser.name

	ser.write("AT\r\n")
	line = ser.readline(size=None, eol='\r\n')
#	line = ser.readline()
	print line

	ser.write("AT+CMGF=1\r\n")
	line = ser.readline(size=None, eol='\r\n')
#	line = ser.readline()
	print line
#	print ser.readline()

	ser.write('AT+CMGS="%s"\r\n' %phoneNumber)
	ser.write(text)
	ser.write(ascii.ctrl('z'))
	time.sleep(3)
	print ser.readline()
	print ser.readline()
	print ser.readlines()

	ser.close()
	return
Exemplo n.º 7
0
def sendSMS(phonenumber):
    SMS = "Esto es una prueba"
    ser = serial.Serial('/dev/ttyUSB0', 460800, timeout=1)
    # 460800 is baud rate, ttyUSB0 is virtual serial port we are sending to
    ser.write("AT\r\n")
    # send AT to the ttyUSB0 virtual serial port
    line = ser.readline()
    print(line)
    # what did we get back from AT command? Should be OK
    ser.write("AT+CMGF=1\r\n")
    # send AT+CMGF=1 so setting up for SMS followed by CR
    line = ser.readline()
    print(line)
    # what did we get back from that AT command?
    ser.write('AT+CMGS="%s"\r\n' % phonenumber)
    # send AT+CMGS then CR, then phonenumber variable
    ser.write(SMS)
    # send the SMS variable after we sent the CR
    ser.write(ascii.ctrl('z'))
    # send a CTRL-Z after the SMS variable using ascii library
    time.sleep(10)
    # wait 10 seconds
    print ser.readline()
    print ser.readline()
    print ser.readline()
    print ser.readline()
Exemplo n.º 8
0
 def send_sms(self, message, telephoneNumber):
     """Send a SMS"""
     #self._connection.open()
     self._connection = serial.Serial(self._device,
                                      self._speed,
                                      timeout=self._timeout)  # open port
     self._connection.write('AT+CMGF=1\r\n')
     self._connection.write('AT+CMGS="%s"\r\n' % telephoneNumber)
     self._connection.write(ascii.ctrl('m'))  # end session
     self._connection.write(message)  # message
     self._connection.write(ascii.ctrl('z'))  # end session
     #self._connection.open()
     res = self._connection.readlines()
     self._connection.close()
     self._connection = None
     return res
Exemplo n.º 9
0
 def _at_command(self, command, sleep=0):
     #self._connection.open()
     import time
     self._connection = serial.Serial(
         self._device,
         self._speed,
         timeout=self._timeout,
         parity=serial.PARITY_NONE,
         stopbits=serial.STOPBITS_ONE,
         rtscts=True,
         dsrdtr=True,
         bytesize=serial.EIGHTBITS)  # open port
     self._connection.write(command)
     self._connection.write(ascii.ctrl('m'))  # end session
     #self._connection.close()
     #self._connection.open()
     #res = self._connection.readlines()
     self._connection.flush()
     self._connection.flushInput()
     self._connection.flushOutput()
     if sleep:
         time.sleep(sleep)
     res = []
     while self._connection.inWaiting():
         res.append(self._connection.readline())
     self._connection.close()
     return res
Exemplo n.º 10
0
 def sendmensaje(self, mns=""):
     """Función para enviar el mensaje"""
     self.serie.write(b'AT\r\n')
     time.sleep(1)
     #Le ponemos en modo para SMS
     self.serie.write(b'AT+CMGF=1\r\n')
     time.sleep(1)
     #encode('UTF-8') codificada a byte el mensaje
     #Comando para enviar el mensaje, se pasa el valor del número
     self.serie.write(b'AT+CMGS=\"' + self.receptor.encode('UTF-8') +
                      b'\"\r\n')
     time.sleep(0.5)
     #Se escribe el mensaje
     self.serie.write(mns.encode('UTF-8'))
     time.sleep(0.5)
     #Termina el menzaje con Ctrl+z
     self.serie.write(ascii.ctrl("z").encode('UTF-8'))
     time.sleep(0.5)
     #Le pasamos un fin de linea
     self.serie.write(b'\r\n')
     print("Mensaje enviado")
     self.serie.write("AT+CMGF=1\r\n")
     time.sleep(1)
     print("Escribiendo 2,2")
     #Muestra el mensaje por el puerto serial
     self.serie.write("AT+CNMI=2,2,0,0,0\r\n")
     time.sleep(1)
     while True:
         res = self.serie.readline()
         print(res)
Exemplo n.º 11
0
    def send(self, receiver, message):
        if receiver is not None and message is not None:
            print "[DEBUG] Sending SMS with details: "
            print "Reciever: %s" % receiver
            print "Message: %s" % message
            time222 = strftime("%Y-%m-%d %H:%M:%S", gmtime())
            print "Time: %s", time222

            self.modem.write(b'AT+CMGS="%s"\r' % receiver)
            sleep(0.05)
            self.modem.write(b'%s\r' % message)
            sleep(0.05)
            self.modem.write(ascii.ctrl('z'))
            sleep(0.05)
            response = self.modem.readlines()
            if "+CMGS" in response[-3]:
                print "[INFO ] SMS sent successfully!"
                log("success",
                    "sms",
                    "Poruka sa sledecim detaljima je uspesno poslata",
                    more="Primalac: %s Poruka: %s" % (
                        receiver,
                        message,
                    ))
            else:
                print "[ERROR] Something went wrong while sending SMS!"
                log("danger",
                    "sms",
                    "Doslo je do greske prilikom slanja poruke",
                    more="Primalac: %s Poruka: %s" % (receiver, message))
        else:
            print ""
Exemplo n.º 12
0
def sendsms(phoneNumber, text):
    ser = serial.Serial('/dev/ttyUSB1', 460800, timeout=1)
    print ser.name

    ser.write("AT\r\n")
    line = ser.readline(size=None, eol='\r\n')
    #	line = ser.readline()
    print line

    ser.write("AT+CMGF=1\r\n")
    line = ser.readline(size=None, eol='\r\n')
    #	line = ser.readline()
    print line
    #	print ser.readline()

    ser.write('AT+CMGS="%s"\r\n' % phoneNumber)
    ser.write(text)
    ser.write(ascii.ctrl('z'))
    time.sleep(3)
    print ser.readline()
    print ser.readline()
    print ser.readlines()

    ser.close()
    return
Exemplo n.º 13
0
    def _at_command(self, command, sleep=0):
        #self._connection.open()
        import time
        self._connection = serial.Serial(self._device, 
                self._speed, timeout=self._timeout,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
		rtscts=True, dsrdtr=True,
                bytesize=serial.EIGHTBITS
                )  # open port
        self._connection.write(command)
        self._connection.write(ascii.ctrl('m'))                        # end session
        #self._connection.close()
        #self._connection.open()
        #res = self._connection.readlines()
        self._connection.flush()
        self._connection.flushInput()
        self._connection.flushOutput()
        if sleep:
            time.sleep(sleep)
        res = []
        while self._connection.inWaiting():
            res.append(self._connection.readline())
        self._connection.close()
        return res
def sendsms(number, text):
    ser.write('AT+CMGF=1\r\n')
    sleep(2)
    ser.write('AT+CMGS="%s"\r\n' % number)
    sleep(2)
    ser.write('%s' % text)
    sleep(2)
    ser.write(ascii.ctrl('z'))
Exemplo n.º 15
0
def sendsms(number, text):
    ser.write('AT+CMGF=1\r\n')
    sleep(2)
    ser.write('AT+CMGS="%s"\r\n' % number)
    sleep(2)
    ser.write('%s' % text)
    sleep(2)
    ser.write(ascii.ctrl('z'))
    print "Text: %s  \nhas been sent to: %s" % (text, number)
Exemplo n.º 16
0
def sendsms(number,text):
    ser.write('AT+CMGF=1\r\n')
    sleep(2)
    ser.write('AT+CMGS="%s"\r\n' % number)
    sleep(2)
    ser.write('%s' % text)
    sleep(2)
    ser.write(ascii.ctrl('z'))
    print "Text: %s  \nhas been sent to: %s" %(text,number)
Exemplo n.º 17
0
def sendSMS(message, telephoneNumber):
    """Send a SMS"""
    ser = serial.Serial(connection, baudrate, timeout=5)  # open port

    ser.write('AT+CPIN="%s"\r\n' % pin)                   # PIN-Code
    ser.write('AT+CMGF=1\r\n')                            # to TEXTMODE

    ser.write('AT+CMGS="%s"\r\n' % telephoneNumber)       # tel number
    ser.write(message)                                    # message
    ser.write(ascii.ctrl('z'))                            # end session
def smstx(msg,num):
   lat,lon = displl()
   adrport.write('AT+CMGF=1\r\n')
   time.sleep(0.5)        
   adrport.write('AT+CMGS="{}"\r\n'.format(num))
   #print('AT+CMGS="%s"\r\n' %dnum)
   time.sleep(0.5)
   adrport.write("{}.Location is latitude:{}, longitude:{} -Vehicle security system.\r\n".format(msg,lat,lon))
   time.sleep(0.5)
   adrport.write(ascii.ctrl('z'))
   time.sleep(8)   
   return
Exemplo n.º 19
0
def send_sms(message, phonenumber):
    # Initialize serial connection to 3G USB Modem
    modem = serial.Serial(device, baudrate, timeout=5)
    print "Connected to " + modem.name
    # Check modem status
    modem.write(b'AT\r')
    sent_cmd = getline(modem)
    response = modem.read(4)
    if "OK" in response:
        print "Modem Status: OK"
        # check pin and enter it if needed
        modem.write(b'AT+CPIN?\r')
        sent_cmd = getline(modem)
        line2 = getline(modem)  # empty
        line3 = getline(modem)  # empty
        response = getline(modem)  # get OK
        #print(response)
        if "SIM PIN" in response:
            print "Sending PIN to modem ... "
            modem.write(b'AT+CPIN="%s"' % simpin)
            sent_cmd = getline(modem)
            response = getline(modem)
            print response
        elif "READY" in response:
            print "PIN already entered."
        elif "SIM not inserted" in response:
            print "Sem CHIP"
        # set modem to text mode
        modem.write(b'AT+CMGF=1\r')
        sent_cmd = getline(modem)
        response = getline(modem)
        if "OK" in response:
            print "Modem set to text mode!"
            # send sms
            print "Sending sms ..."
            modem.write(b'AT+CMGS="%s"\r' % phonenumber)
            time.sleep(0.5)
            modem.write(b'%s\r' % message)
            time.sleep(0.5)
            modem.write(ascii.ctrl('z'))
            time.sleep(0.5)
            response = modem.readlines()
            if "+CMGS" in response[-3]:
                print(response)
                print "Sucess: SMS sent!"
            else:
                print "Error: SMS not sent!"
        else:
            print "Error: Setting modem to text mode failed!"
    elif "NO CARRIER" in response:
        print "Error: No 3G connection!"
    else:
        print "Error: Something else failed!"
Exemplo n.º 20
0
    def echo_handler(self, connection):
        """ Fallback handler incase of no handlers. Echos the requests.
        """
        while True:
            request = connection.recv(1024)
            if 'end' in request:
                break
            elif request:
                connection.send(request)

        connection.send(ctrl(']'))
        connection.close()
Exemplo n.º 21
0
    def echo_handler(self, connection):
        """ Fallback handler incase of no handlers. Echos the requests.
        """
        while True:
            request = connection.recv(1024)
            if 'end' in request:
                break
            elif request:
                connection.send(request)

        connection.send(ctrl(']'))
        connection.close()
 def sendsms(number, text):
     print(number)
     first = 'AT+CMGF=1\r\n'
     ser.write(first.encode())
     sleep(2)
     second = 'AT+CMGS="%s"\r\n' % number
     ser.write(second.encode())
     sleep(2)
     third = '%s' % text
     ser.write(third.encode())
     sleep(2)
     fourth = ascii.ctrl('z')
     ser.write(fourth.encode())
Exemplo n.º 23
0
def send_sms(modem, to, text):
    log.debug("Sending SMS " + str(to))
    time.sleep(2)
    # switch to text mode
    modem.write(b'AT+CMGF=1\r')
    time.sleep(2)
    # set the recipient number
    modem.write(b'AT+CMGS="' + to.encode() + b'"\r')
    time.sleep(2)
    # send the message
    modem.write(text.encode())
    time.sleep(1)
    # end the message with ctrl+z
    modem.write(ascii.ctrl('z'))
Exemplo n.º 24
0
def sendSMS(number, text):
    ser = serial.Serial('/dev/ttyUSB0', 460800, timeout=1)
    ser.write("AT\r\n")
    time.sleep(1)

    ser.write("AT+CMGF=1\r\n")
    time.sleep(1)

    ser.write('AT+CMGS="%s"\r\n' % number)
    ser.write(text)
    ser.write(ascii.ctrl('z'))
    time.sleep(3)
    ser.close()
    return
Exemplo n.º 25
0
def send_sms(text):
	#initialize the AT
	gsm.write("AT\r")
	time.sleep(2)
	reply=gsm.read(gsm.inWaiting())
	print(reply)
	#set the mode to text mode
	gsm.write("AT+CMGF=1\r")
	time.sleep(2)
	reply=gsm.read(gsm.inWaiting())
	print(reply)
	#delete all SMS in memory
	gsm.write('AT+CMGDA="DEL ALL"\r')
	time.sleep(2)
	reply=gsm.read(gsm.inWaiting())
	print(reply)
	#remove anything from the input buffer
	gsm.flushInput()
	reply=gsm.read(gsm.inWaiting())
	print("listening for any incoming sms...")
	print text
	while True:
		if reply != "":
			#read the new message
			gsm.write('AT+CMGR=1\r')
			time.sleep(3)
			reply=gsm.read(gsm.inWaiting())
			print("the received content is ->")
			print(reply)
			#reply=+CMGR: "REC UNREAD","+489300222",,"07/02/18.00:05:10+32"
			x=reply.split(,);
			number=x[1];
			print("the number is->")
			print(number)
			if "LOCATE" in reply:
				#prepare to send latlong to sender
				gsm.write("AT+CSMP=17,167,0,16\r")
				time.sleep(3)
				#set mode to gsm
				gsm.write('AT+CSCS="GSM"\r')
				time.sleep(3)
				#send latlong as msg
				gsm.write('AT+CMGS="+254718145956"\r')
				time.sleep(2)
				gsm.write(text)
				gsm.write(ascii.ctrl('z'))
				time.sleep(5)
				reply=gsm.read(gsm.inWaiting())
				print(reply)
Exemplo n.º 26
0
	def _input_iteration(self):
		ch = self.mainscr.getch()
		if QUITTING_TIME.isSet(): return False
		logging.debug("input: %r (%s / %s, ctrl=%s)" % (ch, ascii.unctrl(ch), ascii.ctrl(ch), ascii.isctrl(ch)))
		if ascii.isprint(ch):
			self.add_char(chr(ch))
		elif ch in (ascii.BS, ascii.DEL, curses.KEY_BACKSPACE):
			self.remove_char()
		elif ch == ascii.NL:
			self.open_selected()
		elif ch == curses.KEY_UP or (ascii.ismeta(ch) and ascii.unctrl(ch) == 'a'): # shift+tab???
			self.select(PREVIOUS)
		elif ch == curses.KEY_DOWN or ch == curses.ascii.TAB:
			self.select(NEXT)
		elif ch == curses.KEY_LEFT:
			self.move_cursor(backwards=True)
		elif ch == curses.KEY_RIGHT:
			self.move_cursor()
		elif ch == curses.KEY_HOME:
			self.move_cursor_to(0)
		elif ch == curses.KEY_END:
			self.move_cursor_to(len(self.query))
		elif ascii.isctrl(ch) and ascii.ctrl(ch) in (ascii.STX, ascii.ETX, ascii.CAN, ascii.ETX): # ctrl-c, variously o_O
			logging.debug("copy to clipboard")
			self.copy_selected_path_to_clipboard()
		elif ch == ascii.ESC:
			self.set_query("")
		elif ch == ascii.EOT: # ctrl-D
			logging.debug("EOF")
			return False
		else:
			logging.debug("not handled...")
		self.ui_lock.acquire()
		self.update()
		self.ui_lock.release()
		return True
Exemplo n.º 27
0
 def sendMessage(self, phoneNr, textMessage):
     logging.info("Sending Message %s to %s " % (textMessage, phoneNr))
     logging.debug("Switching to TEXT mode.")
     cmd = "AT+CMGF=1\r\n"
     self.ser.write(cmd.encode())
     textMessage = textMessage + ascii.ctrl('Z')
     cmd = 'AT+CMGS="%s"\r\n' % phoneNr
     logging.debug(cmd)
     self.ser.write(cmd.encode())
     logging.debug(textMessage)
     self.ser.write(textMessage.encode())
     line = self.ser.readline()
     strLine = line.decode()
     logging.debug(strLine)
     line = self.ser.readline()
     strLine = line.decode()
     logging.debug(strLine)
Exemplo n.º 28
0
class Hash(object):
    HASH_KEY=ascii.ctrl('\\')
    def __init__(self):
        self.line = linebuf.LineBuf()
        self.term = term.Terminal(0)
        self.aliascmds = {}

    def completer(self, text, state):
        matches = [s for s in self.cmdtab.keys() if s.startswith(text)]

        try:
            return matches[state]
        except IndexError:
            return None

    def load_commands(self):
        import command
        import commands
        import filetransfer

        self.cmdtab = {}
        for cmd in command.list_commands():
            self.cmdtab[ cmd.name ] = cmd(self)

    def builtin_bang(self, line):
        os.system(line[1:])

    def builtin_alias(self, line):
        line = line[5:].strip()
        if not line.strip():
            for k,v in self.aliascmds.iteritems():
                print "%s = %s" % (k,v)
        else:
            alias_cmd, sh_cmd = line.split('=', 1)
            self.aliascmds[ alias_cmd ] = sh_cmd
            self.cmdtab[alias_cmd] = alias.Alias(self, sh_cmd)

    def builtin_command(self, line):
        argv = shlex.split(line)
        if argv[0] in self.cmdtab:
            try:
                self.cmdtab[argv[0]].process(argv)
            except Exception, e:
                print 'Error!', e
        else:
Exemplo n.º 29
0
def sendSMS(modem, phoneNumber, text):
	modem.write('AT+CMGS="%s"\r' %phoneNumber)
	modem.write(text)
	modem.write(ascii.ctrl('z'))
	time.sleep(2)
	
	modem.readline()
	modem.readline()
	modem.readline()
	cmgi = modem.readline()
	modem.readline()
	modem.readline()
	status = modem.readline()
	if status.startswith("OK"):
		logger.info("SMS sent.")
		return True
	else:
		logger.error("Error sending SMS")
		return False
Exemplo n.º 30
0
def sendSMS(modem, phoneNumber, text):
    modem.write('AT+CMGS="%s"\r' % phoneNumber)
    modem.write(text)
    modem.write(ascii.ctrl('z'))
    time.sleep(2)

    modem.readline()
    modem.readline()
    modem.readline()
    cmgi = modem.readline()
    modem.readline()
    modem.readline()
    status = modem.readline()
    if status.startswith("OK"):
        logger.info("SMS sent.")
        return True
    else:
        logger.error("Error sending SMS")
        return False
Exemplo n.º 31
0
def sendmensaje(receptor, mns=""):
	"""Función para enviar el mensaje"""
	serie.write('AT\r\n')
	time.sleep(1)
	#Le ponemos en modo para SMS
	serie.write('AT+CMGF=1\r\n')
	time.sleep(1)
	#Comando para enviar el mensaje, se pasa el valor del número
	serie.write('AT+CMGS=\"' + receptor + '\"\r\n')
	time.sleep(1)
	#Se escribe el mensaje
	serie.write(mns)
	time.sleep(3)
	#Termina el menzaje con Ctrl+z
	serie.write(ascii.ctrl("z"))
	time.sleep(3)
	#Le pasamos un fin de linea
	serie.write('\r\n')
	print ("Mensaje enviado\n")
Exemplo n.º 32
0
 def serialCommand(self, cmd, message=""):
     logging.debug("Serial Command %s Message <%s>" %
                   (cmd.replace("\r\n", ""), message))
     retval = ""
     if (message != ""):
         message = message + ascii.ctrl('Z')
         self.ser.write(cmd.encode())
         self.ser.write(message.encode())
     else:
         self.ser.write(cmd.encode())
     try:
         line = self.ser.readline()
         while (line != b''):
             retval = retval + line.decode()
             logging.debug(line)
             line = self.ser.readline()
     except:
         retval = ""
     return retval
Exemplo n.º 33
0
def serialCommand(ser, cmd, message=""):
    retval = ""
    if (message != ""):
        logging.debug("-- SEND --")
        logging.debug("  Command:%s" % cmd)
        logging.debug("---------")
        logging.debug("  Message:%s" % message)
        logging.debug("---------")
        message = message + ascii.ctrl('Z')
        ser.write(cmd.encode())
        ser.write(message.encode())
    else:
        ser.write(cmd.encode())
    line = ser.readline()
    while (line != b''):
        retval = retval + line.decode()
        logging.debug(line)
        line = ser.readline()
    return retval
Exemplo n.º 34
0
def sendSMS(phonenumber, msg):
    SMS = "Esto es una prueba"
    ser = serial.Serial('/dev/ttyUSB0', 460800, timeout=1)
    # 460800 is baud rate, ttyUSB0 is virtual serial port we are sending to
    ser.write("AT\r\n")
    time.sleep(0.5)
    # send AT to the ttyUSB0 virtual serial port
    line = ser.readline()
    print(line)
    # what did we get back from AT command? Should be OK
    ser.write("AT+CMGF=1\r\n")
    time.sleep(0.5)
    # send AT+CMGF=1 so setting up for SMS followed by CR
    line = ser.readline()
    #print(line)
    # what did we get back from that AT command?
    ser.write('AT+CMGS="%s"\r\n' % phonenumber)
    time.sleep(0.5)
    # escribimos el texto del mensaje
    ser.write(msg + ascii.ctrl('z'))
    time.sleep(0.5)
    #time.sleep(2)
    # send AT+CMGS then CR, then phonenumber variable
    #ser.write(SMS)
    # send the SMS variable after we sent the CR
    #ser.write(ascii.ctrl('z'))
    # send a CTRL-Z after the SMS variable using ascii library
    time.sleep(10)
    # wait 10 seconds
    line += ser.readline()
    line += ser.readline()
    line += ser.readline()
    line += ser.readline()
    #print ser.readline()
    #print ser.readline()
    #print ser.readline()
    #print ser.readline()
    print(line)
    # borramos mensajes recibidos
    ser.write("AT+CMGD=2\r\n")
    line = ser.readline()
    print(line)
Exemplo n.º 35
0
    def process(self, input):
        try:
            self.old_cursor_state = curses.curs_set(2)
        except curses.error:
            logging.debug("Got curses.error when enabling cursor")
        
        # Put input back on stack so that textbox.edit can read it
        try:
            curses.ungetch(input)
        except TypeError:
            pass

        self.textbox.do_command(ord(ctrl('e')))
        self.textbox.edit(self.handle_input)
        
        try:
            self.old_cursor_state = curses.curs_set(self.old_cursor_state)
        except curses.error:
            logging.debug("Got curses.error when reverting cursor")
        logging.debug("Returning: " + str(self.input))
        return self.input
Exemplo n.º 36
0
def testSMS(counter):
    stat = True
    x = smscol.find_one({"Status":"Pending"})
    penMessage = x['Message']
    global num
    sender = x['Sender']
    num = x['Receiver']
    date1 = x['Date']
    modem.write(bytes('AT+CMGS="%s"\r\n' % num))
    time.sleep(0.5)
    modem.write(bytes('Message: "%s"\r\n' % penMessage))
    time.sleep(0.5)
    modem.write(bytes('Sender: %s\r\n' % sender))
    time.sleep(0.5)
    modem.write(bytes('Date: %s' % date1))
    time.sleep(0.5)
    modem.write(bytes(ascii.ctrl('z')))
    time.sleep(0.5)
    while stat:
        a = modem.readlines(modem.inWaiting())
        z = []
        y = ''

        for q in a:
            if q.startswith('OK') or q.startswith('+CMS') or q.startswith('^RSSI'):
                r = a.index(q)
                z.append(r)
                stat = False
            else: pass

        for q in z:
            y = a[q]

    print(y, 'sent?')

    if y.startswith('OK'):
        print('sent')
        smscol.update_one({"Status":"Pending"},{ "$set":{"Status":"Processed"}})    
    elif y.startswith('+CMS') or y.startswith('^RSSI'):
        print('failed')
Exemplo n.º 37
0
def prompt(message, default=None, characters=None):
    """Prompt for input.

    :param message: The prompt message.
    :param default: Default `None`. The default input value.
    :param characters: Default `None`. Case-insensitive constraint for single-
        character input.
    """
    if isinstance(default, basestring):
        message = "{0} [{1}]".format(message, default)

    if characters:
        puts("{0} ".format(message), newline=False)
    else:
        message = "{0}: ".format(message)

    while True:
        if characters:
            ret_val = getch()

            if default is not None and ret_val in (chr(CR), chr(LF)):
                puts()
                ret_val = default
                break
            if ret_val in characters.lower() or ret_val in characters.upper():
                puts()

                if ret_val not in characters:
                    ret_val = ret_val.swapcase()

                break
            elif isctrl(ret_val) and ctrl(ret_val) in (chr(ETX), chr(EOT)):
                raise KeyboardInterrupt
        else:
            ret_val = raw_input(message).strip() or default

            if ret_val:
                break

    return ret_val
Exemplo n.º 38
0
	def sendMessageInstance(self, message, telephoneNumber):
		try:
			#############################
			timeCounter = 0
			self.successfulSending = None
			#############################
			# Serializamos el objeto para poder transmitirlo
			serializedMessage = 'INSTANCE' + pickle.dumps(message)
			# Enviamos los comandos AT correspondientes para efectuar el envío el mensaje de texto
			info01 = self.sendAT('AT+CMGS="' + str(telephoneNumber) + '"') # Numero al cual enviar el SMS
			info02 = self.sendAT(serializedMessage + ascii.ctrl('z'))      # Mensaje de texto terminado en Ctrl+Z
			# ------------------ Caso de envío EXITOSO ------------------
			# Ejemplo de info02[0]: Mensaje enviado desde el Modem.\x1a\r\n
			# Ejemplo de info02[1]: +CMGS: 17\r\n
			# Ejemplo de info02[3]: OK\r\n
			# Comprobamos si el envío fue exitoso
			for i in info02:
				if i.startswith('OK'):
					self.successfulSending = True
					break
				elif i.startswith('+CMS ERROR'):
					self.successfulSending = False
					break
			# Esperamos respuesta de la red si es que no la hubo
			while self.successfulSending is None and timeCounter < 15:
				time.sleep(1)
				timeCounter += 1
			# Comprobamos si hubo respuesta de la red y cual fue..
			if self.successfulSending is True:
				logger.write('INFO', '[GSM] Instancia de mensaje enviada a %s.' % str(telephoneNumber))
				# Borramos el mensaje enviado almacenado en la memoria
				self.removeAllSms()
				return True
			else:
				logger.write('WARNING', '[GSM] No se pudo enviar la instancia a %s.' % str(telephoneNumber))
				return False
		except:
			logger.write('ERROR', '[GSM] Error al enviar la instancia de mensaje a %s.' % str(telephoneNumber))
			return False
Exemplo n.º 39
0
def enviarSMS(telf, iddb, Resultado):
    try:

        # Le ponemos en modo para SMS
        sSerie.write("AT+CMGF=1\r\n")
        time.sleep(.4)
        sSerie.write("AT+CSCA=\"+51190000000\"\r\n")
        time.sleep(.4)
        #print(sSerie.readline())
        # Le pasamos el numero al que vamos ha mandar el SMS
        sSerie.write("AT+CMGS=\"" + telf + "\"\r\n")
        time.sleep(.4)
        # Texto del mensaje terminado en Ctrl+Z
        sSerie.write(iddb + " " + Resultado + "\r\n" + ascii.ctrl('z'))
        print sSerie.readline()
        print "SMS enviado"
        # Leemos la informacion devuelta
        time.sleep(.2)
        resp = sSerie.readline()
        resp = resp.strip()
        if (resp != "OK"):
            time.sleep(.2)
            resp = resp + sSerie.readline()
            resp = resp.strip()
        time.sleep(1)
        print "Envio SMS:" + resp
        if resp == "OK":
            try:
                sqlu = "UPDATE smslog SET F_Respuesta=now(),Estado='Enviado',Resultado='" + Resultado + "' WHERE idSMS='" + iddb + "'"
                cur.execute(sqlu)
                conn.commit()
                print "FIN: Se envio SMS con exito"
            except:
                conn.rollback()
                print "Error al actualizar en la base"
        else:
            print "FIN de proceso, No se pudo enviar respuesta...!!!"
    except ValueError:
        print("Oops! se ha producido un error ...")
Exemplo n.º 40
0
    def sendSMS(self, number: str, data: str):

        self.logger.debug("Sending SMS messsage >{}< to {}".format(data, number))

        self.logger.debug("AT+CMGF")
        self.modem.write(b"AT+CMGF=1\r")
        time.sleep(0.5)
        self.logger.debug(self.read_all())

        self.logger.debug("AT+CSCS")
        self.modem.write(b"AT+CSCS=\"GSM\"\r")
        time.sleep(0.5)
        self.logger.debug(self.read_all())

        self.logger.debug("AT+CMGS")
        self.modem.write("AT+CMGS=\"{}\"\r".format(number).encode("ascii"))
        time.sleep(0.5)
        self.modem.write(data.encode("ascii"))
        time.sleep(0.5)
        self.modem.write(ascii.ctrl('z').encode("ascii"))

        self.logger.debug(self.read_all())

        self.logger.debug("Message sent")
Exemplo n.º 41
0
import time
import serial
from types import *
from curses import ascii

# Modem Commands and other necessary strings
AT='AT'
OK='OK'
CTRLZ=ascii.ctrl('z')
CR='\r'
PLUS='+'
NEWLINE='\n'
CMGF='+CMGF=1'
CMGS='+CMGS='
QUOTES='\"'
COPS='+COPS?'
CSQ='+CSQ'
CBC='+CBC'


def getCBC(serialConnection):
    sendCommand(serialConnection, AT+CBC+NEWLINE)
    response = sanitize(getResponse(serialConnection))
    return response

def getBatteryLevel(serialConnection):
    response = getCBC(serialConnection)
    return response[8:10]

def getVoltageLevel(serialConnection):
    response = getCBC(serialConnection)
Exemplo n.º 42
0
print ser.name

ser.write("AT\r\n")
line = ser.readline()
print line
line = ser.readline()
print line

ser.write("AT+CMGF=0\r\n")
line = ser.readline()
print line
line = ser.readline()
print line
print ser.readline()

#ser.write("AT+ZMSGL=1,2")
#print ser.readline()
#print ser.readline()
#print ser.readline()

ser.write('AT+CMGS=21\r')# %"359882506400")
ser.write("07915389080003F111000C915389280546000004FF0774657374696E67")
ser.write(ascii.ctrl('z'))
time.sleep(3)
print ser.readline()
print ser.readline()
print ser.readlines()

ser.close()
DEVNULL.close()
Exemplo n.º 43
0
def _parse_key1(key, s):
    ctrl = 0
    meta = 0
    ret = ''
    while not ret and s < len(key):
        if key[s] == '\\':
            c = key[s+1].lower()
            if _escapes.has_key(c):
                ret = _escapes[c]
                s += 2
            elif c == "c":
                if key[s + 2] != '-':
                    raise KeySpecError, \
                              "\\C must be followed by `-' (char %d of %s)"%(
                        s + 2, repr(key))
                if ctrl:
                    raise KeySpecError, "doubled \\C- (char %d of %s)"%(
                        s + 1, repr(key))
                ctrl = 1
                s += 3
            elif c == "m":
                if key[s + 2] != '-':
                    raise KeySpecError, \
                              "\\M must be followed by `-' (char %d of %s)"%(
                        s + 2, repr(key))
                if meta:
                    raise KeySpecError, "doubled \\M- (char %d of %s)"%(
                        s + 1, repr(key))
                meta = 1
                s += 3
            elif c.isdigit():
                n = key[s+1:s+4]
                ret = chr(int(n, 8))
                s += 4
            elif c == 'x':
                n = key[s+2:s+4]
                ret = chr(int(n, 16))
                s += 4
            elif c == '<':
                t = key.find('>', s)
                if t == -1:
                    raise KeySpecError, \
                              "unterminated \\< starting at char %d of %s"%(
                        s + 1, repr(key))                        
                ret = key[s+2:t].lower()
                if ret not in _keynames:
                    raise KeySpecError, \
                              "unrecognised keyname `%s' at char %d of %s"%(
                        ret, s + 2, repr(key))
                ret = _keynames[ret]
                s = t + 1
            else:
                raise KeySpecError, \
                          "unknown backslash escape %s at char %d of %s"%(
                    `c`, s + 2, repr(key))
        else:
            ret = key[s]
            s += 1
    if ctrl:
        if len(ret) > 1:
            raise KeySpecError, "\\C- must be followed by a character"
        ret = ascii.ctrl(ret)
    if meta:
        ret = ['\033', ret]
    else:
        ret = [ret]
    return ret, s

import curses
from curses.ascii import ctrl
from copy import copy
import functools

import terminalui
from terminalui import LOG_LEVEL_INPUT
from terminalui.i18n import fit_text_truncate, \
                            convert_paragraph, \
                            get_encoding, \
                            textwidth

KEY_BS = 127  # Backspace code that curses doesn't translate right
KEY_CTRL_H = ord(ctrl('h'))
KEY_TAB = ord(ctrl('i'))
KEY_ENTER = ord(ctrl('j'))


def no_action(input_key):
    '''Supports defining actions which have no effect and allow parent
    windows to handle the key.

    '''
    return input_key


def consume_action(dummy):
    '''Supports defining an action which has no effect, and consume the
    keystroke so that parents do not handle it.
Exemplo n.º 45
0
def _parse_key1(key, s):
    ctrl = 0
    meta = 0
    ret = ''
    while not ret and s < len(key):
        if key[s] == '\\':
            c = key[s+1].lower()
            if _escapes.has_key(c):
                ret = _escapes[c]
                s += 2
            elif c == "c":
                if key[s + 2] != '-':
                    raise KeySpecError, \
                              "\\C must be followed by `-' (char %d of %s)"%(
                        s + 2, repr(key))
                if ctrl:
                    raise KeySpecError, "doubled \\C- (char %d of %s)"%(
                        s + 1, repr(key))
                ctrl = 1
                s += 3
            elif c == "m":
                if key[s + 2] != '-':
                    raise KeySpecError, \
                              "\\M must be followed by `-' (char %d of %s)"%(
                        s + 2, repr(key))
                if meta:
                    raise KeySpecError, "doubled \\M- (char %d of %s)"%(
                        s + 1, repr(key))
                meta = 1
                s += 3
            elif c.isdigit():
                n = key[s+1:s+4]
                ret = chr(int(n, 8))
                s += 4
            elif c == 'x':
                n = key[s+2:s+4]
                ret = chr(int(n, 16))
                s += 4
            elif c == '<':
                t = key.find('>', s)
                if t == -1:
                    raise KeySpecError, \
                              "unterminated \\< starting at char %d of %s"%(
                        s + 1, repr(key))
                try:
                    ret = _keynames[key[s+2:t].lower()]
                    s = t + 1
                except KeyError:
                    raise KeySpecError, \
                              "unrecognised keyname `%s' at char %d of %s"%(
                        key[s+2:t], s + 2, repr(key))
                if ret is None:
                    return None, s
            else:
                raise KeySpecError, \
                          "unknown backslash escape %s at char %d of %s"%(
                    `c`, s + 2, repr(key))
        else:
            if ctrl:
                ret = unicode(ascii.ctrl(key[s]))
            else:
                ret = unicode(key[s])
            s += 1
    return (ret, meta, ctrl), s
Exemplo n.º 46
-1
    def readKeypress(self):
        i = sys.stdin.read(1)

        if i == ctrl('q'):
            self.quit()
            return
        elif i == ctrl('s'):
            self.save()
            return

        self.dirtyFlag = True

        if i[0] == '\x1b':
            i = sys.stdin.read(2)
            inputSwitcher = {
                'A': 'UP',
                'B': 'DOWN',
                'C': 'RIGHT',
                'D': 'LEFT',
            }
            i = inputSwitcher[i[1]]
        elif ord(i) == 127:
            i = 'BACKSPACE'
        elif ord(i) == 13:
            i = 'ENTER'

        self.editor.processKeypress(i)