import sys
import socket
import os
import time
import binascii
import sys, string, os
import thread
import array

UDP_IP = "0.0.0.0"
UDP_PORT = 50002
IP_Status = True
Host_IP = ""
AppVersion = 0.2

def OpenSocket(Port = 8002, IP = "localhost"):
        sock = ''
        try:
                sock = socket.socket(socket.AF_INET, # Internet
                socket.SOCK_DGRAM) # UDP
                sock.bind((IP, Port))
                sock.setblocking(0)
                sock.settimeout(60)
        except:
                 print " OpenSocket Exception ",sys.exc_info()
        return sock




def Receive(sock,size):
        recv_data = ""      # to return string object by default even if recvfrom is timedout and not returned any object/string for rec_data

        try:
                
                recv_data, recv_addr = sock.recvfrom(size)    # size <- if size < UDP Packet size, only the partial data copied and rest of data in UDP packet will be ignored/lost
                
        except:
                 print "Unable to send,Socket is not ready"

        return recv_data
         


def Send(sock, data =[],Port = 50001, IP = "localhost"):
   
    try:
        size = sock.sendto(data, (IP, Port))

    except:
         print "Unable to send,Socket is not ready"

    return size

def Get_IpAddress():

        global Host_IP
        while True:
                
                        
                                Host_IP = raw_input("Enter valid IP Address: ")
                                getIP = Host_IP.split('.')
                                if(len(getIP) == 4):
                                        break
                                  
        #if(Host_IP == ""):                
                #if(IP_Status):
                        #Host_IP = raw_input("Enter your Host IP Address: ")
               # else:
                       # Host_IP = raw_input("Enter valid Host IP Address: ")
                        
                #getIP = Host_IP.split('.')
##                print len(getIP)
                #if(len(getIP) != 4):
                        #IP_Status = False
                        #Get_IpAddress(IP_Status,"");
                        
                #else:
                       # print "Valid ip"
                        #print Host_IP
                        #return Host_IP
        #else:
                #return Host_IP  
                
        

def CloseSocket(sock):
        sock.close()
 
try:
        print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
        print "\t\t\t UDP CONTROLLER TOOL\n"
        print "UDP Port Number: " + str(UDP_PORT)
        print "Version        : " + str(AppVersion)
        print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
        print " READ :                       00 01 <reg address>           Ex:00 01 40 \n"
        print " WRITE:                       01 03 <reg address> <Value>   Ex:01 03 41 00 01 \n"
        print " PLAY:                        02 00                         Ex:02 00 \n"
        print " STOP:                        03 00                         Ex:03 00 \n"       
        print " RAW DATA:                    06 01 <ON/OFF>                Ex:06 01 01 (or) 06"
        print "                                                               01 00\n"
        print " CONNECT:                     0A 00                         Ex:0A 00 \n"
        print " DISCONNECT:                  0B 00                         Ex:0B 00 \n"
        print " OPENVIEW:                    0C 00                         Ex:0C 00 \n"
        print " LIST OF CONFIGURATION FILES: 0D 00                         Ex:0D 00 \n"
        print " LOADCONFIG:                  0D 01 <config file>           Ex:0D 01 01/02/..N \n"        
        print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
        
        
        sock = OpenSocket(UDP_PORT,UDP_IP)
        Get_IpAddress()
except Exception,ex:
        sock = ""
                    


while True:
        while True:
                input_var = raw_input("\nEnter Command: ")
                try:
                        if(input_var != ""):
                                split = input_var.split()
                                str_array = bytearray(len(split))
                                command = buffer(str_array)
                                
                                for i in range(len(split)):
                                        str_array[i] = int(split[i], 16)
                                command ="".join(command)
                                size = Send(sock,command,50001,Host_IP);
                                if size!= len(command) :
                                    print "UDP.Send ERROR"
                                break
                        else:
                                print "Invalid Command"
                except Exception,ex:
                        print "Error"        

        ReceivedPkts = Receive(sock,8192);
        if len(ReceivedPkts)>0 :
           Receiveddata = "";
           RegisterValue = "";
           Receiveddata1 = "";
           Receiveddata2 = "";
           Receiveddata1,Receiveddata2=ReceivedPkts[:3],ReceivedPkts[3:]           
           Receiveddata = ' '.join( [ "%02X" % ord( x ) for x in Receiveddata1 ] )
           arg1,arg2,arg3= Receiveddata.rstrip().split(' ')
           if(arg1 == "95"):
                   print "\nAvailable DCFG File\n",Receiveddata2
                   receivedfiles = Receiveddata2.split("\r\n")
                   #print "len = ",len(receivedfiles)
                   for i in range(len(receivedfiles)):
                        print ""+str(i+1)+" )"+receivedfiles[i]
                   print "Enter load config command with any of above choice as shown below..\n"
                   print "\tEg.,0D 01 <01/02/03...>choice\n"
                   print "Response Data",Receiveddata
           if(arg1 != "95"):
                   if len(Receiveddata2) == 2 and arg1 == "80":
                           RegisterValue = ' '.join( ["%02X" % ord( x ) for x in Receiveddata2 ] )
                           print "Response Data",Receiveddata,RegisterValue
                   else:
                           if len(Receiveddata2) > 0:
                                   print "Response Data",Receiveddata
                                   
                                   print "-----------------------"
                                   print "\n",Receiveddata2
                                   print "-----------------------"
                           else:
                                   print "Response Data",Receiveddata
           if(arg2=="00"):
                   print "Success"
           elif(arg2=="01"): 
                  print "Failure"           
           elif(arg2=="04"): 
                  print "No View is available"
           elif(arg2=="05"): 
                  print "Cannot Play, Already in Play state"
           elif(arg2=="06"):                   
                  print "Cannot Stop, Already in Stop state "
           elif(arg2=="07"):
                  print "Cannot Calibrate, Not in Stop state" 
           elif(arg2=="08"): 
                  print "Reset is must for clock calibration"
           elif(arg2=="09"): 
                  print "Not Applicable"
           elif(arg2=="0A"): 
                  print "Invalid Command"
           elif(arg2=="0B"): 
                  print "Already Connected"           
           elif(arg2=="0C"): 
                  print "Open Failed or View Already Opened"
           elif(arg2=="0D"): 
                  print "Load Configuration Failed"
           elif(arg2=="0E"): 
                  print "Invalid Parameter"           
           elif(arg2=="A0"):
                  print "Views Plugin removed or not found"
           elif(arg2=="B0"):
                  print "Load Configuration file not found or Invalid"
           elif(arg2=="C0"):
                  print "Failed..Please Connect the device."
##           elif(arg2=="D0"):
##                  print "\n\nEnter load config command with any of above choice as shown below..\n\n  Eg.,0D 01 (01/02/03...)choice "
           elif(arg2=="E0"):
                  print "Failed..No Config files available"
           elif(arg2=="F0"):
                  print "Failed..Connect device to Write/Read Register"
           elif(arg2=="1A"): 
                  print "Already Disconnected"
           elif(arg2=="1B"):
                  print "Load Configuration Failed, Not in Stop State"
           elif(arg2=="1C"):
                  print "Connection Failed, Target Hardware Not Found"

           Receiveddata = ""
           Receiveddata1 = ""
           Receiveddata2 = ""
        else :
            print "received message size is zero"
            continue


  

