summaryrefslogblamecommitdiffstats
path: root/Handler/SIPCall.py
blob: 8dca811fd42dd420fa841d6a0f9ad379375b2d62 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11










                             









                        


























































                                                                                                                                     
 






















                                                                                                                                 


































                                                                                         
                                                










                                                                     
                                                
























                                                               






                                                                                     










                                                                       

            
                                                                                        
                                                                         
                




                                                                                                      

                                                                                

                                    
                                                                                                                                     
                                        
                                                                                                                          


                                                        
                                                                                                               





                                                                                                  
                                                                                                                                  




                                                                          

                                                                
 

                                                









                                                   

                                                






                                            

                        


          
import sys
import pjsua as pj
import socket
import time
import MySQLdb
import subprocess
from time import sleep
from datetime import datetime
import string


stop ="false"
server = "132.230.4.8"
username = "mpselftest1"
password = "1mpselftest"

LOG_LEVEL=2
current_call = None
success = ""


class ServerHandler:
	
	def __init__(self,p):
		self.port = p 
		self.host = None #symbolic name meaning all available interfaces
		self.s = None
		self.connected = 0
		self.address = "127.0.0.1" #address of the main controller
		self.onceConnected = 0
		self.error = 'No error'

	def openSocket(self):
		self.error = 'No error'
		for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC,
                              socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
    			af, socktype, proto, canonname, sa = res

    			try:
        			self.s = socket.socket(af, socktype, proto)
				self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #this resolves the bug with live packets
    			except socket.error, msg:
        			self.s = None
				self.connected = 0
				self.error = str(msg)
        			continue

    			try:
        			self.s.bind(sa)
        			self.s.listen(1)
    			except socket.error, msg:
        			self.s.close()
        			self.s = None
				self.connected = 0
				self.error = str(msg)
        			continue
    			break

		if self.s is None:
			self.connected = 0
			return 0
    		else:	#accept the connection
			self.connection, self.address = self.s.accept()
			self.connected = 1
			self.onceConnected = 1
			return 1

	def connectedTo(self):
		return self.address

	def receiveData(self):
		if self.connected == 1:
			while 1:
    				data = self.connection.recv(1024)
				if not data:
					return 'NO DATA'
				else:
					return data
		else:
			return 0

	def sendData(self, data):
		if self.connected == 1:
    			self.connection.send(data)
			return 1
		else:
			return 0
		
	def closeConnection(self):
		if self.onceConnected == 1:
			self.connection.close()
			return 1
		else:
			return 0

	def killPort(self):
		killResult = os.popen('lsof -i tcp:' + str(self.port) + ' | grep "python " | awk -F" " ' + "'{print $2}'").read()
		killResult = killResult.replace('\n','')
		print killResult
		if killResult!='':
			print killResult
			killPort = os.popen("kill -9 " + killResult).read()
			return 1
		return 0

# Logging callback
def log_cb(level, str, len):
    print str, "SIP log"


# Callback to receive events from account
class MyAccountCallback(pj.AccountCallback):

    def __init__(self, account=None):
        pj.AccountCallback.__init__(self, account)

    # Notification on incoming call##


        
# Callback to receive events from Call
class MyCallCallback(pj.CallCallback):
   
    def __init__(self, call=None):
        pj.CallCallback.__init__(self, call)

    # Notification when call state has changed
    def on_state(self):
        global current_call
	global success

	if self.call.info().state_text <> "DISCONNCTD":
		if self.call.info().state_text == "CONNECTING":
			print "CONNECTING CALL"
			#print "isine opo:", self.call.info().state_text
			print "CALL CONFIRMED and ESTABLISH", self.call.info().state_text
			sleep(5)
			current_call.hangup()
			success = "true"
			server.sendData(success)
		else:
			sleep(1)
	#print ""

	if self.call.info().last_reason <> "":
		
		if self.call.info().last_reason == "Busy Here":
			
			print "Destination Number is Busy or offline"
			print ""
			success = "false"
			server.sendData(success)
			

		#print self.call.info().state_text
        
        if self.call.info().state == pj.CallState.DISCONNECTED:
            current_call = None
            print 'Current call Disconnected'


def make_call(uri):
    try:
        print "Making call to", uri
	cb=MyCallCallback()
        return acc.make_call(uri, cb)
    except pj.Error, e:
        print "Exception: " + str(e)
        return None
        



lib = pj.Lib()
while stop <> "true":


	lib.init(log_cfg = pj.LogConfig(level=LOG_LEVEL, callback=log_cb))
	transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))

	print "\nListening on", transport.info().host, 
	print "port", transport.info().port, "\n"
	lib.start()
	lib.set_null_snd_dev()	
	
	# open socket connection and connect to the controller
	server = ServerHandler(50097) 
	tried = server.openSocket()

	if server.error != 'No error':
		print server.error
		if server.error == '[Errno 98] Address already in use':
			print 'one should try to kill the port'
			print server.killPort()
			server.closeConection()

	try:
		acc_cfg = pj.AccountConfig("132.230.4.8","mpselftest1","1mpselftest")	
		acc = lib.create_account(acc_cfg, cb=MyAccountCallback())
		
			
		if acc.info().reg_status < 700:
			
			my_sip_uri = "sip:" + transport.info().host + ":" + str(transport.info().port)
			
			server.sendData('I am ready')#send message to controller
			print "here:", server.connected
			while 1:
				try:
					data = server.receiveData() # waiting mode, until receiver start message or terminate message
					
					if data == "start": # if receiver start message, handler start to call destination
						
						while 1:

							num = server.receiveData() # waiting destination number
							if num <> "":
								
								number = "sip:"+num+"@132.230.4.8"
								current_call = make_call(number)
								break

					if data == "terminated": # will terminate the handler if controller send terminate message
						stop = "true"
						break
	
				except ValueError:
					print "error when sending message"
					server.closeConnection()
					del server 

			server.closeConnection()
			del server 
					
		else:
			Regis_status= "Bad"
			print "error when register"

			lib.destroy()
			lib = None
    			acc = None


		server.closeConnection()	
		del server 
	except ValueError:    
		print "Exception: " + str(e)

print "Goodbye"
sleep(3)
acc.delete()
lib.destroy()
server.closeConnection()
del server 
lib = None
acc = None