import sys
import os
import time
import datetime
import exceptions
import socket
import msvcrt

AppVersion = 0.2

def FileOpen(name = "test.txt", mode = "w"):
        try:
                ipfile = open(name, mode)
        except :
                ipfile = ""
                return ipfile
        else:
                return ipfile

def FileClose(file ):
        file.close()

def FileWrite(ipfile, data):
        ipfile.write(data);

def LogWrite(file = "log.txt", errmsg = ""):
        errstr = "'"
        errstr = "Time: "+time.ctime()+"\t"+errmsg+"\n"        
        FileWrite(file,errstr)

def OpenSocket(Port = 50007, IP = "172.16.7.37",logfile="log.txt"):
                sock = ''
                try:
                                print "opensocket",IP
                                sock = socket.socket(socket.AF_INET, # Internet
                                                socket.SOCK_DGRAM) # UDP
                except:
                                logstr = "Socket Open Error "+str(sys.exc_info())
                                LogWrite(logfile,logstr)
                                return sock
                
                sock.settimeout(1); #1sec
                # Bind socket to local host and port
                try:
                                sock.bind((IP, Port));
                except:
                                logstr = "socket Bind Error "+str(sys.exc_info()) 
                                LogWrite(logfile,logstr)
                                sock = ''
                                return sock
                return sock

def CloseSocket(sock):
                sock.close()

def Receive(sock, Size = 100,logfile = "log.txt"):
                recv_data = ""
                try:
                                recv_data, recv_addr = sock.recvfrom(Size)
                except socket.timeout:
                                logstr = "socket Receive time out  "+str(sys.exc_info()) 
                                LogWrite(logfile,logstr)
                                sock = ''
                                return sock
                except :
                                logstr = "Socket Receive Error "+str(sys.exc_info())
                                LogWrite(logfile,logstr);
                                return recv_data
                return recv_data


def Send(sock, data,Port = 50007, IP = "172.16.7.37"):
                try:
                                sock.sendto(data, (IP, Port))
                except:
                                print "Socket Exception",sys.exc_info()

