summaryrefslogtreecommitdiffstats
path: root/Controller/Controller-SecondType.py
blob: 10739a11e1188cef9ebb64620194cc9202eb55be (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import sys
import os
import re
import time
import MySQLdb
import subprocess
from time import sleep
from datetime import datetime


stop = "False"
status = ""
dbSStatus = ""

#db configuration

user = 'root'
passw = 'mysqlpassword'
host = 'localhost'
dbname = 'gsmselftesting'

global _from
global to



#function to ping
def FuncPing(ip):

 global status
 lifeline = re.compile(r"(\d) received")
 report = ("No response","Partial Response","Alive")

 A=1,2,3
 for host in A:
   
   pingaling = os.popen("ping -q -c2 "+ip,"r")

   while 1:
      line = pingaling.readline()
      if not line: break
      igot = re.findall(lifeline,line)
      if igot:
	       
	status= report[int(igot[0])]

# class for database
class DBMySQLConnection:
	def __init__(self, username, password, host, dbname):
		#initialize at the start all the user parameters
		self.usern = username
		self.passw = password
		self.host = host
		self.db = dbname
		self.connectionCreated = 0
		self.tasksList = list() 
		global debugMode
		debugMode = 0 

	def connectDB(self):
		try:
			#try the connection
			self.datBaseConn=MySQLdb.connect(self.host,self.usern, self.passw,self.db)
			self.datBaseConn.paramstyle = 'format'
			self.cur = self.datBaseConn.cursor() #make the cursor, used for sending queries
			self.connectionCreated = 1 #use it as an indicator that the connection was created
			return 1

		except MySQLdb.Error, e:
			#if we have an error then try to catch it
			error=str(e)
			if error[1:5] == '1045':
				#wrong username or password
				return 0
			elif error[1:5] == '2002':
				#can't connect to mysql, mysql shutdown or wrong host
				return 2
			else:
				if debugMode == 1:
					print error
				return 3

	def closeDBConn(self):
		#close the connection to the database here
		if self.connectionCreated == 1:
			try:
				#close the cursor and then the connection to the DB
				self.cur.close()
				self.datBaseConn.close()
				return 1
			except MySQLdb.Error, e:
				#in case of an error
				if debugMode == 1:
					error = str(e)
					print error
				return 3
		else:
			#I never really had a connection
			return 0
		
	def anyTasksToDo(self):
		#see are there any jobs to be executed and make a list out of it
		if self.connectionCreated == 1:
			try:	
				self.cur.execute("SELECT * FROM TempTaskTable")
				output = self.cur.fetchall() #get the mysql response
				#parse the output from the mysql by creating a list 
				#with lists where each attribue(column) gets independent
				#element of the list
                    		for record in output:
					columns = list()
                        		for entry in record:
                            			columns.append(str(entry))
					self.tasksList.append(columns)
                   		return 1
			except MySQLdb.Error, e:
				error = str(e)
				if error[1:5] == '1146':
					return 2 #the table doesn't exist
				if debugMode == 1:
					print str(e)
				return 3
		else:
				return 0 

	def cleanTasksList(self):
		if self.connectionCreated == 1:
			del self.tasksList[:] 
			return 1
		else:
			return 0

	def removeTaskFromList(self, taskID):
		#remove only one task from the task list
		if self.connectionCreated == 1:
			for index in range(len(self.tasksList)):
        			item = self.tasksList[index]
				if item[0] == str(taskID):
					#self.tasksList.remove(index)
					#print 'found it'
					del self.tasksList[index]
					return 1 #deleted taskID
		
			return 2 #didn't find that taskID
		else:
			return 0
			
	def deviceAddress(self,deviceName):
		if self.connectionCreated == 1:
			try:
				successful = self.cur.execute("SELECT `deviceIP` FROM DeviceAddress where `deviceName`=%s", deviceName)
				#self.cur.execute()
				output = self.cur.fetchall() #get the mysql response
				#parse the output from the mysql by creating a list 
				#with lists where each attribue(column) gets independent
				#element of the list
				deviceAddr = ''
                    		for record in output:
					columns = list()
                        		for entry in record:
                            			deviceAddr = str(entry)
                   		return deviceAddr
			except MySQLdb.Error, e:
				error = str(e)
				if error[1:5] == '1146':
					return 2 #the table doesn't exist
				if debugMode == 1:
					print str(e)
				return 3 #some error happened  
		else:
			return 0 #I am not connected

	def updateTaskResult(self, taskID, status):
		if self.connectionCreated == 1:
			try:
				successful = self.cur.execute("UPDATE TaskTable SET status=%i WHERE taskID=%i"%(int(status), int(taskID)))
				output = self.cur.fetchone()

				if debugMode == 1:
					print output
				if successful == 0:
					return 1 #update successful
				else:
					return 4 #taskID doesn't exist

			except MySQLdb.Error, e:
				if debugMode == 1:
					print str(e)
				return 3
		else:
			return 0

	def updatePingResult(self, taskNo, sipServer, sipGate, sipLoc, gsmBox1, gsmBox2):
		if self.connectionCreated == 1:
			try:
                                successful = self.cur.execute("UPDATE PingResultTable SET sipServer=%i, sipGate=%i, sipLoc=%i, gsmBox1=%i, gsmBox2=%i WHERE taskNo=%i"%(int(sipServer), int(sipGate), int(sipLoc), int(gsmBox1), int(gsmBox2), int(taskNo)))
                                output = self.cur.fetchone()
				
				if debugMode == 1:
                                	print output
				if successful == 0:
					return 1 #ping table updated
				else:
					return 4 #the taskNo didn't exist 

                                
                        except MySQLdb.Error, e:
				if debugMode == 1:
                                	print str(e)
                                return 3
		else:
			return 0
	
	def deleteTempTask(self, taskID):
		if self.connectionCreated == 1:
			try:
                                successful = self.cur.execute("DELETE FROM TempTaskTable WHERE taskID=%i"%(int(taskID)))
                                output = self.cur.fetchone()
				
				if debugMode == 1:
                                	print output

				if successful == 1:
					return 1 #deleted it
				else:
				  	return 4 #that taskID didn't exist or something else
                        except MySQLdb.Error, e:
				if debugMode == 1:
                                	print str(e)
                                return 3
			
		else:
			return 0

	def addResult(self, taskID, result):
		if self.connectionCreated == 1:
			try:
                                successful = self.cur.execute("INSERT INTO ResultTable(taskID, result) VALUES ('%i', '%i')"%(int(taskID), int(result)))
                                output = self.cur.fetchone()
				
				if debugMode == 1:
                                	print output
				if successful == 1:
					return 1 #successfully added the result
				else:
				  	return 4 #hmmm
                        except MySQLdb.Error, e:
				error = str(e)
				if error[1:5] == '1062':
					return 2 #duplicate entry for the key
				if debugMode == 1:
                                	print str(e)
                                return 3
		else:
			return 0

# class for socket connection

class Connection:
	def __init__(self, h, p):
		self.host = h
		self.port = p
		self.s = None
		self.connected = 0

	def connect(self):
		self.s = None
		
		for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
			af, socktype, proto, canonname, sa = res
		    	try:
		        	self.s = socket.socket(af, socktype, proto)
		    	except socket.error, msg:
		        	self.s = None
				self.connected = 0
		        	continue
		    	try:
		        	self.s.connect(sa)
		    	except socket.error, msg:
		        	self.s.close()
				self.connected = 0
		        	self.s = None
		        	continue
		    	break
		if self.s is None:
			self.connected = 0
			return '810 General socket layer error: Could not open socket'
		else: 
			self.connected = 1
			return '800 Socket connected'

	def send_data(self, data):
		if self.connected == 1:
			self.s.send(data)

	def receive_data(self):
		if self.connected == 1:
			return self.s.recv(1024)
		else:
			return '812 Socket is not connected.'

	def close_connection(self):
		if self.connected == 1:
			self.s.close()
			self.connected = 0
		return 'Closed'


# all Test case function

# One function for all test case

def FuncTest(orig, origadd, dest, destadd):

	global repeatTest
	repeatTest = ""
	
	#first make test from sip to gsm1 rz
	try:

		if dest =="Box1" or dest =="Box2":

			if dest =="Box1":
				y = Connection(destadd,50095)

			if dest =="Box2":
				y = Connection(destadd,50096)

			print "GSM handler", y.connect()
			y.send_data('hello server please wakeup the handler and be')
			sleep(1)
			y.send_data('caller')

		else:
			# open SIP caller handler
			command="--command=python " +orig
			subprocess.Popen(args=["gnome-terminal", command])

			sleep(5)
			if orig=="SIP":
				x = Connection(origadd,50097)

			if orig == "landline":
				x = Connection(origadd,50098)

			if orig == "LocalSIP":
				x = Connection(origadd,50099)

			else: #mean external GSM
				x = Connection(origadd,50100)
		
			print "handler", x.connect()
			x.send_data('hello Handler')
			
		# wait respond from handler
		while 1:
			origHandler = x.receive_data() 
			if origHandler <> "":
				break
			#think about time out		

		if origHandler == "ready":
			print "sip handler ready"
			try:
				if dest =="Box1" or dest =="Box2":
	
					if dest =="Box1":
						y = Connection(destadd,50101)

					if dest =="Box2":
						y = Connection(destadd,50102)

					print "GSM handler", y.connect()
					y.send_data('hello server please wakeup the handler and be')
					sleep(1)
					y.send_data('receiver')
					
				else:
					command="--command=python " +dest
					subprocess.Popen(args=["gnome-terminal", command])
		
					sleep(5)
		
					if orig=="SIP":
						x = Connection(origadd,50103)

					if orig == "landline":
						x = Connection(origadd,50104)

					if orig == "LocalSIP":
						x = Connection(origadd,50105)

					else: #mean external GSM
						x = Connection(origadd,50106)

					print "GSM handler", y.connect()
					y.send_data('hello Receiver, caller number')

				#wait respond from gsm handler
				while 1:
					destHandler = y.receive_data()
					if destHandler <> "":
						break
					#should have timeout = think about timeout

				if destHandler == "ready":
					
					x.send_data("start")#send message to handler to start the call
					sleep(2)
					x.send_data("destination number")
					#send destination number to sip caller and signal to start the call

					#wait respond from both of handler
					while 1:
						resultOrig = X.receive_data()
						resultDest = y.receive_data()

						if resultOrig <> "" or resultDest <> "":
							break

					#if failed, try one more time
					if resultOrig == "failed" or resultDest == "failed":
						y.send_data('hello Destination Handler')
						x.send_data("start + destination number")

						while 1:
							resultOrig = X.receive_data()
							resultDest = y.receive_data()

							if resultOrig <> "" or resultDest <> "":
								break
						
						#if still failed, save to db and update variable gsmRz2Sip == "1", so we make automatic test vice versa
						if resultOrig == "failed" or resultDest == "failed":
							db.execute ("update result table")
							repeatTest="true"

					else: #save to database, tell handler to terminated
						db.execute ("update result table")
						y.send_data("terminated") # signal GSM1 RZ to terminate

				else:
					statusTest = "604 General Handler Error: Destination handler no respond"
					#tell SIP handler to terminate
					x.send_data("terminated")
					
				y.close_connection()

			except ValueError:    
				print "601 General Handler Error: Could not open Destination handler"
		else:
			statusTest = "605 General Handler Error: Origin handler no respond"
		
		x.close_connection()
	
	except ValueError:    
		print "602 General Handler Error: Could not open Origin handler"

		

# Main software



# Check DB connection
x = DBMySQLConnection(user, passw, host, dbname)
print "connected to the DB ", x.connectDB()


if dbStatus = 1:
	
	FuncPing("132.230.4.8")
	sipServerStatus = status

	FuncPing("132.230.4.8")
	sipLocalStatus = status
	
	FuncPing("132.230.4.8")
	sipGateStatus = status

	FuncPing("132.230.4.8")
	btsBox1Status = status # it will be on building 101

	FuncPing("132.230.4.8")
	btsBox2Status = status # it will be on the building 52

# Fetch The task information from DB
	print "do i have anything to do", x.anyTasksToDo()	

	for item in x.tasksList:
		taskID = item[0]
		callFrom = item[1]
		callTo = item[2]
		print "call from to ", taskID , callFrom , callTo


		if callFrom == "sip" and sipServerStatus <> "No response":
			
			if callTo == "gsmrz":

				if btsBox1Status <> "No response":
					FuncTest("SIPCall.py", "localhost", "Box1", "132.0.0.2")
					if repeatTest == "true":
						#select table, if there are have test from gsmrz to sip then skip
						#else, update db, put new data to tasktable. from gsmrz to sip

				if btsBox2Status <> "No response":
					FuncTest("SIPCall.py", "localhost", "Box2", "132.0.0.3")
				
				FuncTest("SIPCall.py", "localhost", "RZ1Receiver.py", "132.0.0.1")

		if callFrom =="gsmrz":
			
			if callTo =="sip" and sipServerStatus <> "No response":

				if btsBox1Status <> "No response":
					FuncTest("Box1", "132.0.0.2", "SIPReceiver.py", "localhost")

				if btsBox2Status <> "No response":
					FuncTest("Box2", "132.0.0.3", "SIPReceiver.py", "localhost")
				
				FuncTest("rz1caller.py", "132.0.0.1", "SIPReceiver.py", "localhost")


# will exit if DB connection failed
else:
	sys.exit(5)