summaryrefslogblamecommitdiffstats
path: root/Handler/ca_stMa.py
blob: 5df33c8d8b4de2cecdea397470161365c534bb99 (plain) (tree)
























































































































































                                                                                                                                                                
from serial import * #serial port library
from threading import Thread  #library to make a thread (I guess)
from time import sleep #timer library
import string #import the string handling library 
import sys
import atexit
import signal

####START of the definition how the serial port works

class TimeoutException(Exception):
    pass

def serial_portFunc():
    def timeout_handler(signum, frame):
        raise TimeoutException()

    old_handler = signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(50) # triger alarm in 50 seconds

    try:
	    global last_received #make last_received a global variable
	    global exitSuccessful
	    portAddress = '/dev/ttyUSB0'
	    portName = portAddress[-4:]
            portExist = os.popen('dmesg | grep ' + portName).read()

            if portExist == '':
             print 'The serial port does not exist'
             sys.exit()
            
	    ser = Serial(
		port=portAddress,
		baudrate=19200,
		bytesize=EIGHTBITS,
		parity=PARITY_NONE,
		stopbits=STOPBITS_ONE
		#timeout=0,
		#writeTimeout=0
		#xonxoff=0,
		#rtscts=0
		#interCharTimeout=None
		#I didn't need to set these variables :)
	    )
	####END of the definition how the serial port works
	    exitSuccessful = 0 #variable used to know if it closed successfully

	    last_received = '' #reset the last received variable
	    global pickUp
	    pickUp = 0
	    ser.write('AT\r') #just communicate with the cellphone at start
	    callTrue=0 #use this variable to make sure the cell phone has dialed a number
	    pickUp =0 #use to test if I pick up the call
	    firstCall = 1
	    firstCallSuccessful=0
	    buffer = ''   #make sure buffer variable is empty
	    for arg in sys.argv:
	     callThisNumberFirst = arg
	    while True:   #repeat the message accepting part forever


		#####BEGIN part responsible for receiving on serial port

		buffer = buffer + ser.read(ser.inWaiting()) #read the serial port and add it to the buffer variable
		if '\n' in buffer: #if a new line character is found in the buffer then the cellphone has sent something
		    lines = buffer.split('\n') #parse the buffer variable with the new line character
		    last_received = lines.pop(0) #put into last_received variable the first content from lines (FIFO)

		    buffer = '\n'.join(lines) #add a new line to the buffer variable

		    last_received=last_received.split('\n') #parse the last received value with new lines
		    line = last_received[0].replace(chr(13), '') #remove \r from the first parsed value in last_received and return me a nicely parsed value :) 
		    #print line;

		#####END part responsible for receiving on serial port    






		#####START of the state machine responsible for talking to the cellphone

		    if len(line) > 0: #if line not empty then it is a value the cellphone returned
		     #print 'I received:',line, len(line)
		     if firstCall==1:
		      #print 'I AM IN THE IF :)'
		      sleep(1)
		      callThisNumberFirst = 'ATD'+callThisNumberFirst+';\r'
		      ser.write(callThisNumberFirst)  #call the number from the argument 
		      line=''

		      #sleep(5)
		      #ser.write('AT+CSQ\r') #send the command for signal strength
		      #sleep(2)
		      ##sleep(5) #sleep 2 seconds       
		      #ser.write('AT+CHUP\r')
		      firstCall=0
		      firstCallSuccessful=1

		     if (line=='OK') and (firstCallSuccessful==1):
		      #print 'Successfully connected'
		      sleep(1)
		      ser.write('AT+CSQ\r') #send the command for signal strength
		      sleep(5)
		      #sleep(5) #sleep 2 seconds
		      sleep(1)
		      ser.write('AT+CHUP\r')
		      firstCallSuccessful=0
		      line = ''

		     if line=='RING':  #the cellphone is ringing and somebody is calling
		      if pickUp == 0:
		       sleep(1)
		       ser.write('ATA\r')  #pick up the phone call 
		       sleep(0.5)  #wait half a second before sending another AT command
		       sleep(1)
		       ser.write('AT+CSQ\r') #tell me the signal quality command
		       sleep(3)
		       sleep(1)
		       ser.write('AT+CHUP\r') #ask for the callers numbers
		       line=''
		       pickUp=1

		     if line[0:5] == '+CSQ:':
		      space = int(string.find(line,' '))+1  #find the   (space) sign
		      coma =  int(string.find(line,','))  #find the , (coma) sign
		      signalStrength = (int(line[space:coma])*2)-113
		      #print 'Signal strength', signalStrength, 'dBm'
		      line=''
		      if pickUp==1:
		       exitSuccessful = 1
		       return '|1|'+str(signalStrength)+'|'

		     if len(line) == 4:
                      if line == 'BUSY':
                       if callTrue == 1:
                        signalStr = '|0|Number was busy|'
                        return '|0|Number was busy|'

		#####END of the state machine responsible for talking to the cellphone
    except TimeoutException:
        return "|2|Timeout"
    finally:
        signal.signal(signal.SIGALRM, old_handler)

    signal.alarm(0)
    return signalStr

if __name__ == '__main__':
    result = serial_portFunc()
    print result