summaryrefslogblamecommitdiffstats
path: root/Under-Testing/Server-Code-New/GSMHandler.py
blob: 7cfcfb1486d3c420e3d6b6ca492ea870134e5b4e (plain) (tree)





















                                                     


                                                                                     







                                                 
                    















































                                                                               
                                                               




                                                                          
                                                                        



























































































































































                                                                                                                                                  
                          


                                                         




















































                                                             
                          




                                                              
























































                                                                                                                        
import ServerClass
import GSMClass
import LogFileClass
from time import sleep
import sys
import setproctitle
import csv
global sipServer, username, password, handler
global portListen
global portAddress
global nameOfLogFile

def initLogfile():
	global nameOfLogFile

	nameOfLogFile = str(handler)+' handler.log'

def openFile():
	global sipServer, username, password, handler
	global portListen
	global portAddress

	#String format: 'Account:username:password:server:handler:PortName:portCaller
	File = open('handler.txt')
	reader = csv.reader(File, delimiter=':')
	for row in reader:
     		if str(row[0]) == 'Account':
			#username = str(row[1])
			#password = str(row[2])
			#sipServer = str(row[3])
			handler = str(row[4])
			portAddress = str(row[5])
			portListen = int(row[6])
	File.close()
	

baudRate = 19200

#Taking account information
openFile()

#start Logging
initLogfile()
logger = LogFileClass.Logging(nameOfLogFile)
logger.logEvent('')

errorCount = 0

whileCounter =0

#define global varibales
global lastState
global resetState
global deviceError
lastState = 0
resetState = 0
deviceError = 0



def initSystem():

	
	global handlerSocket
	global gsmDevice
	global initTalkVar
	global lastState
	global initDevice
	global numberToCall
	global resetState
	global deviceError

	initTalkVar = 0 #variable used to know if we initialized the start talk
	lastState = 0 #variable used to know
	numberToCall = '000' #number to call 
	resetState = 0

	handlerSocket = ServerClass.ServerHandler(portListen)
	logger.logEvent('LISTEN ON PORT: '+str(portListen))
	anyConnection = handlerSocket.openSocket()

	try :
		logger.logEvent('Trying connect to the device')
		gsmDevice = GSMClass.serialPort(portAddress, baudRate, 15)
		initDevice = gsmDevice.portInit(5)
		logger.logEvent('init device ' + str(initDevice))

	except ValueError:
		logger.logEvent('Failure when trying connect to device')

	########################################################


	if initDevice!= 1:
		deviceError = 1
	else:
		deviceError = 0


	if anyConnection == 1 and initDevice == 1:
		logger.logEvent('CONNECTION ESTABLISHED AND DEVICE WORKING: ' + str(handlerSocket.connectedTo()))
		return 1

	elif anyConnection == 1 and initDevice != 1:
		logger.logEvent('$connection established but device not working: ' + str(handlerSocket.connectedTo()))
		resetState = 1
		return 2
	else:
		logger.logEvent('$no connection')
		logger.logEvent('$else case in init system' + str(anyConnection) + ' ' + str(initDevice) + ' ')
		resetState = 1
		
		return 0

	

def receiveMessage(timeout):

	message = str(handlerSocket.receiveData(timeout))
	print 'I RECEIVED THE FOLLOWING MESSAGE' + message
	if message == 'NO DATA':
		print 'try to close the connection' + str(handlerSocket.closeConnection())
		global resetState
		resetState = 1
		return 1
	if message != '0' and message !='NO DATA': 
		print 'in receive message', message, lastState	
	
		if message == 'HELLO HANDLER' and lastState == 0:
			outcome = initTalk()
			if outcome == 1:
				logger.logEvent('TALK INITIALIZATION SENT')
			else:
				logger.logEvent('$talk initialization not sent: ' + str(outcome))

		elif message == 'RECEIVER' and lastState == 1:
			outcome = initReceiver()
			if outcome == 1:
				logger.logEvent('RECEIVER READY SENT')
			else:
				logger.logEvent('$receiver ready not sent: ' + str(outcome))
			return 7

		elif message == 'RECEIVE START' and lastState == 2:
			outcome = receiveStart()
			print 'outcome ' + str(outcome)
			if outcome == 1:
				logger.logEvent('RECEIVE STATUS REPORTED')
				return 2
			else:
				logger.logEvent('$receive status not reported: ' + str(outcome))
				return 3

		elif message[0:6] == 'CALLER' and lastState == 1:
			outcome = initCaller() 

			global numberToCall
			numberToCall = message[7:]
			if outcome == 1:
				logger.logEvent('CALLER READY SENT')
			else:
				logger.logEvent('$caller ready not sent: ' + str(outcome))
			return 6
			
		elif message == 'CALL START' and lastState == 4:
			outcome = callStart(numberToCall)
			print 'outcome ' + str(outcome)
			if outcome == 1:
				logger.logEvent('CALLER STATUS SENT')
				return 4
			else:
				logger.logEvent('$caller status not sent: ' + str(outcome))
				return 5

		elif message == 'TERMINATE CONNECTION' and (lastState == 5 or lastState == 3):
			outcome = terminateConnection()
			if outcome == 1:
				logger.logEvent('TERMINATED THE CONNECTION AFTER TEST')
			else:
				logger.logEvent('$connection could not be terminated after the test: ' + str(outcome))
		
		elif message == 'TERMINATE CONNECTION':
			outcome = terminateConnection()
			if outcome == 1:
				logger.logEvent('TERMINATED THE CONNECTION IN MIDDLE. IN STATE: ' + str(lastState) )
			else:
				logger.logEvent('$connection could not be terminated in middle: ' + str(outcome) + ' in state: ' + str(lastState))
		else:
			print message
			outcome = other()
			logger.logEvent('other appeared')

	return 1
	#return 0