if __name__ == '__main__':        
        Size = 100;
        Port = 50007;
        IP = '0.0.0.0';
        filename = "test.txt";
        filemode = "w"; # default mode as 'write'
        SequenceNumber = 0;
        num = 0;
        flag = True;
        packetsize = 26; # 13bytes -> sync(F0) 1byte + size 2 byte + sequence number 2 byte + time stamp 2 bytes + x1 2bytes + x2 2bytes + y1 2bytes + y2 2bytes
        recvcount = 0;
        samplecount = 0;
        Initial = True
        Escape = False

        # Open files to store data and error
        try:
                        logfile = FileOpen("log.txt",filemode);
        except:
                        logfile = ""
                        print " Log File open error :",sys.exc_info()
                        print "Exiting the application"
                        time.sleep(1);
                        sys.stdin.close();
                        sys.exit(0);

        # Open socket 
        try:
                        sock = OpenSocket(Port,IP,logfile)
        except Exception,ex:
                        sock = ""

        if(sock == ""):
                        print "Exiting the application socket block"
                        time.sleep(1);
                        sys.stdin.close();
                        sys.exit(0);
        else:
                        print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
                        print "\t\t\tUDP TRANSFER TOOL\n"
                        print "UDP Port Number: 50007"
                        print "Version        : " + str(AppVersion)
                        print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"               
                        
                        
                        print "Press ESC to Stop Receiving Data"
                        try:                        
                                while True:
                                        
                                        if(Initial == True):                                                                                                
                                                # Get file name
                                                try:                                                        
                                                        while True:
                                                                UserFile = raw_input('Enter the File name : ');
                                                                if(UserFile != ""):
                                                                        break
                                                                else:
                                                                        continue                                                                
                                                                
                                                except:
                                                        print "\nQuitting ..."
                                                        CloseSocket(sock);
                                                        FileClose(file);
                                                        FileClose(logfile);  
                                                        time.sleep(2);
                                                        sys.stdin.close();
                                                        sys.exit(0);

                                                filename = UserFile;

                                                # Open files to store data and error
                                                try:
                                                                file = FileOpen(filename,filemode);
                                                except:
                                                                file = ""
                                                                logstr = "Data File open Error : "+str(sys.exc_info())
                                                                LogWrite(logfile,logstr);
                                                                
                                                if(file == ""):
                                                                print "Couldn't Open File. Exiting the application"
                                                                time.sleep(1);
                                                                sys.stdin.close();
                                                                sys.exit(0);
                                                Initial = False
                                        
                                        if msvcrt.kbhit():
                                                if ord(msvcrt.getch()) == 27:
                                                        Escape = True                                                        
                                        sys.stdout.write("\rReceived Packet Count: " +str(samplecount))
                                        #sys.stdout.write("\rSequence Number: "+str(num))
                                        if(Escape == False):
                                                
                                                ReceivedPkts = Receive(sock, Size,logfile);
                                                datasize = len(ReceivedPkts)

                                                if(datasize == 18):
                                                        recvdata,data1 = ReceivedPkts[:18],ReceivedPkts[18:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16)
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                sampledata = int(data1,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(sampledata)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))                                                            
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);
                                                                
                                                elif(datasize == 26):
                                                        recvdata,data1 = ReceivedPkts[:26],ReceivedPkts[26:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16) 
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                dataX1,data2 = data1[:8],data1[8:]
                                                                dataX2,data1 = data2[:8],data2[8:]
                                                                dataX1 = int(dataX1,16)
                                                                dataX2 = int(dataX2,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(dataX1)+"\t"+str(dataX2)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))                                                            
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);
                                                elif(datasize == 34):
                                                        recvdata,data1 = ReceivedPkts[:34],ReceivedPkts[34:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16) 
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                dataX1,data2 = data1[:8],data1[8:]
                                                                dataX2,data1 = data2[:8],data2[8:]
                                                                dataY1,data2 = data1[:8],data1[8:]
                                                                dataX1 = int(dataX1,16)
                                                                dataX2 = int(dataX2,16)
                                                                dataY1 = int(dataY1,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(dataX1)+"\t"+str(dataX2)+"\t"+str(dataY1)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))                                                            
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);                
                                                                
                                                elif(datasize == 42):
                                                        recvdata,data1 = ReceivedPkts[:42],ReceivedPkts[42:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16) 
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                dataX1,data2 = data1[:8],data1[8:]
                                                                dataX2,data1 = data2[:8],data2[8:]
                                                                dataY1,data2 = data1[:8],data1[8:]
                                                                dataY2,data1 = data2[:8],data2[8:]
                                                                dataX1 = int(dataX1,16)
                                                                dataX2 = int(dataX2,16)
                                                                dataY1 = int(dataY1,16)
                                                                dataY2 = int(dataY2,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(dataX1)+"\t"+str(dataX2)+"\t"+str(dataY1)+"\t"+str(dataY2)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))                                                            
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);
                                                elif(datasize == 50):
                                                        recvdata,data1 = ReceivedPkts[:50],ReceivedPkts[50:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16) 
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                dataX1,data2 = data1[:8],data1[8:]
                                                                dataX2,data1 = data2[:8],data2[8:]
                                                                dataY1,data2 = data1[:8],data1[8:]
                                                                dataY2,data1 = data2[:8],data2[8:]
                                                                dataX3,data2 = data1[:8],data1[8:]
                                                                dataX1 = int(dataX1,16)
                                                                dataX2 = int(dataX2,16)
                                                                dataY1 = int(dataY1,16)
                                                                dataY2 = int(dataY2,16)
                                                                dataX3 = int(dataX3,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(dataX1)+"\t"+str(dataX2)+"\t"+str(dataY1)+"\t"+str(dataY2)+"\t"+str(dataX3)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))                                                            
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);
                                                elif(datasize == 58):
                                                        recvdata,data1 = ReceivedPkts[:58],ReceivedPkts[58:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16) 
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                dataX1,data2 = data1[:8],data1[8:]
                                                                dataX2,data1 = data2[:8],data2[8:]
                                                                dataY1,data2 = data1[:8],data1[8:]
                                                                dataY2,data1 = data2[:8],data2[8:]
                                                                dataX3,data2 = data1[:8],data1[8:]
                                                                dataX4,data1 = data2[:8],data2[8:]
                                                                dataX1 = int(dataX1,16)
                                                                dataX2 = int(dataX2,16)
                                                                dataY1 = int(dataY1,16)
                                                                dataY2 = int(dataY2,16)
                                                                dataX3 = int(dataX3,16)
                                                                dataX4 = int(dataX4,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(dataX1)+"\t"+str(dataX2)+"\t"+str(dataY1)+"\t"+str(dataY2)+"\t"+str(dataX3)+"\t"+str(dataX4)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))                                                            
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);                  
                                                elif(datasize == 74):
                                                        recvdata,data1 = ReceivedPkts[:74],ReceivedPkts[74:]
                                                        ReceivedPkts = data1;
                                                        sync, data1 = recvdata[:2],recvdata[2:]
                                                        if (sync == "F0"): # checking SYNC
                                                                size, data2 = data1[:2],data1[2:]
                                                                seqnum = ""
                                                                seqnum, data1 = data2[:2],data2[2:]   
                                                                num = int(seqnum,16) 
                                                                sys.stdout.write("\rSequence Number: "+str(num))

                                                                data1 = recvdata[10:] # skip prefix 10
                                                                dataX1,data2 = data1[:8],data1[8:]
                                                                dataX2,data1 = data2[:8],data2[8:]
                                                                dataY1,data2 = data1[:8],data1[8:]
                                                                dataY2,data1 = data2[:8],data2[8:]
                                                                
                                                                dataX3,data2 = data1[:8],data1[8:]
                                                                dataX4,data1 = data2[:8],data2[8:]
                                                                dataY3,data2 = data1[:8],data1[8:]
                                                                dataY4,data1 = data2[:8],data2[8:]
                                                                dataX1 = int(dataX1,16)
                                                                dataX2 = int(dataX2,16)
                                                                dataY1 = int(dataY1,16)
                                                                dataY2 = int(dataY2,16)
                                                                dataX3 = int(dataX3,16)
                                                                dataX4 = int(dataX4,16)
                                                                dataY3 = int(dataY3,16)
                                                                dataY4 = int(dataY4,16)
                                                                samplecount = samplecount+1;
                                                                timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S')
                                                                seqdatastr = str(dataX1)+"\t"+str(dataX2)+"\t"+str(dataY1)+"\t"+str(dataY2)+"\t"+str(dataX3)+"\t"+str(dataX4)+"\t"+str(dataY3)+"\t"+str(dataY4)+"\t"+str(timestamp)+"\t"+str(num)+"\n"
                                                                FileWrite(file,seqdatastr);                                                               

                                                                sys.stdout.write("\rReceived Packet Count: "+str(samplecount))
                                                        else:
                                                                logstr = "Invalid Sync receviced"
                                                                LogWrite(logfile,logstr);
                                                                                                        
                                                else:
                                                        if(ReceivedPkts != ""):                                                       
                                                                
                                                                logstr = "Received pocket size less than 13bytes"
                                                                LogWrite(logfile,logstr);
                                        if(Escape == True):
                                                print "\nUDP files saved at :"
                                                print "\nRaw data      :",os.path.abspath(file.name)
                                                #print "\n\nError message :",os.path.abspath(logfile.name)
                                                print "\nPress Ctrl+C to Quit\n"
                                                FileClose(file);
                                                #FileClose(logfile);                                       
                                                Initial = True
                                                Escape = False
                                                samplecount = 0
                                                ReceivedPkts = ""
                                                                                        
                        except KeyboardInterrupt:
                                        print "\nKeyboard Interrupt"
                                        CloseSocket(sock);
                                        FileClose(file);
                                        FileClose(logfile); 

                                        time.sleep(2)
                                        sys.stdin.close();
                                        sys.exit(0);

