From b99193ba68f947802245a288940e54904ecbee61 Mon Sep 17 00:00:00 2001 From: Triatmoko Date: Fri, 18 Nov 2011 13:23:49 +0100 Subject: final version --- Under-Testing/Box2-Code/GSMClass.py | 303 --------------------------- Under-Testing/Box2-Code/LogFileClass.py | 21 -- Under-Testing/Box2-Code/READ ME.txt | 20 -- Under-Testing/Box2-Code/ServerClass.py | 162 --------------- Under-Testing/Box2-Code/serverHandler.py | 344 ------------------------------- 5 files changed, 850 deletions(-) delete mode 100644 Under-Testing/Box2-Code/GSMClass.py delete mode 100644 Under-Testing/Box2-Code/LogFileClass.py delete mode 100644 Under-Testing/Box2-Code/READ ME.txt delete mode 100644 Under-Testing/Box2-Code/ServerClass.py delete mode 100644 Under-Testing/Box2-Code/serverHandler.py (limited to 'Under-Testing/Box2-Code') diff --git a/Under-Testing/Box2-Code/GSMClass.py b/Under-Testing/Box2-Code/GSMClass.py deleted file mode 100644 index 126446e..0000000 --- a/Under-Testing/Box2-Code/GSMClass.py +++ /dev/null @@ -1,303 +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.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 - ) - 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:': - - 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/Box2-Code/LogFileClass.py b/Under-Testing/Box2-Code/LogFileClass.py deleted file mode 100644 index cb152f4..0000000 --- a/Under-Testing/Box2-Code/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/Box2-Code/READ ME.txt b/Under-Testing/Box2-Code/READ ME.txt deleted file mode 100644 index 654b1f2..0000000 --- a/Under-Testing/Box2-Code/READ ME.txt +++ /dev/null @@ -1,20 +0,0 @@ - -Class files: - - - 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. - - - LogFileClass.py - This class is used to make the log files. - -Handler files: - - - serverHandler.py - -How to start the server Handler: - - you can use SSH connection to the box and type: - - $ sudo python serverHandler.py $ - diff --git a/Under-Testing/Box2-Code/ServerClass.py b/Under-Testing/Box2-Code/ServerClass.py deleted file mode 100644 index 088a2ae..0000000 --- a/Under-Testing/Box2-Code/ServerClass.py +++ /dev/null @@ -1,162 +0,0 @@ -import socket -import sys -import os -import string -import signal -import fcntl -import struct - -class TimeoutException(Exception): - pass - -class ServerHandler: - - def __init__(self,p): - self.port = p - ifname = 'eth0' #define here the interface you want to find the ip address - - #code for getting our public addresss so I can make the SSH tunneling work - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - publicAddress = socket.inet_ntoa(fcntl.ioctl( - s.fileno(),0x8915, # SIOCGIFADDR - struct.pack('256s', ifname[:15]))[20:24]) - - self.host = publicAddress #None #'127.0.0.1' #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) - - 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/Box2-Code/serverHandler.py b/Under-Testing/Box2-Code/serverHandler.py deleted file mode 100644 index 37cab37..0000000 --- a/Under-Testing/Box2-Code/serverHandler.py +++ /dev/null @@ -1,344 +0,0 @@ -import ServerClass -import GSMClass -import LogFileClass -import sys -import os -from time import sleep -def restart_program(): - """Restarts the current program. - Note: this function does not return. Any cleanup action (like - saving data) must be done before calling this function.""" - python = sys.executable - os.execl(python, python, * sys.argv) - - -################################ -################################ -######SET THESE PARAMETERS###### -################################ -portListen = 50008 #port number of handler -nameOfLogFile = 'handler.log' #name of the log file -portAddress = '/dev/ttyUSB0' -baudRate = 19200 -################################ -################################ -################################ - -#create the log file class -logger = LogFileClass.Logging(nameOfLogFile) -#use this variable as the error counter -errorCount = 0 -#start logging all events -logger.logEvent('') -#counter how many time we were in the while loop -whileCounter =0 - -#define global varibales -global lastState -global resetState -global deviceError -lastState = 0 -resetState = 0 -deviceError = 0 - -def initSystem(): - print 'init system' - - 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() - #add this if you need it - gsmDevice = GSMClass.serialPort(portAddress, baudRate, 15) - initDevice = gsmDevice.portInit(5) - ######################################################## - - #add nice formating to the log file :) - - print 'any connection ' + str(anyConnection) - print 'initDevice ' + str(initDevice) - - 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 != 0: - logger.logEvent('$connection established but device not working: ' + str(handlerSocket.connectedTo())) - 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 - -########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' - - - - sendMessage = handlerSocket.sendData(callSuccess) - if deviceError==0: - tryHangUp = gsmDevice.hangUp() - 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' - - handResponse = handlerSocket.sendData(callSuccess) - - if deviceError==0: - tryHangUp = gsmDevice.hangUp() - - return handResponse -######################### - - -########TERMINATE PART######## -def terminateConnection(): - print 'terminate connection' - global resetState - close = handlerSocket.closeConnection() - resetState = 1 - return close -############################## - -########TERMINATE PART######## -def other(): - print 'other' - global lastState - global resetState - - close = handlerSocket.closeConnection() - lastState = 8 - resetState = 1 - return 1 -############################## - - - -while 1: - - 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') - receivedMessage = 0 - print 'reset state: ', resetState - while receivedMessage < 4 and resetState!= 1: - handlerSocket.sendData('DEVICE NOT READY') - print 'I AM IN THIS WHILE LOOP' - - if receivedMessage == 4 or receivedMessage == 5 or receivedMessage == 2 or receivedMessage == 3: - receivedMessage = receiveMessage(20) - else: - receivedMessage = receiveMessage(30) - - elif test ==0: - print 'nobody can connect, reboot board, restart cellphone' - logger.logEvent('nobody can connect, reboot board, restart cellphone') - logger.closeLogging() - del logger - del handlerSocket - del gsmDevice - restart_program() -- cgit v1.2.3-55-g7522