########INIT TALK PART########
def initTalk():
	print 'init talk'
	#initialize the talk between handler and controller
	global lastState
	test = gsmDevice.portInit(2)
	if test != 1:
		test = gsmDevice.portInit(2)
		if test != 1:
			sendMessage = handlerSocket.sendData('DEVICE NOT READY')
		else:
			lastState = 1
			sendMessage = handlerSocket.sendData('HELLO CONTROLLER')
	else:
		lastState = 1
		sendMessage = handlerSocket.sendData('HELLO CONTROLLER')
	return sendMessage
##############################


########RECEIVE PART########
def initReceiver():
	print 'initReceiver'

	#init function to initialize the receiver
	global lastState
	lastState = 2	
	sendMessage = handlerSocket.sendData('RECEIVER READY')
	return sendMessage

def receiveStart():
	print 'receiveStart'

	#wait for a call and report if you received it and it was successfull or not
	global lastState
	global deviceError
	lastState = 3
	if deviceError == 0:
		receiveCall = gsmDevice.receiveCall()
		if receiveCall == 'TIMEOUT':
			deviceError = 1
			print 'device error in RECEIVE'
	else:
		receiveCall = 0

	if deviceError == 0:
		if receiveCall == 1:
			callSuccess = 'CALL OK'
		else:
			callSuccess = 'CALL NOT OK'
	if deviceError==0:
		tryHangUp = gsmDevice.hangUp()	
	sendMessage = handlerSocket.sendData(callSuccess)

	return sendMessage
############################


########CALL PART########
def initCaller():
	print 'initCaller1'

	#initialize caller here
	global lastState
	lastState = 4
	sendMessage =  handlerSocket.sendData('CALLER READY')
	return sendMessage

def callStart(numberToCall):
	print 'initCaller2'
	
	#call the number here
	global lastState
	global deviceError
	lastState = 5

	callSuccess = 'CALL NOT OK'

	if deviceError==0:
		tryCall = gsmDevice.callNumber(numberToCall)
		if tryCall == 'TIMEOUT':
			deviceError = 1
			print 'device error in CALL'
	else:
		tryCall=0
	

	if tryCall != 1:
		callSuccess = 'CALL NOT OK'
	else:
	  print 'try call result'+ str(tryCall)
	  if tryCall != 'TIMEOUT':
		sleep(2)
		activeCall = gsmDevice.currentCall()
		counter = 0
		while(activeCall!=1):
			sleep(1)
			activeCall = gsmDevice.currentCall()
			if counter == 10:
				break
			counter += 1
		
		if activeCall == 1:
			callSuccess = 'CALL OK'
		else:
			callSuccess = 'CALL NOT OK'

	if deviceError==0:
		try:
			tryHangUp = gsmDevice.hangUp()
		except ValueError:
			print 'Error when try hangup the call'
	handResponse = handlerSocket.sendData(callSuccess)

	return handResponse
#########################


########TERMINATE PART########
def terminateConnection():
	print 'terminate connection'
	global resetState
	close = handlerSocket.closeConnection()
	resetState = 1
	sys.exit(0.5)
	return close
##############################

########TERMINATE PART########
def other():
	print 'other'
	global lastState
	global resetState
	
	close = handlerSocket.closeConnection()
	lastState = 8
	resetState = 1
	return 1
##############################

setproctitle.setproctitle('GSM Handler')

try:

	test = initSystem()
	if test == 1:
		print 'initialized system'
		receivedMessage = 0
		while receivedMessage < 8 and resetState!= 1:
			if receivedMessage == 4 or receivedMessage == 5 or receivedMessage == 2 or receivedMessage == 3:
				receivedMessage = receiveMessage(20)
			else:
				receivedMessage = receiveMessage(30)
	elif test ==2:
		print 'initialized system but device not working'
		logger.logEvent('initialized system but device not working')
		handlerSocket.sendData('DEVICE NOT READY')
		
	
	elif test ==0:
		print 'nobody can connect, reboot board, restart cellphone'
		logger.logEvent('nobody can connect, reboot board, restart cellphone')
	
	logger.closeLogging()
	del handlerSocket
	del gsmDevice
except ValueError:
	logger.logEvent('Could not start the handler')
	logger.closeLogging()