summaryrefslogtreecommitdiffstats
path: root/Under-Testing/Server-Code-New
diff options
context:
space:
mode:
Diffstat (limited to 'Under-Testing/Server-Code-New')
-rw-r--r--Under-Testing/Server-Code-New/.DS_Storebin6148 -> 0 bytes
-rw-r--r--Under-Testing/Server-Code-New/._.DS_Storebin4096 -> 0 bytes
-rw-r--r--Under-Testing/Server-Code-New/._handler.txtbin4096 -> 0 bytes
-rw-r--r--Under-Testing/Server-Code-New/ClientClass.py123
-rw-r--r--Under-Testing/Server-Code-New/ControllerClass.py361
-rw-r--r--Under-Testing/Server-Code-New/DbClass.py445
-rw-r--r--Under-Testing/Server-Code-New/GSMClass.py310
-rw-r--r--Under-Testing/Server-Code-New/GSMHandler.py372
-rw-r--r--Under-Testing/Server-Code-New/LogFileClass.py21
-rw-r--r--Under-Testing/Server-Code-New/PingClass.py28
-rw-r--r--Under-Testing/Server-Code-New/READ ME.txt55
-rw-r--r--Under-Testing/Server-Code-New/SIPHandler.py272
-rw-r--r--Under-Testing/Server-Code-New/SSHTunnelBoxClass.py44
-rw-r--r--Under-Testing/Server-Code-New/ServerClass.py152
-rw-r--r--Under-Testing/Server-Code-New/WebsiteCommClass.py162
-rw-r--r--Under-Testing/Server-Code-New/gsmselftest.py795
-rw-r--r--Under-Testing/Server-Code-New/handler.txt1
-rw-r--r--Under-Testing/Server-Code-New/help.txt18
-rw-r--r--Under-Testing/Server-Code-New/initTestClass.py122
-rw-r--r--Under-Testing/Server-Code-New/startSoftware.py21
-rw-r--r--Under-Testing/Server-Code-New/truthtableClass.py233
-rw-r--r--Under-Testing/Server-Code-New/usbDetectClass.py96
22 files changed, 0 insertions, 3631 deletions
diff --git a/Under-Testing/Server-Code-New/.DS_Store b/Under-Testing/Server-Code-New/.DS_Store
deleted file mode 100644
index 5008ddf..0000000
--- a/Under-Testing/Server-Code-New/.DS_Store
+++ /dev/null
Binary files differ
diff --git a/Under-Testing/Server-Code-New/._.DS_Store b/Under-Testing/Server-Code-New/._.DS_Store
deleted file mode 100644
index 941570a..0000000
--- a/Under-Testing/Server-Code-New/._.DS_Store
+++ /dev/null
Binary files differ
diff --git a/Under-Testing/Server-Code-New/._handler.txt b/Under-Testing/Server-Code-New/._handler.txt
deleted file mode 100644
index a322a67..0000000
--- a/Under-Testing/Server-Code-New/._handler.txt
+++ /dev/null
Binary files differ
diff --git a/Under-Testing/Server-Code-New/ClientClass.py b/Under-Testing/Server-Code-New/ClientClass.py
deleted file mode 100644
index 46c3b00..0000000
--- a/Under-Testing/Server-Code-New/ClientClass.py
+++ /dev/null
@@ -1,123 +0,0 @@
-import socket
-import sys
-import os
-import string
-import signal
-
-class TimeoutException(Exception):
- pass
-
-class Connection:
- def __init__(self, h, p):
- self.host = h
- self.port = p
- self.s = None
- self.connected = 0
-
- self.debugMode = 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)
- 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
- 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 0 #couldn't connect to the server
- else:
- self.connected = 1
- return 1 #successfully connected to the server
-
- def sendData(self, data):
- if self.connected == 1:
- try:
- self.s.send(data)
- return 1
- except Exception, e:
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- self.connected = 0
- return 2
-
- else:
- return 0
-
- def receiveData(self, timeout):
- if self.connected == 1:
-
- def timeout_handler(signum, frame):
- raise TimeoutException()
-
- old_handler = signal.signal(signal.SIGALRM, timeout_handler)
- signal.alarm(timeout) #start the timeout alarm, for timeout seconds
- try:
- data = self.s.recv(1024)
-
- #stop the timeout function
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
-
- return data
-
-
- except TimeoutException:
- #timeout happened
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'TIMEOUT'
-
- except Exception, e:
-
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
-
- error = str(e)
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- self.connected = 0
- if error[0:11] == '[Errno 104]':
- return 3 #the other side reset the connection,[Errno 104] Connection reset by peer
-
- return 2
- else:
- return 0
-
- def closeConnection(self):
- if self.connected == 1:
- try:
- self.connected = 0
- SHUT_RDWR = 2
- self.s.shutdown(SHUT_RDWR)
- self.s.close()
- return 1
- except Exception, e:
- self.connected = 0
- error = str(e)
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- if error[0:11] == '[Errno 107]':
- return 3 #the other side closed the connection before us, [Errno 107] Transport endpoint is not connected
- return 2
- else:
- return 0
diff --git a/Under-Testing/Server-Code-New/ControllerClass.py b/Under-Testing/Server-Code-New/ControllerClass.py
deleted file mode 100644
index 4ed0d9d..0000000
--- a/Under-Testing/Server-Code-New/ControllerClass.py
+++ /dev/null
@@ -1,361 +0,0 @@
-import sys
-import os
-import subprocess
-import SSHTunnelBoxClass
-import ClientClass
-import random
-import csv
-
-import LogFileClass
-logger = LogFileClass.Logging('TestProcessLog.log')
-
-from time import sleep
-
-
-class controller:
-
- def __init__(self, callFrom, callPortName, accCaller, callTo, destPortName, destNo, accDest):
-
- self.callFrom = callFrom
- self.dest = callTo
- self.destNo = destNo
- self.accDest = accDest
- self.accCaller = accCaller
- self.callPortName = callPortName
- self.destPortName = destPortName
- self.portCaller = None
- self.portDest = None
- self.resultCaller = None
- self.resultDest = None
- self.testResult = None
-
- def FuncTest(self):
-
- logger.logEvent(' -- -X- --')
-
- self.initCaller()
-
- if self.callFrom =="GSMRZ3" or self.callFrom =="GSMRZ2": # wait until ssh connection establish
- if self.continues == 1:
- #putting 6 seconds sleep to prevent unsuccess login using SSH since we have problem with duration time loging into beagle board
- sleep(6)
- self.callerGreeting()
- else:
- self.connected = 'NOT OK'
- else:
- #waiting 2 seconds if doesnt use ssh connection until handler ready
- sleep(2)
- self.callerGreeting()
-
- logger.logEvent('Status Handler Connection :'+self.connected)
- if self.connected == 'OK':
-
- self.caller.sendData('CALLER|'+self.destNo)
- callerHandler = self.caller.receiveData(25)
- #waiting ready message from caller
-
- if callerHandler == "CALLER READY":
- logger.logEvent('Caller handler : Ready')
- self.initReceiver()
- if self.dest =="GSMRZ3" or self.dest =="GSMRZ2": # wait until ssh connection establish
- if self.continues == 1:
- #putting 6 seconds sleep to prevent unsuccess login using SSH since we have problem with duration time loging into beagle board
- sleep(6)
- self.receiverGreeting()
- else:
- self.connected = 'NOT OK'
- else:
- #waiting 2 seconds if doesnt use ssh connection until handler ready
- sleep(2)
- self.receiverGreeting()
-
- logger.logEvent('Status Handler Connection :'+self.connected)
- if self.connected == 'OK':
-
- self.receiver.sendData('RECEIVER')
- destHandler = self.receiver.receiveData(25)
- #waiting ready message from destination
-
- if destHandler == 'RECEIVER READY':
- logger.logEvent('Receiver handler : Ready')
- self.startCall()
- self.waitingFeedback()
-
- #Device destination having error after handler ready to receive call.
- elif destHandler == 'DEVICE NOT READY':
- self.testResult == 802
- logger.logEvent('802 General Device Error: Destination device no respond timeout')
- self.initTerminate()
- else:
- self.testResult = 604
- logger.logEvent('604 General Handler Error: Destination handler no respond timeout')
- self.initTerminate()
-
- #can connect to handler but device destination not ready to do the test.
- elif self.connected == 'DEVICE NOT READY':
- self.testResult = 802
- logger.logEvent('802 General Device Error: Destination device no respond timeout')
- self.initTerminate()
- else:
- logger.logEvent('998 General Handler Error: Could not connect Destination handler')
- self.testResult = 998
- self.caller.sendData('TERMINATE CONNECTION')
- self.caller.closeConnection()
- self.initCancelTest()
- else:
- self.testResult = 605
- logger.logEvent('605 General Handler Error: caller handler no respond timeout')
-
- self.caller.sendData('TERMINATE CONNECTION')
- self.caller.closeConnection()
-
- #can connect to handler but device caller not ready to do the test.
- elif self.connected == 'DEVICE NOT READY':
- self.testResult = 801
- self.caller.sendData('TERMINATE CONNECTION')
- self.caller.closeConnection()
- logger.logEvent('802 General Device Error: Caller device no respond timeout')
- self.initCancelTest()
- else:
- self.testResult = 999
- logger.logEvent('999 General Handler Error: Could not connect to Caller handler')
-
- def writeToFile(self, AccountInfo):
- try:
- with open('handler.txt', 'w') as F:
- writer = csv.writer(F)
- writer.writerow([AccountInfo])
- F.close()
- except ValueError:
- print "can't write to file"
-
- def initCancelTest(self):
- #close SSH connection when using gsmBox and destination doesnt respond. to make sure SSH connection are terminate
- logger.logEvent('init Cancel test')
- if self.callFrom[0:5] == 'GSMRZ':
- if self.callFrom != 'GSMRZ1':
- # close SSH tunneling
- self.boxCaller.killTunneling()
-
- # waiting results state
- def waitingFeedback(self):
- logger.logEvent('Waiting Feedback')
- self.resultDest = self.receiver.receiveData(20)
- self.resultCaller = self.caller.receiveData(20)
- #print 'result '+self.resultCaller+'--'+self.resultDest
- if self.resultCaller == 'DEVICE NOT READY':
- logger.logEvent('Task :'+self.callFrom+' - '+self.dest)
- logger.logEvent('Caller DEVICE NOT READY')
- self.testResult = 801
- self.initTerminate()
-
- elif self.dest == 'DEVICE NOT READY':
- logger.logEvent('Task :'+self.callFrom+' - '+self.dest)
- logger.logEvent('Caller DEVICE NOT READY')
- self.testResult = 802
- self.initTerminate()
-
- elif self.resultCaller == 'CALL OK' and self.resultDest =='CALL OK':
- logger.logEvent('Task :'+self.callFrom+' - '+self.dest)
- logger.logEvent('Test Succeed')
- self.testResult = 200
- self.initTerminate()
- else:
- #build specially only for Eplus card. since they use prepaid card.
- if self.dest == 'GSMExt.Eplus':
- if self.resultCaller == 'CALL OK' and self.resultDest <> 'TIME OUT':
- logger.logEvent('Task :'+self.callFrom+' - '+self.dest)
- logger.logEvent('Test Failed - Eplus No credit on Eplus')
- self.testResult = 402
- self.initTerminate()
- else:
- logger.logEvent('Test Failed')
- logger.logEvent('Task :'+self.callFrom+' - '+self.dest)
- self.testResult = 486
- self.initTerminate()
-
- else:
- #one or both of the handler send un success test. assign failed to this test
- if self.resultCaller <> 'CALL OK' or self.resultDest <> 'CALL OK':
- logger.logEvent('Task :'+self.callFrom+' - '+self.dest)
- logger.logEvent('Test Failed')
- self.testResult = 486
- self.initTerminate()
-
- #send start call message to caller
- def startCall(self):
- logger.logEvent('Start Call')
- self.receiver.sendData('RECEIVE START')
- self.caller.sendData('CALL START')
-
- def initAccount(self, account, handler, PortName, portCom):
-
- accConf = account
- self.username = accConf[0:accConf.find(':')]
-
- line = accConf[accConf.find(':')+1:]
- self.password = line[0:line.find(':')]
-
- newLine = line[line.find(':')+1:]
- self.server = newLine[0:newLine.find(':')]
-
- textFile = 'Account:'+str(self.username)+':'+str(self.password)+':'+str(self.server)+':'+str(handler)+':'+str(PortName)+':'+str(portCom)
- self.writeToFile(textFile)
-
- # define the caller configuration such as port name and port caller.
- def initCaller(self):
- logger.logEvent('init Caller')
- logger.logEvent(self.callFrom)
- self.portCaller = random.randint(30000,60000)
-
- if self.callFrom[0:4] == 'GSMR':
- if self.callFrom =="GSMRZ1":
- self.initAccount(self.accCaller,self.callFrom, self.callPortName,self.portCaller)
- self.initGSM(self.portCaller, self.callPortName, self.callFrom)
- else:
- self.initAccount(self.accCaller, self.callFrom, self.callPortName,self.portCaller)
- #open SSH tunneling
-
- self.boxCaller = SSHTunnelBoxClass.SSHTunneling(self.portCaller, 50008, self.server, self.username, self.password)
- status = self.boxCaller.startTunneling()
- logger.logEvent('SSH Status :'+str(status))
-
- #check whether the SSH tunneling succes or not, 0 is failed!
- if status!= 0:
- self.continues = 1
- else:
- self.continues = 0
- elif self.callFrom[0:4] == 'GSME':
- self.initAccount(self.accCaller,self.callFrom, self.callPortName,self.portCaller)
- self.initGSM(self.portCaller, self.callPortName, self.callFrom)
-
- else:
- #open the SIP handler
- self.initAccount(self.accCaller,self.callFrom, self.callPortName,self.portCaller)
- script = 'SIPHandler.py'
- subprocess.Popen(['python',script], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-
- # define the destination configuration such as port name and port caller.
- def initReceiver(self):
- logger.logEvent('init Receiver')
- logger.logEvent(self.dest)
- self.portDest = random.randint(30000,60000)
-
- if self.dest[0:4] == 'GSMR':
- if self.dest =="GSMRZ1":
- self.initAccount(self.accDest, self.dest, self.destPortName,self.portDest)
- self.initGSM(self.portDest, self.destPortName, self.dest)
- else:
- self.initAccount(self.accDest, self.dest, self.destPortName,self.portDest)
- #open SSH tunneling
-
- self.boxDest = SSHTunnelBoxClass.SSHTunneling(self.portDest, 50008, self.server, self.username, self.password)
- status = self.boxDest.startTunneling()
-
- #check whether the SSH tunneling succes or not, 0 is failed!
- logger.logEvent('SSH Status :'+str(status))
- if status!= 0:
- self.continues = 1
- else:
- self.continues = 0
-
- elif self.dest[0:4] == 'GSME':
- self.initAccount(self.accDest, self.dest, self.destPortName,self.portDest)
- self.initGSM(self.portDest, self.destPortName, self.dest)
-
- else:
- #self.portDest = 50100
- self.initAccount(self.accDest, self.dest, self.destPortName,self.portDest)
- script = 'SIPHandler.py'
- subprocess.Popen(['python',script], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-
- # send terminate message to Handlers
- def initTerminate(self):
- logger.logEvent('TERMINATE CONNECTION')
- self.caller.sendData('TERMINATE CONNECTION')
- self.receiver.sendData('TERMINATE CONNECTION')
-
- if self.callFrom[0:5] == 'GSMRZ':
- if self.callFrom != 'GSMRZ1':
- # close SSH tunneling
- self.boxCaller.killTunneling()
- if self.dest[0:5] == 'GSMRZ':
- if self.dest != 'GSMRZ1':
- # close SSH tunneling
- self.boxDest.killTunneling()
-
- #close port communication
- self.receiver.closeConnection()
- self.caller.closeConnection()
-
- def callerGreeting(self): # send greeting message to the caller handler
- logger.logEvent('Caller Greeting')
- self.connected = None
- #open connection to the Handler
- self.caller = ClientClass.Connection('localhost',self.portCaller)
- self.caller.connect()
-
- if self.caller.connected == 1:
- #connection establish and send hallo message to handler
- logger.logEvent('Connected to Caller Handler')
- self.caller.sendData('HELLO HANDLER')
- #waiting handler respond
- message = self.caller.receiveData(20)
-
- if message == 'HELLO CONTROLLER':
- # caller handler send hello message
- logger.logEvent('Caller Handler respond')
- self.connected = 'OK'
- elif message == 'DEVICE NOT READY':
- # the handler found the device not ready to making test.
- logger.logEvent('Connect to Caller but device doesnt work')
- self.connected = 'DEVICE NOT READY'
- else:
- logger.logEvent('Cannt connect to Caller')
- self.connected = 'NOT OK'
- else:
- #can't connect to caller handler
- logger.logEvent('Cannt connect to Caller')
- self.connected = 'NOT OK'
-
- def receiverGreeting(self): # send greeting message to the destination handler
- logger.logEvent('Receiver Greeting')
- self.connected = None
-
- #open connection to the Handler
- self.receiver = ClientClass.Connection('localhost', self.portDest)
- self.receiver.connect()
-
- if self.receiver.connected == 1:
- #connection establish and send hallo message to handler
- logger.logEvent('Connected to Receiver Handler')
- self.receiver.sendData('HELLO HANDLER')
- #waiting handler respond
- message = self.receiver.receiveData(20)
-
- # destination handler send hello message
- if message == 'HELLO CONTROLLER':
- logger.logEvent('Receiver Handler respond')
- self.connected = 'OK'
-
- # the handler found the device not ready to making test.
- elif message == 'DEVICE NOT READY':
- logger.logEvent('Connect to Caller but device doesnt work')
- self.connected = 'DEVICE NOT READY'
- else:
- logger.logEvent('receiver handler not respond')
- self.connected = 'NOT OK'
- else:
- #can't connect to destintaion handler
- logger.logEvent('Cannt connect to Receiver')
- self.connected = 'NOT OK'
-
- def initGSM(self, portCommunication, portDevice, handler):
- #open GSM Handler
- logger.logEvent('Init GSM')
- script = 'GSMHandler.py'
- subprocess.Popen(['python',script], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-
-
-
-
diff --git a/Under-Testing/Server-Code-New/DbClass.py b/Under-Testing/Server-Code-New/DbClass.py
deleted file mode 100644
index d937eb1..0000000
--- a/Under-Testing/Server-Code-New/DbClass.py
+++ /dev/null
@@ -1,445 +0,0 @@
-import MySQLdb
-import string
-
-class DBMySQLConnection:
- def __init__(self):
- #initialize at the start all the user parameters
- self.usern = "root"
- self.passw = ""
- self.host = "localhost"
- self.db = "gsmselftesting"
- self.connectionCreated = 0
- self.tasksList = list()
- self.callerLists = list()
- self.errCode = None
- self.deviceUpdate = None
- self.lockSet = 0
- global debugMode
- debugMode = 0
-
- def connectDB(self):
- try:
- #try to connect
- 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))
- #columns.append(str(0))
- self.tasksList.append(columns)
-
- if not self.tasksList:
- return 0
- else:
- 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 deviceAddress(self,deviceName):
- if self.connectionCreated == 1:
- try:
- successful = self.cur.execute("SELECT `portName`,`number`, `username`, `password`, `server` FROM DeviceAddressTable where `deviceName`=%s", deviceName)
- output = self.cur.fetchall()
- deviceAddr = ''
- for record in output:
- columns = list()
- for entry in record:
- columns.append(str(entry))
- deviceAddr = columns
-
- 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 deviceList(self): # taking all device list and put it in the list
- deviceLists = list()
- if self.connectionCreated == 1:
- try:
- tuple = self.cur.execute("SELECT `deviceName` FROM DeviceAddressTable")
- output = self.cur.fetchall()
-
- for record in output:
- columns = list()
- for entry in record:
- columns.append(str(entry))
- deviceLists.append(columns)
- return deviceLists
-
-#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:
- print 'not conn'
- return 0 #I am not connected
-
- def GSMPrefix(self):
- if self.connectionCreated == 1:
- try:
- successful = self.cur.execute("SELECT * FROM GSMPrefix")
- output = self.cur.fetchall() #get the mysql response
- GSMListPrefix = list()
- for record in output:
- columns = list()
- for entry in record:
- columns.append(str(entry))
- GSMListPrefix.append(columns)
-
- return GSMListPrefix
-
- 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 updateGSMDevice(self, deviceName, newPortName, newNumber):
- if self.connectionCreated == 1:
- try:
- try:
- #delete old device portName which assign to this port, to prevent double port address in the table.
- stmt = "UPDATE DeviceAddressTable SET portName = 'missing' WHERE portName = '"+newPortName+"'"
- self.cur.execute(stmt)
- except ValueError:
- print "Error execute query"
-
- stmt = "UPDATE DeviceAddressTable SET portName = '"+ newPortName + "', number = '"+ newNumber+ "' WHERE deviceName = '" + deviceName+ "'"
- self.cur.execute(stmt)
- return 1
-
- except MySQLdb.Error, e:
- if debugMode == 1:
- print str(e)
- return 3
- else:
- return 0
-
- def updatePingResult(self, taskNo, sipServer, sipGate, unisip, gsmBox1, gsmBox2):
- if self.connectionCreated == 1:
- try:
- successful = self.cur.execute("INSERT INTO PingResultTable(taskNo, sipServer, sipGate, unisip, gsmBox1, gsmBox2) VALUES ('%i', '%i','%i', '%i','%i','%i')"%( int(taskNo),int(sipServer), int(sipGate), int(unisip), int(gsmBox1), int(gsmBox2)))
-
- 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
-
-
- def errorCode(self,code):
- if self.connectionCreated == 1:
- try:
- successful = self.cur.execute("SELECT description FROM ErrorCodeTable where `respondCode`=%s", code)
- data = self.cur.fetchone()
- self.errCode = data[0]
- return self.errCode
-
- 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 lockMutex(self, seconds):
- if self.connectionCreated == 1:
- try:
- successful = self.cur.execute("SELECT IS_FREE_LOCK('SoftwareStarted')")
- output = self.cur.fetchone()
- if output[0] == 1:
- #resource is free which means software is not started yet
- successful = self.cur.execute("SELECT GET_LOCK('SoftwareStarted', %i)"%(int(seconds)))
-
- output1 = self.cur.fetchone()
- if output1[0] == 1:
- #I got the lock now
- self.lockSet = 1
- return 1
- elif output1[0] == 0:
- return 7 #if the attempt timed out (for example, because another client has previously locked the name)
- else:
- return 6 # if an error occurred (such as running out of memory or the thread was killed with
- elif output[0] ==0:
- return 4 #software is already running and somebody has allocated the mutex
- else:
- #means some not so good bug
- return 5 # if an error occurs (such as an incorrect argument).
- 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
-
- def maxTaskNo(self):
- if self.connectionCreated == 1:
- try:
- succ = self.cur.execute("SELECT max(taskNo) FROM TaskTable")
- taskNo = self.cur.fetchone()
- self.taskNo = taskNo[0]
- if self.taskNo == None or self.taskNo == '0' or self.taskNo == '' or self.taskNo == 0:
- self.taskNo = 1
- else:
- self.taskNo = int(self.taskNo) +1
- return self.taskNo
-
- except MySQLdb.Error, e:
- error = str(e)
- message = 'error'
- if debugMode == 1:
- print str(e)
- if error[1:5] == '1062':
- return message #duplicate entry for the key
-
- return message
- else:
- return 0
-
- def maxTaskID(self):
- if self.connectionCreated == 1:
- try:
- succ = self.cur.execute("SELECT max(taskID) FROM TaskTable")
- taskID = self.cur.fetchone()
- self.taskID = taskID[0]
- if self.taskID == None or self.taskID == '0' or self.taskID == '' or self.taskID == 0:
- self.taskID = 1
- return self.taskID
-
- except MySQLdb.Error, e:
- error = str(e)
- message = 'error'
- if debugMode == 1:
- print str(e)
- if error[1:5] == '1062':
- return message #duplicate entry for the key
-
- return message
- else:
- return 0
-
- def insertTask(self, taskNo, fromDevice, toDevice):
- if self.connectionCreated == 1:
- try:
- newQuery = ("INSERT INTO `TaskTable` (`taskNo`,`from`,`to`) VALUES ('"+str(taskNo)+"','" +str(fromDevice)+ "', '"+str(toDevice)+"')")
- successful = self.cur.execute(newQuery)
- output = self.cur.fetchone()
-
- return 1
-
- if debugMode == 1:
- print output
-
- except MySQLdb.Error, e:
- error = str(e)
- if debugMode == 1:
- print str(e)
- if error[1:5] == '1062':
- return 2 #duplicate entry for the key
- return 3
- else:
- return 0
- def insertTaskIn2(self, fromDevice, toDevice, taskNo):
- if self.connectionCreated == 1:
- try:
- #we used here a transaction since I want the mysql to execute a few commands and tell me was it successful rather than to execute some and there happens a mistake and one part is updated and the other isn't
- newQuery = "START TRANSACTION; INSERT INTO `TaskTable` (`taskNo`, `from`, `to`) VALUES ('" + str(taskNo) + "', '" + str(fromDevice) + "', '" + str(toDevice) +"'); SELECT @taskID := LAST_INSERT_ID(); INSERT INTO `TempTaskTable` (`taskID`, `taskNo`, `from`, `to`) VALUES (@taskID, '" + str(taskNo) + "', '" + str(fromDevice) + "', '"+ str(toDevice) + "'); COMMIT;"
-
- successful = self.cur.execute(newQuery)
- output = self.cur.fetchone()
- while self.cur.nextset() is not None: pass
-
- return 1
-
- if debugMode == 1:
- print output
-
- except MySQLdb.Error, e:
- error = str(e)
- if debugMode == 1:
- print str(e)
- if error[1:5] == '1062':
- return 2 #duplicate entry for the key
- return 3
- else:
- return 0
- def releaseMutex(self):
- if self.connectionCreated == 1:
- try:
- if self.lockSet == 1:
- successful = self.cur.execute("SELECT IS_FREE_LOCK('SoftwareStarted')")
- output = self.cur.fetchone()
- if output[0] == 1:
- #the lock seems to be free
- self.lockSet = 0
- return 4
-
- elif output[0] == 0:
-
- #try to release the lock
- successful = self.cur.execute("SELECT RELEASE_LOCK('SoftwareStarted')")
- output1 = self.cur.fetchone()
- self.lockSet = 0
- if output1[0] == 1:
- #the lock was released successfully
- return 1
-
- elif output1[0] == 0:
- # if the lock was not established by this thread (in which case the lock is not released)
- return 5
- else:
- # and NULL if the named lock did not exist. The lock does not exist if it was never obtained by a call to GET_LOCK() or if it has previously been released.
- return 6
- else:
- #some serious problem
- #and NULL if an error occurs (such as an incorrect argument).
- return 5
-
- else:
- return 7 #the lock wasn't set
-
- 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
-
-
diff --git a/Under-Testing/Server-Code-New/GSMClass.py b/Under-Testing/Server-Code-New/GSMClass.py
deleted file mode 100644
index b932ab5..0000000
--- a/Under-Testing/Server-Code-New/GSMClass.py
+++ /dev/null
@@ -1,310 +0,0 @@
-from serial import * #serial port library
-import string
-import sys
-import signal
-
-class TimeoutException(Exception):
- pass
-
-class serialPort():
-
- def __init__(self, portAddress, baudRate, timeout):
- self.portAddress = portAddress
- self.portExist = 0
- self.ser = 0
- self.baudRate = baudRate
- self.signalStrength = 0
- #self.callerConnected = -1
- self.timer = timeout
- self.timer1 = timeout
- self.start = 0
-
- self.debugMode = 0
-
- def portInit(self, timeout1):
- portName = self.portAddress[-4:]
- portExist = os.popen('dmesg | grep ' + portName).read()
- self.timer = timeout1
- if portExist == '':
- return 0
- else:
- try:
- self.ser = Serial(
- port=self.portAddress,
- baudrate=self.baudRate,
- 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 :)
- )
- self.ser.flushOutput() #clean the output buffer from the serial port
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('AT\r')
-
- received = self.__receiveData()
- self.start=1
- if received == 'OK':
- self.portExist = 1
- return 1 #cellphone is OK, receives commands
- elif received == 'TIMEOUT':
- return 'TIMEOUT'
- else:
- return 2 #cellphone has an error
-
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
-
- self.portExist = 3
- return 3
-
- def callNumber(self,numberToCall):
- if self.portExist == 1:
- try:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('ATD'+str(numberToCall)+';\r')
- if self.__receiveData() == 'OK':
- return 1
- else:
- return 4
-
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
-
- return 3
- else:
- return 0
-
-
- def hangUp(self):
- if self.portExist == 1:
- try:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('AT+CHUP\r')
- received = self.__receiveData()
- if received == 'OK':
- return 1
- elif received == 'ERROR':
- return 2 #other side hang up the call
- else:
- return 4
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
- return 3
- else:
- return 0
-
-
- def closePort(self):
- if self.portExist == 1:
- try:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.close()
- return 1
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
- return 3
- else:
- return 0
-
- def getSignalQuality(self):
- if self.portExist == 1:
- try:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('AT+CSQ\r')
- if self.__receiveData() == 'OK':
- if self.__receiveData == 'SIGNAL':
- return 1
- else:
- return 4
- else:
- return 2
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
- return 3
-
- else:
- return 0
-
- def receiveCall(self):
- if self.portExist == 1:
- try:
- self.ser.flushInput() #clean the input buffer for serial port
- if self.__receiveData() == 'RING':
- self.ser.write('ATA\r')
- if self.__receiveData()=='OK':
- return 1
- else:
- return 4
- else:
- return 2
-
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
- return 3
- else:
- return 0
-
- def currentCall(self):
- if self.portExist == 1:
- try:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('AT+CLCC\r')
- received = self.__receiveData()
- if received == 'OK':
- return 2 #not yet in a call
- elif received == 'ACTIVE':
- return 1 #in a call
- elif received == 'HELD':
- return 5 #held call
- elif received == 'DIALING':
- return 6 #dialing
- elif received == 'ALERTING':
- return 7 #alerting the call
- elif received == 'INCOMING':
- return 8 #incoming call
- elif received == 'WAITING':
- return 9 #waiting for a call
-
- else:
- return received #in some other state
- except Exception, e:
- import traceback
- if self.debugMode == 1:
- print e
- print traceback.format_exc()
- return 3
- else:
- return 0
-
- def __receiveData(self):
- def timeout_handler(signum, frame):
- raise TimeoutException()
- if self.start == 0:
- self.timer = 5
- else:
- self.timer = self.timer1
-
- old_handler = signal.signal(signal.SIGALRM, timeout_handler)
- signal.alarm(self.timer)
-
- bufferData = ''
- lines = ''
- line = ''
-
- try:
- while True:
- bufferData = bufferData + self.ser.read(self.ser.inWaiting()) #read the serial port and add it to the buffer variable
- if '\n' in bufferData: #if a new line character is found in the buffer then the cellphone has sent something
- lines = bufferData.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)
-
- bufferData = '\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 :)
- if self.debugMode == 1:
- if len(line) > 0:
- print line
-
- if line == 'OK':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'OK'
-
- elif line == 'ERROR':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'ERROR'
-
- elif line[0:11] == '+CME ERROR:':
- if self.debugMode == 1:
- print 'ERROR:', line
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'ERROR'
-
- elif line == 'RING':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'RING'
-
- elif line[0:5] == '+CSQ:': #+CSQ:
- space = int(string.find(line,' '))+1 #find the (space) sign
- coma = int(string.find(line,',')) #find the , (coma) sign
- self.signalStrength = (int(line[space:coma])*2)-113
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'SIGNAL'
-
- elif line == 'NO CARRIER':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'NO CARRIER'
-
- elif line == 'BUSY':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'BUSY'
-
- elif line[0:6] == '+CLCC:':
- #+CLCC: 1,0,
- #self.ser.flushInput()
- if line[11:12] == '0':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'ACTIVE'
- elif line[11:12] == '1':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'HELD'
- elif line[11:12] == '2':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'DIALING'
- elif line[11:12] == '3':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'ALERTING'
- elif line[11:12] == '4':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'INCOMING'
- elif line[11:12] == '5':
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'WAITING'
-
- except TimeoutException:
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'TIMEOUT'
-
- except Exception, e:
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- print 'NO GOOD'
- print e
- return 3
diff --git a/Under-Testing/Server-Code-New/GSMHandler.py b/Under-Testing/Server-Code-New/GSMHandler.py
deleted file mode 100644
index 1379fe9..0000000
--- a/Under-Testing/Server-Code-New/GSMHandler.py
+++ /dev/null
@@ -1,372 +0,0 @@
-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 writeToFile():
- try:
- string = '--'
- with open('handler.txt', 'w') as F:
- writer = csv.writer(F)
- writer.writerow([string])
- F.close()
- except ValueError:
- print "can't write to file"
-
-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':
- handler = str(row[4])
- portAddress = str(row[5])
- portListen = int(row[6])
- File.close()
- writeToFile()
-
-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()
-
diff --git a/Under-Testing/Server-Code-New/LogFileClass.py b/Under-Testing/Server-Code-New/LogFileClass.py
deleted file mode 100644
index cb152f4..0000000
--- a/Under-Testing/Server-Code-New/LogFileClass.py
+++ /dev/null
@@ -1,21 +0,0 @@
-import string
-import datetime
-
-class Logging:
-
- def __init__(self, logFileName):
- self.writeToFile = open(logFileName, 'a')
- self.justStarted = 1
-
- def logEvent(self, event):
- now = str(datetime.datetime.now())
- if self.justStarted == 1:
- self.writeToFile.write('\n\n------------------STARTED THE LOGGING '+ now + ' ------------------\n')
- self.justStarted = 0
- else:
- self.writeToFile.write('On: '+ now + '\t' + 'Event: ' +str(event) + '\n')
-
- def closeLogging(self):
- now = str(datetime.datetime.now())
- self.writeToFile.write('------------------FINISHED THE LOGGING '+ now + ' ------------------')
- self.writeToFile.close()
diff --git a/Under-Testing/Server-Code-New/PingClass.py b/Under-Testing/Server-Code-New/PingClass.py
deleted file mode 100644
index e13b32b..0000000
--- a/Under-Testing/Server-Code-New/PingClass.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import subprocess
-import string
-
-class Ping:
-
- def __init__(self, pingAddress):
- self.pingAddress = pingAddress
-
- def ping(self,numberTries):
- tried = 1
- while numberTries >= tried:
- tried += 1
- #the parameter c 1 means only one ping to be sent, parameter W 3 means how many seconds the time out should be, 3 seconds
- ping_cmd = subprocess.Popen(['ping', self.pingAddress, '-c', '1', '-W', '2'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
-
- pingAlive = int(string.find(ping_cmd, '1 received'))
- unknownHost = int(string.find(ping_cmd, 'unknown host'))
-
-
- if pingAlive != -1:
- break
-
- if unknownHost != -1:
- return 2 #unknown host
- if pingAlive != -1:
- return 1 #ping works fine
- else:
- return 0 #no ping response
diff --git a/Under-Testing/Server-Code-New/READ ME.txt b/Under-Testing/Server-Code-New/READ ME.txt
deleted file mode 100644
index 0e2ff54..0000000
--- a/Under-Testing/Server-Code-New/READ ME.txt
+++ /dev/null
@@ -1,55 +0,0 @@
-
-Class files:
-
- - ClientClass.py
- This class file is used by the controller as socket communication class to communicate with the Handlers.
-
- - ServerClass.py
- This class file is used by handlers as socket communication class to communicate with the controller.
-
- - GSMClass.py
- This class file is used by GSM Handlers to control and talk to the mobile devices.
-
- - PingClass.py
- This class file is used to ping GSMBoxes and servers in the system.
-
- - truthtableClass.py
- This class file is used by the controller to find out how many nanoBTS's are installed in the University tecommunication network and it finds out the working (or not working) state of the University telecommunication network.
-
- - ControllerClass.py
- This class file is used by the software to assign the tasks and start the handlers.
-
- - initTestClass.py
- This class is used by the software to parse information from database class and to send the right device information to the controller class.
-
- - SSHTunnelBoxClass.py
- This class is used by the software to communicate with the GSMBoxes (using SSH tunnel port forwarding).
-
- - usbDetectClass.py
- This class is used to identify the right mobile device, port address and phone number.
-
- - DbClass.py
- This class is used to fetch information from the database.
-
- - LogFileClass.py
- This class is used to make the log files.
-
- - WebsiteCommClass.py
- This class is used by the controller to communicate with the Website.
-
-Handler files:
-
- - GSMHandler.py
- - SIPHandler.py
-
-Main Software:
-
- - startSoftware.py
- This script file should be run manually after you login on the server machine. This script file is used to receive the message from the website and then it tries to start the controller software (main test software).
-
- - gsmselftest.py
- This is the main software which is controlling the handlers, it also assigns tasks for the tests.
-
-Help file:
- - help.txt
- That file is used to find out more information about how to use the software manually using the terminal.
diff --git a/Under-Testing/Server-Code-New/SIPHandler.py b/Under-Testing/Server-Code-New/SIPHandler.py
deleted file mode 100644
index eb5302c..0000000
--- a/Under-Testing/Server-Code-New/SIPHandler.py
+++ /dev/null
@@ -1,272 +0,0 @@
-import sys
-import string
-import pjsua as pj
-import ServerClass
-import LogFileClass
-import setproctitle
-from time import sleep
-import csv
-
-def log_cb(level, str, len):
-
- print ""
-
-# Receive events from incoming Call
-class Account(pj.AccountCallback):
-
- def __init__(self, account=None):
- pj.AccountCallback.__init__(self, account)
-
- def on_incoming_call(self, call):
- global current_call
-
- #print 'Incoming Call'
- current_call = call
- call_cb = Calling(current_call)
- current_call.set_callback(call_cb)
-
- logger.logEvent('Incoming Call')
-
- call.answer(200)
-
- sleep(2)
-
- logger.logEvent('CALL OK')
-
-#creating object for calling
-class Calling(pj.CallCallback):
-
- def __init__(self, call=None):
- pj.CallCallback.__init__(self, call)
-
- def on_state(self):
- global current_call
-
- if self.call.info().state <> pj.CallState.DISCONNECTED:
- if self.call.info().state_text == "CONNECTING":
- logger.logEvent("Call Connecting")
- try:
- logger.logEvent('Try to hangup the call')
- self.call.hangup()
- logger.logEvent('Hangup OK')
- except ValueError:
- logger.logEvent('hangup failed, waiting destination hangup the call')
-
- server.sendData('CALL OK')
-
- if self.call.info().last_reason == "Busy Here":
- logger.logEvent('Number busy or Offline')
- server.sendData('CALL NOT OK')
- logger.logEvent('CALL NOT OK')
-
- if self.call.info().state == pj.CallState.DISCONNECTED:
- logger.logEvent('Call Disconnected')
- current_call = None
-
-#function to make a call
-def make_call(uri):
-
- try:
- cb=Calling()
- return acc.make_call(uri, cb)
-
- except pj.Error, e:
- logger.logEvent('Error when trying to call, 408')
- server.sendData('CALL NOT OK')
- return None
-
-def writeToFile():
- try:
- string = '--'
- with open('handler.txt', 'w') as F:
- writer = csv.writer(F)
- writer.writerow([string])
- F.close()
- except ValueError:
- print "can't write to file"
-
-def openFile():
- global sipServer, username, password, ip, portadd
- global port
-
- #file format: 'Account:username:password:server:handler:PortName:portCommunication
- 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])
- port = int(row[6])
- File.close()
- writeToFile()
-
-#send greeting message to the controller
-def greeting():
-
- global server
- server = None
-
- # create socket communication object
- server = ServerClass.ServerHandler(port)
- logger.logEvent('try to Connect to Controller')
- conn = server.openSocket()
-
- if server.connected == 1:
- #connection to the controller establish
- logger.logEvent('Connection Establish')
- if server.receiveData(25) == 'HELLO HANDLER':
- server.sendData('HELLO CONTROLLER')
- return 1
- else:
- logger.logEvent('Cant connect to Controller')
- del server
- return 0
-
-def initLogFile(sipServer):
-
- global logger
-
- if sipServer == '132.230.4.8':
- nameOfLogFile = 'SIP handler.log'
- #print '--SIP Asterisk--'
-
- elif sipServer == 'sipgate.de':
- nameOfLogFile = 'Landline handler.log'
- #print '--Landline--'
-
- elif sipServer == '132.230.252.228':
- nameOfLogFile = 'University SIP handler.log'
- #print '--university tephone network--'
-
- logger = LogFileClass.Logging(nameOfLogFile)
-
-def initState():
- global message
- global state
- global num
-
- logger.logEvent('init state')
- message = server.receiveData(30)
-
- if message == 'RECEIVER':
- state = 'RECEIVER'
-
- elif message[0:6] == 'CALLER':
- state = 'CALLER'
- no = message[7:]
-
- # need special handle for calling from unisip account
- if sipServer == '132.230.252.228':
- num = no[7:]
- else:
- num = no
-
-lib = pj.Lib()
-stop = False
-
-print 'INIT SYSTEM'
-
-openFile()
-setproctitle.setproctitle('SIP Handler')
-initLogFile(sipServer)
-
-logger.logEvent('')
-
-while stop <> True:
-
- acc_cfg = None
-
- lib.init(log_cfg = pj.LogConfig(level=1, callback=log_cb))
- transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
-
- lib.start()
- lib.set_null_snd_dev()
-
- if greeting() != 1:
- lib.destroy()
- break
- try:
- initState()
- acc_cfg = pj.AccountConfig(str(sipServer),str(username),str(password))
- logger.logEvent('Register Account to SIP server')
- acc = lib.create_account(acc_cfg, cb=Account())
-
- if acc.info().reg_status < 700:
-
- # being receiver state
- if state =='RECEIVER':
- logger.logEvent(acc.info().reg_status)
- server.sendData('RECEIVER READY')
- logger.logEvent('Receiver Handler Ready')
-
- #waiting state
- while 1:
-
- data = server.receiveData(1)
- if data == 'RECEIVE START':
- print data
- logger.logEvent(data)
-
- #get shutting down message
- if data == 'TERMINATE CONNECTION':
- print data
- logger.logEvent('Terminate')
- stop = True
- break
- #being caller state
- elif state =='CALLER':
- logger.logEvent(acc.info().reg_status)
- server.sendData('CALLER READY')
- logger.logEvent('Caller Handler Ready')
-
- while 1:
- data = server.receiveData(1)
-
- #start the call
- if data == 'CALL START':
- #print data
- if num <> '':
- sleep(3)
- logger.logEvent(data)
- logger.logEvent('Make a call to: ' + num)
- number = "sip:"+num+"@"+sipServer
- make_call(number)
- else:
- logger.logEvent('No number to call')
- logger.logEvent('CALL NOT OK')
-
- #shutting down message
- if data == 'TERMINATE CONNECTION':
- #print data
- stop = True
- logger.logEvent('Terminate')
- break
-
- else:
- logger.logEvent('Unknow Message')
- server.sendData('Unknow Message')
- break
-
- else:
- logger.logEvent("488 Not Acceptable Here")
- server.sendData('DEVICE NOT READY')
- break
-
- except ValueError:
- logger.logEvent("401 Unauthorized ")
- break
-
-logger.logEvent("Goodbye")
-logger.closeLogging()
-# trying to clean everything before shutting down
-try:
- acc.delete()
- lib.destroy()
- lib = None
- acc = None
- server.closeConnection()
- del server
-except ValueError:
- message = 'trying failure'
-
diff --git a/Under-Testing/Server-Code-New/SSHTunnelBoxClass.py b/Under-Testing/Server-Code-New/SSHTunnelBoxClass.py
deleted file mode 100644
index 1b76d0b..0000000
--- a/Under-Testing/Server-Code-New/SSHTunnelBoxClass.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#Here is a tutorial how to generate and copy your RSA SSH public key :)
-#>>> http://www.thegeekstuff.com/2008/11/3-steps-to-perform-ssh-login-without-password-using-ssh-keygen-ssh-copy-id/
-import subprocess
-from time import sleep
-
-class SSHTunneling:
-
- def __init__(self, localPort, remotePort, remoteServer, username, password):
- self.lPort = localPort
- self.rPort = remotePort
- self.rServer = remoteServer
-
- self.usern = username
- self.passw = password
-
- self.__tunnelStarted = 0
- self.__sshTunnel = 1
-
- def startTunneling(self):
- if self.__tunnelStarted == 0:
- command = str(self.lPort) + ':' + self.rServer + ':' + str(self.rPort)
- uad = self.usern + '@' + self.rServer
-
- try:
- self.__sshTunnel = subprocess.Popen(['ssh','-p','7884','-N', '-L', command, uad], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- sleep(2)
- self.__tunnelStarted = 1
- return 1
- except Exception, e:
- error = str(e)
- return 0
-
- def killTunneling(self):
- if self.__tunnelStarted == 1:
- try:
- self.__sshTunnel.kill()
- self.__tunnelStarted = 0
- return 1
-
- except Exception, e:
- error = str(e)
- return 0
-
-
diff --git a/Under-Testing/Server-Code-New/ServerClass.py b/Under-Testing/Server-Code-New/ServerClass.py
deleted file mode 100644
index 93c2f8e..0000000
--- a/Under-Testing/Server-Code-New/ServerClass.py
+++ /dev/null
@@ -1,152 +0,0 @@
-import socket
-import sys
-import os
-import string
-import signal
-
-class TimeoutException(Exception):
- pass
-
-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'
-
- self.debugMode = 0
-
- 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, timeout):
- if self.connected == 1:
-
- def timeout_handler(signum, frame):
- raise TimeoutException()
-
- try:
-
- old_handler = signal.signal(signal.SIGALRM, timeout_handler)
- signal.alarm(timeout) #start the timeout alarm, for timeout seconds
-
- data = self.connection.recv(1024)
-
- #stop the timeout function
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
-
- if not data:
- self.connected = 0
- return 'NO DATA'
- else:
- return data
-
- except TimeoutException:
- #timeout happened
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'TIMEOUT'
-
- except Exception, e:
- #stop the timeout timer
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
-
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- self.connected = 0
- if error[0:11] == '[Errno 104]':
- return 3 #the other side reset the connection,[Errno 104] Connection reset by peer
-
- return 2
- else:
- return 0
-
- def sendData(self, data):
- if self.connected == 1:
- try:
- self.connection.send(data)
- return 1
-
- except Exception, e:
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- self.connecected = 0
- return 2
- else:
- return 0
-
- def closeConnection(self):
- if self.onceConnected == 1:
- try:
- self.connected = 0
- SHUT_RDWR = 2
- self.connection.shutdown(SHUT_RDWR)
- self.connection.close()
- return 1
- except Exception, e:
- self.connected = 0
- error = str(e)
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- if error[0:11] == '[Errno 107]':
- return 3 #the other side closed the connection before us [Errno 107] Transport endpoint is not connected
- return 2
- 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
diff --git a/Under-Testing/Server-Code-New/WebsiteCommClass.py b/Under-Testing/Server-Code-New/WebsiteCommClass.py
deleted file mode 100644
index 206411e..0000000
--- a/Under-Testing/Server-Code-New/WebsiteCommClass.py
+++ /dev/null
@@ -1,162 +0,0 @@
-import socket
-import sys
-import os
-import string
-import signal
-
-class TimeoutException(Exception):
- pass
-
-class ServerHandlerSoftware:
-
- 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'
-
- self.debugMode = 0
-
- def openSocket(self, timeoutVar):
- 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
- self.s.settimeout(timeoutVar)
-
- 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
- try:
- self.connection, self.address = self.s.accept()
- self.s.settimeout(0)
- self.connected = 1
- self.onceConnected = 1
- return 1
- except socket.timeout:
- return 'TIMEOUT'
-
- def connectedTo(self):
- return self.address
-
- def receiveData(self, timeout):
- if self.connected == 1:
-
- def timeout_handler(signum, frame):
- raise TimeoutException()
-
- try:
-
- old_handler = signal.signal(signal.SIGALRM, timeout_handler)
- signal.alarm(timeout) #start the timeout alarm, for timeout seconds
-
- data = self.connection.recv(1024)
-
- #stop the timeout function
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
-
- if not data:
- self.connected = 0
- return 'NO DATA'
- else:
- return data
-
- except TimeoutException:
- #timeout happened
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- return 'TIMEOUT'
-
- except Exception, e:
- #stop the timeout timer
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
-
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- self.connected = 0
- if error[0:11] == '[Errno 104]':
- return 3 #the other side reset the connection,[Errno 104] Connection reset by peer
-
- return 2
- else:
- return 0
-
- def sendData(self, data):
- if self.connected == 1:
- try:
- self.connection.send(data)
- return 1
-
- except Exception, e:
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- self.connecected = 0
- return 2
- else:
- return 0
-
- def closeConnection(self):
- if self.onceConnected == 1:
- try:
- self.connected = 0
- SHUT_RDWR = 2
- self.connection.shutdown(SHUT_RDWR)
- self.connection.close()
- return 1
- except Exception, e:
- self.connected = 0
- error = str(e)
- if self.debugMode == 1:
- import traceback
- print traceback.format_exc()
- print e
- if error[0:11] == '[Errno 107]':
- return 3 #the other side closed the connection before us [Errno 107] Transport endpoint is not connected
- return 2
- 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
diff --git a/Under-Testing/Server-Code-New/gsmselftest.py b/Under-Testing/Server-Code-New/gsmselftest.py
deleted file mode 100644
index 082b19f..0000000
--- a/Under-Testing/Server-Code-New/gsmselftest.py
+++ /dev/null
@@ -1,795 +0,0 @@
-#! /usr/bin/env python
-from serial import * #serial port library
-import sys
-import ControllerClass
-import DbClass
-import PingClass
-import truthtableClass
-import initTestClass
-import usbDetectClass
-import WebsiteCommClass
-import signal
-import random
-from time import sleep
-import setproctitle
-
-setproctitle.setproctitle('Controller Software')
-
-class bcolors:
- HEADER = '\033[95m'
- OKBLUE = '\033[94m'
- OKGREEN = '\033[92m'
- WARNING = '\033[93m'
- FAIL = '\033[91m'
- ENDC = '\033[0m'
-
- def disable(self):
- self.HEADER = ''
- self.OKBLUE = ''
- self.OKGREEN = ''
- self.WARNING = ''
- self.FAIL = ''
- self.ENDC = ''
-class TimeoutException(Exception):
- pass
-
-global resultsList
-resultsList = list()
-global taskNo
-dbStatus = None
-global caller
-global callee
-
-def timeout_handler(signum, frame):
- raise TimeoutException()
-
-def allPing(): #ping all existing devices
-
- global sipGate
- global sipServer
- global unisip
- global gsmBox1
- global gsmBox2
-
- serverAdd = db.deviceAddress(str('landline'))
- server = PingClass.Ping(str(serverAdd[4]))
- sipGate = server.ping(1)
-
- serverAdd = db.deviceAddress(str('sip'))
- server = PingClass.Ping(str(serverAdd[4]))
- sipServer = server.ping(1)
-
- serverAdd = db.deviceAddress(str('unisip'))
- server = PingClass.Ping(str(serverAdd[4]))
- unisip = server.ping(1)
-
- serverAdd = db.deviceAddress(str('GSMRZ2'))
- server = PingClass.Ping(str(serverAdd[4]))
- gsmBox1 = server.ping(1)
-
- serverAdd = db.deviceAddress(str('GSMRZ3'))
- server = PingClass.Ping(str(serverAdd[4]))
- gsmBox2 = server.ping(1)
-
-def initDB(): # function for connection database
- global dbStatus
- global db
- if dbStatus != 1:
- db = DbClass.DBMySQLConnection()
- db.connectDB()
- dbStatus = db.connectDB()
- if dbStatus == 1:
- db.lockMutex(600)
-
-def initNagiosString(x):
-
- initResult = truthtableClass.trueTable(x)
- initResult.initNagiosResult()
-
- if int(initResult.FAILED) != 0:
- print "GSM CRITICAL - Number of test "+str(initResult.testMount)+'; Failure '+str(initResult.FAILED)+'; Unknown '+str(initResult.handlerError)
- elif int(initResult.handlerError) != 0:
- print "GSM WARNING - Number of test "+str(initResult.testMount)+'; Failure '+str(initResult.FAILED)+'; Unknown '+str(initResult.handlerError)
- elif int(initResult.FAILED) == 0 and int(initResult.handlerError) == 0:
- print "GSM OK - Number of test "+str(initResult.testMount)+'; Failure '+str(initResult.FAILED)+'; Unknown '+str(initResult.handlerError)
- else:
-
- print "unknown error"
-
-def initTrueTable(x):
-
- initResult = truthtableClass.trueTable(x)
- initResult.initTrueTable()
-
- print '\n'
- openBSC = None
- asterikServer = None
- for x in initResult.nanoBts:
-
- name = x[0]
- if x[1] == True:
- openBSC = True
- asterikServer = True
- print bcolors.OKGREEN +name+ ' Working'+ bcolors.ENDC
-
- else:
- if int(x[1]) == 486:
- print bcolors.FAIL+name+ ' not Working' + bcolors.ENDC
- elif int(x[1]) == 200:
- print bcolors.OKGREEN +name+ ' Working'
- asterikServer = True
- elif int(x[1]) == 402:
- print bcolors.WARNING +name+ ' not Working need top up the credit'
- asterikServer = True
- elif int(x[1]) == 998 or int(x[1]) == 999:
- print bcolors.FAIL+name+ ' not Working, handler error'+ bcolors.ENDC
- elif int(x[1]) == 801 or int(x[1]) == 802:
- print bcolors.FAIL+name+ ' Device Error, Check the device'+ bcolors.ENDC
- else:
- print bcolors.OKGREEN +name+ ' not Working'+ bcolors.ENDC
-
- print ''
- if openBSC != None:
- if openBSC == True:
- print bcolors.OKGREEN +'openBSC working'+ bcolors.ENDC
- else:
- print bcolors.FAIL+'openBSC doesnt work'+ bcolors.ENDC
- print ''
-
- if initResult.asteriskServer == True or asterikServer == True:
- print bcolors.OKGREEN +'asterik server is working'+ bcolors.ENDC
- print ''
-
- if initResult.outGoingRZ == True:
- print bcolors.OKGREEN +'Outgoing call from RZ is working'+ bcolors.ENDC
- elif initResult.outGoingRZ == False:
- print bcolors.FAIL+'Outgoing call from RZ is not working'+ bcolors.ENDC
-
- if initResult.incomingRZ == True:
- print bcolors.OKGREEN +'incoming call from outside RZ to GSM RZ is working'+ bcolors.ENDC
- elif initResult.incomingRZ == False:
- print bcolors.FAIL+'incoming call from outside RZ to GSM RZ is not working'+ bcolors.ENDC
- print '\n'
-
-def errorCodes(callFrom, callTo, result):
- message = '|' + str(callFrom) + '|' + str(callTo) + '|' + str(result) + '|' + str(db.errorCode(result))
-
- sendResultWebsite(message)
-
- # function to search in the list
-def isThere(keyword,lists):
- x = 0
- for item in lists:
-
- if item == keyword:
- return 1
- else:
- x = x+1
-
-def testDest(callFrom, callTo, tried):
-
- makeTest.initTest(callFrom,callTo)
- db.insertTask(taskNum,callFrom,callTo)
- smartResultList.append([callFrom,callTo, makeTest.result,tried])
- taskID = db.maxTaskID()
- db.addResult(taskID, makeTest.result)
- if WebStatus == True:
- errorCodes(callFrom, callTo, makeTest.result)
-
-def smartTest():
- global smartResultList
- smartResultList = list()
- deviceLists = db.deviceList()
- gsmList = list()
- gsmRZList = list()
- sipList = list()
- destList = list()
- rem = list()
- item = list()
-
- cpgsmRZList = list()
-
- for lists in deviceLists: #define category of the device
- device = lists[0]
- if device[0:5] == 'GSMRZ':
- gsmRZList.append(device)
- cpgsmRZList.append(device)
- elif device[0:5] == 'GSMEx':
- gsmList.append(device)
- else:
- sipList.append(device)
-
- if device[0:5] == 'GSMRZ' or device[0:5] == 'GSMEx' or device == 'sip':
- destList.append(device)
-
- #first test from university telphone network to random GSM RZ avaliable
- i = random.randint(0, len(gsmRZList)-1)
- callTo = gsmRZList[i]
- callFrom = 'unisip'
- testDest(callFrom, callTo, 1)
- gsmRZList.remove(callTo)
- destList.remove(callTo)
-
-
- for callFrom in gsmRZList:
- i = random.randint(0, len(destList)-1) #Check whether the caller and dest are same
- callTo = destList[i]
- if callFrom == callTo: #Check whether the caller and dest are same
- if i == 0:
- i = i+1 # if it in the first list, change to be the second list else, just back on step.
- else:
- i = i-1
- callTo = destList[i]
-
- destList.remove(callTo)
- destList.remove(callFrom)
- gsmRZList.remove(callFrom)
- testDest(callFrom, callTo, 1)
-
-
- # test incoming call from outside rz network to gsm rz
- i = random.randint(0, len(gsmRZList)-1) #
- callTo = gsmRZList[i]
- callFrom = 'landline'
-
- if isThere(callTo,destList) == 1: # Checking whether caller at gsmrz list in the destination list, if yes delete it.
- destList.remove(callTo)
- testDest(callFrom, callTo, 1)
-
- for callTo in destList:
- callFrom = 'sip'
- if callFrom != callTo:
- testDest(callFrom, callTo, 1)
-
- #checking unsuccess call, to make sure that destination are really unreachable
- for dest in smartResultList:
- #check unsuccess call and did the test have already tried, 2 means has been check
- if int(dest[2]) == 486 or int(dest[2]) == 999 or int(dest[2]) == 998 or int(dest[2]) == 801 or int(dest[2]) == 802:
-
- if int(dest[3]) != 2 and dest[1] != 'sip':
- testDestination = True
- testFromRZ = False
- testCaller = True
- # make sure that destination have not tested by another part and give success result.
- for test in smartResultList:
- if test[1] == dest[1] or test[0] == dest[1]:
- if int(test[2]) == 200:
- testDestination = False
- if test[1] == dest[0] or test[0] == dest[0]:
- if int(test[2]) == 200:
- testCaller = False
- #if destination have not tested by other part. try to test from RZ GSM
- if int(test[2]) == 200 and testFromRZ != True:
- for caller in cpgsmRZList:
- if caller == test[0] or caller == test[1]:
- callFrom = caller
- testFromRZ = True
-
- if testDestination == True:
- if testFromRZ != True:
- callFrom = 'sip'
- callTo = dest[1]
- testDest(callFrom, callTo, 2)
- rem.append(dest)
-
- #check unsuccess call because caller handler having problem
- #destination handler having problem, we should make test also to the caller
- if int(dest[2]) == 998 or int(dest[2]) == 802 or int(dest[2]) == 486:
- if testCaller == True:
- if testFromRZ != True:
- callFrom = 'sip'
- callTo = dest[0]
- testDest(callFrom, callTo, 2)
- rem.append(dest)
-
-
- caller = dest[0] # to test nanobts if the test come from RZ GSM but fehler
- if caller[0:5] == 'GSMRZ' and int(dest[3]) != 2 and dest[1] != 'sip':
- repeatTest = True
- for test in smartResultList:
- if test[1] == caller or test[0] == caller:
- repeatTest = False
- if int(dest[2]) == 486 or int(dest[2]) == 402:
- if repeatTest == True:
- callFrom = 'sip'
- testDest(callFrom, dest[0], 2)
- rem.append(dest)
-
- # test to make sure nanoBTS working or not. sice probably that nanotbts seems error but actually not.
- for RZ in cpgsmRZList:
- repeat = False
- for gsmrzResult in smartResultList:
- if gsmrzResult[0] == RZ or gsmrzResult[1] == RZ:
- if int(gsmrzResult[2]) == 486 or int(gsmrzResult[2]) == 801 or int(gsmrzResult[2]) == 802:
- repeat = True
- From = gsmrzResult[0]
- To = gsmrzResult[1]
- result = gsmrzResult[2]
- if int(gsmrzResult[2]) == 200:
- repeat = False
- if gsmrzResult[1] == RZ and int(gsmrzResult[2]) == 998:
- try:
- cpgsmRZList.remove(RZ)
- except ValueError:
- message = 'Error'
- if gsmrzResult[0] == RZ and int(gsmrzResult[2]) == 999:
- try:
- cpgsmRZList.remove(RZ)
- except ValueError:
- message = 'Error'
-
- if len(cpgsmRZList) > 1:
- if repeat == True:
- i = random.randint(0, len(cpgsmRZList)-1) #
- if i == 0:
- x = i+1
- else:
- x = i-1
- testDest(cpgsmRZList[x], cpgsmRZList[i], 2)
- item = '['+str(From)+','+str(callTo)+','+str(result)+','+str(1)+']'
- rem.append(item)
-
- for remov in rem:
- for x in smartResultList:
- if x == remov:
- try:
- smartResultList.remove(x)
- except ValueError:
- message = 'Error'
- return smartResultList
-
-def doSmartTest(status):
- global taskNum, printMessage
- global WebStatus
- initDB()
- taskNum = db.maxTaskNo()
- global makeTest
- if status == True:
- WebStatus = True
-
- else:
- WebStatus = False
-
- makeTest = initTestClass.initTesting()
- result = smartTest()
- if status == 'NAGIOS':
- initNagiosString(result)
-
- elif status == False:
- initTrueTable(result)
-
- if status == True:
- sendFinishMessage()
-
-
-def doSipTest():
- destList = ['landline', 'unisip']
- doTest = initTestClass.initTesting()
- for callTo in destList:
-
- callFrom = 'sip'
- doTest.initTest(callFrom,callTo)
- resultsList.append([callFrom, callTo, doTest.result])
- initTrueTable(resultsList)
-def doIncomingTest(): #incoming call to RZ network
-
- destList = ['GSMRZ1','unisip', 'GSMRZ2','GSMRZ3']
- doTest = initTestClass.initTesting()
- for callTo in destList:
- callFrom = 'landline'
- doTest.initTest(callFrom,callTo)
- resultsList.append([callFrom, callTo, doTest.result])
- initTrueTable(resultsList)
-
-def doGsmrzTest():
-
- destList = ['GSMRZ1','GSMRZ2', 'GSMRZ3']
- callList = ['sip']
- doTest = initTestClass.initTesting()
-
- for callFrom in callList:
- for callTo in destList:
- doTest.initTest(callFrom,callTo)
- resultsList.append([callFrom, callTo, doTest.result])
- initTrueTable(resultsList)
-
-def doGsmExtTest():
-
- destList = ['GSMExt.O2', 'GSMExt.Voda', 'GSMExt.Eplus', 'GSMExt.Tm']
- callList = ['sip']
-
- doTest = initTestClass.initTesting()
-
- for callFrom in callList:
- for callTo in destList:
- doTest.initTest(callFrom,callTo)
- resultsList.append([callFrom, callTo, doTest.result])
- initTrueTable(resultsList)
-
-def doAllTest():
-
- doSipTest()
- doIncomingTest()
- doGsmrzTest()
- doGsmExtTest()
-
-
-def sendResultWebsite(message):
- if server.sendData(message+ chr(10)) == 1:
- print 'data sent successfully'
- test = server.receiveData(5)
- if test == 'TIMEOUT':
- closeFunction(db,server)
- sys.exit(2)
- if test == 'CONTINUE':
- print 'continue'
-
-def sendFinishMessage():
- if server.connected == 1:
- server.sendData('TEST DONE\n')
- test = server.receiveData(5)
- if test == 'TIMEOUT':
- closeFunction(db,server)
- if test == 'DISCONNECT':
- close = server.closeConnection()
- if close == 1:
- print 'Closed connection successfully'
-
- print 'release mutex says ', db.releaseMutex()
-
-def withDB(x):
-
- initDB()
-
- if x == False:
- deviceLists = db.deviceList()
- callerFound = False
- calleeFound = False
- for device in deviceLists:
- if caller == device[0]:
- callerFound = True
- break
-
- for device in deviceLists:
- if callee == device[0]:
- calleeFound = True
- break
- if callerFound != True or calleeFound != True:
- if callerFound != True:
- print 'No device with name', caller
- db.closeDBConn()
- sys.exit(1)
- if calleeFound != True:
- print 'No device with name', callee
- db.closeDBConn()
- sys.exit(1)
- if callerFound == True and calleeFound == True:
- taskNumber = db.maxTaskNo()
- db.insertTaskIn2(caller, callee, taskNumber)
- resultsList = list()
- if dbStatus == 1: # Checking connection to database
- if db.anyTasksToDo() == 1: # Checking task on the table
-
- allPing()
- i=0
- makeTest = initTestClass.initTesting()
-
- for item in db.tasksList:
-
- taskID = item[0]
- taskNo = item[1]
- callFrom = item[2]
- callTo = item[3]
-
- if i == 0:
- db.updatePingResult(taskNo, sipServer, sipGate, unisip, gsmBox1, gsmBox2)
- print '\n'
- print 'Task ID :', taskID
- print 'Calling From :', callFrom
- print 'To :', callTo
-
-
- makeTest.initTest(callFrom,callTo)
-
- db.addResult(taskID, makeTest.result)
-
- resultsList.append([callFrom, callTo, makeTest.result])
-
- db.errorCode(makeTest.result)
-
- if int(makeTest.result) == 200:
- print bcolors.OKGREEN +'Result : ' +str(makeTest.result)+ ' ' +db.errCode + bcolors.ENDC
- else:
- print bcolors.FAIL+'Result : ' +str(makeTest.result)+ ' ' +db.errCode + bcolors.ENDC
-
- if x == True: # if x = True means that this function call by website
-
- message = '|' + str(callFrom) + '|' + str(callTo) + '|' + str(makeTest.result) + '|' + str(db.errCode)
- sendResultWebsite(message) # send result to website
-
- db.deleteTempTask(taskID)
- i = i+1
-
- db.cleanTasksList()
-
- if x == True:
- sendFinishMessage() #send finish message to website and close the connection
-
- print '\n'
-
- initTrueTable(resultsList) # fetch result list and make adjustment about the result
- db.closeDBConn()
- else:
- print bcolors.FAIL+"--- No job at all ---" + bcolors.ENDC
- db.closeDBConn()
- else:
- print bcolors.FAIL+'Cant connect to database'+ bcolors.ENDC
- sys.exit(1)
-
-def findPort(portName): # take information in existing usb port
- global connect
- global prefix
- global num
- global IMEI
- global portClass
- sleep(0.5)
- portLog = os.popen('dmesg | grep \'pl2303 converter now attached to '+portName+'\'').read()
- sleep(0.5)
- if portLog != '':
- connect = 1
- portClass = usbDetectClass.serialPort(portName)
- portClass.findNumber()
- portClass.findIMEI()
- IMEI = portClass.IMEI
- num = portClass.number
- number = portClass.number
- prefix = number[0:4]
- else:
- connect = 0
-
-def initDevice(deviceName):
- print 'Device Name :',deviceName
- print ' Device IMEI : ',
- imei = sys.stdin.readline().rstrip("\r\n")
- print 'Phone number : ',
- number = sys.stdin.readline().rstrip("\r\n")
- print 'Port Name : /dev/',
- portName = sys.stdin.readline().rstrip("\r\n")
- print ''
-
- if imei == '' or portName == '':
- print bcolors.FAIL+' == cant save device configuration, please fill IMEI / port name of the device =='+ bcolors.ENDC
- else:
- findPort(portName)
- if connect == 1:
- if str(IMEI) != str(imei) and str(num) != str(number):
- print bcolors.FAIL+'== error, device not found =='+ bcolors.ENDC
- elif str(IMEI) == str(imei):
- portClass.initUpdate(deviceName, portName, number)
- print bcolors.OKGREEN +'== Device succeced added =='+ bcolors.ENDC
- elif str(num) == str(number) and str(IMEI) != str(imei):
- portClass.initUpdate(deviceName, portName, number)
- print bcolors.WARNING+'== Device succeced added, but have different IMEI =='+ bcolors.ENDC
- else:
- print bcolors.FAIL+'== error, no device connected =='+ bcolors.ENDC
-
-def autoUpdateDevice(status):
- initDB()
- GSMListPrefix = list()
- GSMListPrefix = db.GSMPrefix()
- i = 0
- x = 0
- count = 0
- while i !=10:
- portName ='ttyUSB'+str(i) #checking usb connection
-
- i=i+1
- old_handler = signal.signal(signal.SIGALRM, timeout_handler)
- signal.alarm(15)
- try:
- findPort(portName)
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- if connect == 1:
- for listNum in GSMListPrefix:
- if prefix == listNum[1]:
- print 'Device Name :',listNum[0]
- print 'IMEI :',IMEI
- print 'Phone Number :',num
- print 'Port Name : /dev/'+portName
- x=x+1
- newPortName = '/dev/'+portName
- portClass.initUpdate(listNum[0], newPortName, num)
- print '\n'
- except TimeoutException:
- signal.signal(signal.SIGALRM, old_handler)
- signal.alarm(0)
- count = count + 1
- message = "Timeout"
- if status == True:
- sendFinishMessage()
- else:
-
- print '== FINISH =='
- print 'Found '+str(x)+' devices'
-
-def updateDevice(): #update port name list of device on DB
- quit = False
- while quit != True:
- print ''
- print "Mobile device configuration"
- print "Menu: a = automatic device configuration, m = Manual configuration, q = quit : ",
- input = sys.stdin.readline().rstrip("\r\n")
- print ''
- if input == 'm': # manual configuration
-
- while True:
- print ''
- print "Mobile device name: "
- print " 1. GSM O2"
- print " 2. GSM Vodafone"
- print " 3. GSM Eplus"
- print " 4. GSM T-Mobile"
- print " 5. GSM RZ 1"
- print " 6. Back to menu"
- print ""
- print "your choise : ",
- input = sys.stdin.readline().rstrip("\r\n")
-
- if input == '6':
- break
- elif input == '1':
- initDevice('GSMExt.O2')
- elif input == '2':
- initDevice('GSMExt.Voda')
- elif input == '3':
- initDevice('GSMExt.Eplus')
- elif input == '4':
- initDevice('GSMExt.Tm')
- elif input == '5':
- initDevice('GSMRZ1')
- else:
- print 'please choose between 1-6'
-
- if input == 'a': #automatic configuration
- autoUpdateDevice(False)
-
- if input == "q":
- break
- sys.exit()
-
-def closeFunction(dbConn,serverSocket):
- print 'Release the mutex: ' + str(dbConn.releaseMutex())
- print 'Close the DB Connection: ' + str(dbConn.closeDBConn())
- del dbConn
- del serverSocket
- sys.exit()
-
-if len(sys.argv) > 1:
-
- command = sys.argv[1]
-
- if command == '--all':
- resultsList = list()
- doAllTest()
-
- elif command == '--sip':
- resultsList = list()
- doSipTest()
-
- elif command == '--gsmrz':
- resultsList = list()
- doGsmrzTest()
-
- elif command == '--gsmext':
- resultsList = list()
- doGsmExtTest()
-
- elif command == '--incoming':
- resultsList = list()
- doIncomingTest()
-
- elif command == '--smart':
- initDB()
- resultsList = list()
- allPing()
- taskNo = db.maxTaskNo()
- db.updatePingResult(taskNo, sipServer, sipGate, unisip, gsmBox1, gsmBox2)
- doSmartTest(False)
-
- elif command == '--nagios':
- initDB()
- resultsList = list()
- allPing()
- taskNo = db.maxTaskNo()
- db.updatePingResult(taskNo, sipServer, sipGate, unisip, gsmBox1, gsmBox2)
- doSmartTest('NAGIOS')
-
- elif command == '--devconf':
- updateDevice()
-
- elif command == '--db':
- if len(sys.argv) > 2:
- try:
- caller = sys.argv[2]
- callee = sys.argv[3]
-
- except ValueError:
- print "Error given caller and destination. Type '--help' for more information."
- else:
- print "Error given caller and destination. Type '--help' for more information."
- sys.exit()
- resultsList = list()
- withDB(False)
-
- elif command == '--help':
- file = open('help.txt', 'r')
- print file.read()
-
- else:
- print "command not found, Type '--help' for more information."
- print '\n'
-else:
- global server
- global tried
-
-
- initDB() # should put db condition
- server = WebsiteCommClass.ServerHandlerSoftware(34500) #define the port
- tried = server.openSocket(10)
-
- if tried == 'TIMEOUT':
- closeFunction(db,server)
-
- test = server.receiveData(10)
- if test == 'TIMEOUT':
- closeFunction(db,server)
-
- if test == 'START TEST':
- server.sendData('CONFIRM\n')
- print 'TEST STARTED'
- withDB(True)
-
- if test == 'SMART TEST':
- allPing()
- taskNo = db.maxTaskNo()
- db.updatePingResult(taskNo, sipServer, sipGate, unisip, gsmBox1, gsmBox2)
- server.sendData('CONFIRM\n')
- print 'SMART TEST STARTED'
- resultsList = list()
- doSmartTest(True)
-
- if test == 'UPDATE DEVICE':
- server.sendData('CONFIRM\n')
- print 'UPDATE DEVICE STARTED'
- autoUpdateDevice(True)
- else:
- sys.exit('WE DIDN\'T RECEIVE THE CONFIRMATION')
-
- db.closeDBConn()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Under-Testing/Server-Code-New/handler.txt b/Under-Testing/Server-Code-New/handler.txt
deleted file mode 100644
index 45b50ac..0000000
--- a/Under-Testing/Server-Code-New/handler.txt
+++ /dev/null
@@ -1 +0,0 @@
---
diff --git a/Under-Testing/Server-Code-New/help.txt b/Under-Testing/Server-Code-New/help.txt
deleted file mode 100644
index 1a3b843..0000000
--- a/Under-Testing/Server-Code-New/help.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-
-Usage: ./gsmselftest.py [option]
-
-Options and arguments (and corresponding environment variables):
-
---db [caller] [callee] : To execute the test case given by defining the caller and callee
---all : To execute all test cases
---sip : To execute SIP test cases
---gsmrz : To check whether GSM RZ network has problems or not
---gsmext : To check whether GSM BOX modem has problems or not
---incoming : To check incoming calls from Landline
---smart : To test only important points in the network and to identify the problems
---devconf : To configure the USB device on the server
---nagios : Execute smart test but only for Nagios plugin
-
- example : ./gsmselftest.py --devconf
- ./gsmselftest.py --smart
- ./gsmselftest.py --db sip GSMRZ1
diff --git a/Under-Testing/Server-Code-New/initTestClass.py b/Under-Testing/Server-Code-New/initTestClass.py
deleted file mode 100644
index 568f840..0000000
--- a/Under-Testing/Server-Code-New/initTestClass.py
+++ /dev/null
@@ -1,122 +0,0 @@
-import sys
-import subprocess, signal
-import os
-import ControllerClass
-import DbClass
-import PingClass
-import random
-from time import sleep
-
-class initTesting:
-
- def __init__(self):
- self.messageList = list()
-
- def pings(self,IP):
-
- server = PingClass.Ping(IP)
- self.serverStatus = server.ping(2)
- return self.serverStatus
-
- def initDB(self):
-
- self.db = DbClass.DBMySQLConnection()
- self.db.connectDB()
- self.dbStatus = self.db.connectDB()
-
- def initaccount(self,account,handler):
- if handler == 'sip' or handler == 'unisip' or handler == 'landline':
- if account[1] != '' or account[2] != '' or account[3] != '' or account[4] != '':
- # checking available sip account, is there enough information about the account such as username, password,server
- self.status = 1
- else:
- self.status = 0
- else:
- if account[0] != '' or account[1] != '':
- self.status = 1
- else:
- self.status = 0
-
-
- #kill process to make sure, that the handler is Terminate incase handler having problem receiving terminate message from controller
- def killProc(self):
- # define process name of the Handler
- procNameDest = 'GSM Handler'
- procNameCall = 'SIP Handler'
-
- p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
- out, err = p.communicate()
-
- #search process name and kill it.
- for line in out.splitlines():
- if procNameDest in line:
- pid = int(line.split(None, 1)[0])
- os.kill(pid, signal.SIGKILL)
- for line in out.splitlines():
- if procNameCall in line:
- pid = int(line.split(None, 1)[0])
- os.kill(pid, signal.SIGKILL)
-
-
- def initTest(self, callFrom, callTo):
-
- self.initDB() # open database connection
-
- if self.dbStatus != 0: # if connection to db establish, do the test
-
- #fetch device account detail from database
- dest = self.db.deviceAddress(str(callTo))
- caller = self.db.deviceAddress(str(callFrom))
-
- # check that the caller server allive or not
- if self.pings(caller[4]) <> 0:
-
- # check that the destination server allive or not
- if self.pings(dest[4]) <> 0:
-
- self.initaccount(caller,callFrom)
- if self.status == 1:
- self.initaccount(dest,callTo)
-
- if self.status == 1:
- #string = 'Account:username:password:server:ipaddress:portaddress:portnumber'
-
- callPortName = caller[0]
- accCaller = caller[2]+':'+caller[3]+':'+caller[4]+':'
-
- destPortName = dest[0]
- destNo = dest[1]
- accDest = dest[2]+':'+dest[3]+':'+dest[4]+':'
-
- # create controller class object and send the handler information
- makeTest = ControllerClass.controller(callFrom, callPortName, accCaller, callTo, destPortName, destNo, accDest)
- makeTest.FuncTest()
-
- self.result = str(makeTest.testResult)
-
- else:
- self.result = 100
- else:
- self.result = 100
-
- sleep(2)
- #make sure the handler have been terminated
- self.killProc() # kill all the handler
-
- self.db.closeDBConn() #close db connection
- sleep(1)
- else:
- #destintaion server die
- self.result = 501
- else:
- #caller server die
- self.result = 500
- self.db.closeDBConn()
- else:
- self.result = 333
-
- return self.result
-
-
-
-
diff --git a/Under-Testing/Server-Code-New/startSoftware.py b/Under-Testing/Server-Code-New/startSoftware.py
deleted file mode 100644
index b2beb58..0000000
--- a/Under-Testing/Server-Code-New/startSoftware.py
+++ /dev/null
@@ -1,21 +0,0 @@
-#! /usr/bin/env python
-import ServerClass
-import subprocess
-import setproctitle
-
-setproctitle.setproctitle('Start Software')
-while 1:
- # try connect to website
- server = ServerClass.ServerHandler(34600)
- tried = server.openSocket()
- test = server.receiveData(2)
- if test == 'START APP':
- print 'start'
- try:
- script = 'gsmselftest.py'
- subprocess.Popen(['python',script], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- except ValueError:
- print " - can't start controller software -"
- server.closeConnection()
- del server
-
diff --git a/Under-Testing/Server-Code-New/truthtableClass.py b/Under-Testing/Server-Code-New/truthtableClass.py
deleted file mode 100644
index c45ab4d..0000000
--- a/Under-Testing/Server-Code-New/truthtableClass.py
+++ /dev/null
@@ -1,233 +0,0 @@
-import DbClass
-
-class trueTable:
- def __init__(self, resultsList):
-
- self.resultsList = resultsList
- self.outGoingRZ = None
- self.asteriskServer = None
- self.incomingRZ = None
- self.openBSC = None
- self.nanoBTS = None
- self.deviceStatus = list()
- self.testMount = len(resultsList)
- self.OK = 0
- self.FAILED = 0
- self.handlerError = 0
-
- def initDB(self):
- # function for connect to database
- self.db = DbClass.DBMySQLConnection()
- self.db.connectDB()
- self.dbStatus = self.db.connectDB()
-
- def lookingBTSname(self, btsname):
- if len(self.nanoBts) == 0:
- self.found = False
- else:
- found = False
- for y in self.nanoBts: #find the existing nanoBts result
- name = y[0]
- if name == btsName:
- self.found = True
- return self.found
-
- def findStatusInList(self,key):
-
- if len(self.deviceStatus) == 0:
- update = False
- else:
- update = False
- for item in self.deviceStatus:
- if key == item[0] and str(item[1]) != 'OK':
- update = True
- return update
-
- def initNagiosResult(self):
- self.initDB()
- deviceLists = self.db.deviceList()
- self.db.closeDBConn()
-
- for items in deviceLists:
- device = items[0]
- for result in self.resultsList:
- if device == result[0] or device == result[1]:
- if int(result[2]) == 200:
- if self.findStatusInList(device) == True:
- try:
- self.deviceStatus.remove([device,'NOT OK'])
- except:
- try:
- self.deviceStatus.remove([device,'UNKNOWN'])
- except:
- continue
- self.deviceStatus.append([device,'OK'])
- else:
- self.deviceStatus.append([device,'OK'])
-
- elif int(result[2]) == 486:
- found = False
- for item in self.deviceStatus:
- if device == item[0]:
- if str(item[1]) != 'OK' or str(item[1]) == 'OK':
- found = True
- if found == False:
- self.deviceStatus.append([device,'NOT OK'])
- else:
- found = False
- for item in self.deviceStatus:
- if device == item[0]:
- if str(item[1]) != 'OK' or str(item[1]) == 'OK':
- found = True
- if found == False:
- self.deviceStatus.append([device,'UNKNOWN'])
- for status in self.deviceStatus:
-
- if status[1] == 'OK':
- self.OK = self.OK+1
- elif status[1] == 'NOT OK':
- self.FAILED = self.FAILED+1
- else:
- self.handlerError = self.handlerError+1
-
- def initTrueTable(self):
- global btsName
- self.initDB()
- deviceLists = self.db.deviceList() #fetch device list from database
- externalRZList = list()
-
- for devLists in deviceLists: #define category of the external devices
- device = devLists[0]
-
- if device[0:5] == 'GSMEx' or device == 'landline':
- externalRZList.append(device) # fetch into the list
- self.db.closeDBConn()
- lists = self.resultsList
- self.nanoBts = list()
- gsmResultList = list()
-
- i= 1
- for w in lists:
- call=w[0]
- dest=w[1]
-
-
- if call[0:5]=='GSMRZ':
- if i <= int(call[5:]):
- i = int(call[5:])
- if dest[0:5]=='GSMRZ':
-
- if i <= int(dest[5:]):
- i = int(dest[5:])
- i = i+1
-
- for x in lists: # to find nanoBts, asterik server and open BSC status regarding result test for GSM RZ
- call=x[0]
- dest=x[1]
- result=x[2]
- stop = False
- j=1
-
- if call[0:5]=='GSMRZ' or dest[0:5]=='GSMRZ':
- while stop != True:
- if j != i:
- key = 'GSMRZ'+str(j)
- if key == call or key == dest:
-
- btsName = 'nanoBts '+str(j)
- if result == '200':
-
- btsName = 'nanoBts '+str(j)
- self.asteriskServer = True #set status of asterik server as working
- self.lookingBTSname(btsName)
- if self.found != True:
- #if doesnt found the nanoBts, add the result to the list, otherwise just ignoring
- try:
- self.nanoBts.remove(btsName)
- except ValueError:
- message = 'Error'
-
- self.nanoBts.append([btsName,True])
-
- if key == call:
- for z in externalRZList:# find the result for outgoing call from GSM RZ to external RZ network
- if dest == z:
- self.outGoingRZ = True #set status as working for outgoing RZ
- if key == dest:
- for z in externalRZList:
- if call == z:
- self.incomingRZ = True # find the result for imcoming call to GSM RZ from external RZ network
- elif result == '486':
- found = False
- if key == call:
- for z in externalRZList:
- if dest == z and self.outGoingRZ != True:
- self.outGoingRZ = False
- if key == dest:
- for z in externalRZList:
- if call == z and self.incomingRZ != True:
- self.incomingRZ = False
- if self.nanoBts == '':
- self.nanoBts.append([btsName,False])
- for y in self.nanoBts: #find the existing nanoBts result
- name = y[0]
- if name == btsName and y[1] == True:
- found = True
- if found != True:
- self.nanoBts.append([btsName,False])
-
- elif (str(result) == '801' or str(result) == '999') and key == call:
- self.lookingBTSname(key)
- if self.found != True:
- self.nanoBts.append([key,result])
-
- elif (str(result) == '802' or str(result) == '998') and key == dest:
- self.lookingBTSname(key)
- if self.found != True:
- self.nanoBts.append([key,result])
-
- j = j+1
- elif j == i:
- stop = True
-
- if call[0:5]=='GSMEx': # looking for calling from GSMexternal
- found = False
- if len(self.nanoBts) == 0:
- self.nanoBts.append([call,result])
- found = False
- else:
- for y in self.nanoBts: #find the existing result for GSM external in the list
- name = y[0]
- if name == call:
- if int(result) == 200:
- if int(y[1]) == 486 or int(y[1]) == 999 or int(y[1]) == 998 or int(y[1]) == 801:
- self.nanoBts.remove(y)
- else:
- found = True
- if found != True:
- self.nanoBts.append([call,result])
-
- if dest[0:5]=='GSMEx': # looking for destination call to GSMexternal
- found = False
- if len(self.nanoBts) == 0:
- self.nanoBts.append([dest,result])
- found = False
- else:
-
- for y in self.nanoBts:
- name = y[0]
- if name == dest:
- if int(result) == 200:
- if int(y[1]) == 486 or int(y[1]) == 999 or int(y[1]) == 998 or int(y[1]) == 402 or int(y[1]) == 802:
- self.nanoBts.remove(y)
- else:
- found = True
- if found != True:
- self.nanoBts.append([dest,result])
-
-
- for device in externalRZList:
- if device == dest and int(result) == 200:
- self.outGoingRZ = True
-
-
diff --git a/Under-Testing/Server-Code-New/usbDetectClass.py b/Under-Testing/Server-Code-New/usbDetectClass.py
deleted file mode 100644
index d64e328..0000000
--- a/Under-Testing/Server-Code-New/usbDetectClass.py
+++ /dev/null
@@ -1,96 +0,0 @@
-from serial import * #serial port library
-import sys
-from time import sleep
-import DbClass
-
-
-class serialPort:
-
- def __init__(self, portAddress):
- self.portAddress = portAddress
- self.portExist = 0
- self.IMEI = None
- self.number = None
- #self.updateStatus = None
-
- def initDB(self):
- self.db = DbClass.DBMySQLConnection()
- self.db.connectDB()
- self.dbStatus = self.db.connectDB()
-
- def initUpdate(self, deviceName, newPortName, newNumber):
- self.initDB()
-
- if self.dbStatus != 0:
- self.db.updateGSMDevice(deviceName, newPortName, newNumber)
- else:
- print 'No connection to database'
-
- def portInit(self):
- self.portExist = 0
- try:
- self.ser = Serial(
- port='/dev/'+self.portAddress,
- baudrate=19200,
- bytesize=EIGHTBITS,
- parity=PARITY_NONE,
- stopbits=STOPBITS_ONE)
- self.ser.open()
- self.ser.isOpen()
- self.portExist = 1
-
- except Exception, e:
- return 0
-
- def isInteger(self, x):
- try:
- int(x)
- return True
- except:
- return False
-
- def findIMEI(self):
- self.portInit()
- if self.portExist == 1:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('AT+GSN\r')
- sleep(0.5)
- result = self.ser.read(25)
- if result != '':
- self.IMEI = result[result.find('3'):15+result.find('3')]
- else:
- self.IMEI = 'IMEI not found'
- return self.IMEI
-
- else:
- self.IMEI = 'port not found'
- return 0
-
- def findNumber(self):
- self.portInit()
-
- if self.portExist == 1:
- self.ser.flushInput() #clean the input buffer for serial port
- self.ser.write('AT+CNUM\r')
- sleep(0.5)
- readNum = self.ser.read(35)
- self.ser.close()
- firstQuote = readNum.find('"')
- cutString = readNum [firstQuote:]
- secondQuote = cutString.find(',')
- number = cutString[1:secondQuote-1]
-
- if number != '':
- if number.find('+') == 0:
- number = '0'+number[3:len(number)]
- elif int(number[0:1]) == 4:
- number = '0'+number[2:len(number)]
- self.number = number
- else:
- self.number = 'number not found'
-
- return self.number
-
- else:
- self.number = 'port not found'
- return 0