summaryrefslogtreecommitdiffstats
path: root/Handler/SIPIncoming.py
blob: 4c9d1bcfcf127d2034063fa97ab22f12c3d8ad94 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import sys
import pjsua as pj
import socket
import time
import os
import string

from time import sleep
from datetime import datetime


HOST = None
PORT = 50020
s = None

stop ="false"
server = "132.230.4.8"
username = "mpselftest2"
password = "2mpselftest"

LOG_LEVEL=2
current_call = None
success = ""
number = ""

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, "I am here"


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

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

    # Notification on incoming call
    def on_incoming_call(self, call):
        global current_call
	global number
        if current_call:
            call.answer(486, "Busy")
            return
            
        number = call.info().remote_uri

        current_call = call

        call_cb = MyCallCallback(current_call)
        current_call.set_callback(call_cb)

        current_call.answer(180)
	current_call.answer(200)
	print "accept call"
	sleep(5)
	current_call.hangup()

        
# 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
        
	if self.call.info().state_text == "CONNECTING":
		success = "true"
		server.sendData(success)

        if self.call.info().state == pj.CallState.DISCONNECTED:
            current_call = None
            print 'Current call is', current_call

    # Notification when call's media state has changed.
    def on_media_state(self):
        if self.call.info().media_state == pj.MediaState.ACTIVE:
            # Connect the call to sound device
            call_slot = self.call.info().conf_slot
            pj.Lib.instance().conf_connect(call_slot, 0)
            pj.Lib.instance().conf_connect(0, call_slot)
	    server.sendData('establish connection')

            print "Media is now active"


        else:
            print "Media is inactive"


        
lib = pj.Lib()

try:
	#open socket connection to the controller
	server = ServerHandler(50103)
	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()
	
	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"
    
    # Start the library
    	lib.start()
    	lib.set_null_snd_dev()


    # Create local account
    	acc_cfg = pj.AccountConfig(server, username, password)
    	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 that the handler ready

    		while stop <> "true":
			
			data = server.receiveData()#waiting message from controller
			if data == "terminated":
				break
	
			if current_call == None:
				continue
			else:
				print "Incoming call from :", number
				sleep(4)
        

    # Shutdown the library
    		transport = None
    		acc.delete()
    		acc = None
    		lib.destroy()
    		lib = None
		server.closeConnection()
		del server
	else:
		Regis_status= "Bad"
		print "error when register"

		lib.destroy()
		lib = None
    		acc = None
		server.closeConnection()
		del server

except pj.Error, e:
    print "Exception: " + str(e)
    lib.destroy()
    lib = None
    server.closeConnection()
    del server