import thread, threading
import socket
import time


mylock = threading.RLock()  #used to make sure different threads don't access the dictionary at the same time
with open("pyLog.txt", "w") as myfile:
    myfile.write("Logging started:\n\n")


def InitTag(delay):
	global initflag
	initflag=0    
       	time.sleep(delay) 

	initflag=1
        vc.triggerEvent("RFID.Init.Done",None)

    
dictTimeStamps = {}  #dictionary to store time-stamps for each rfid


def updateId(ID):
    # This will update the timestamp (last seen time) for a given tagID to the current time.
    # If the stamp does not already exist it will be created and an arrival event will be sent to VC
    if (ID not in dictTimeStamps):        
        if (initflag==1):
		eventName='RFID.Arrival.%s' %(ID)
        	vc.triggerEvent(eventName,None)
	elif (initflag==0):
		eventName='RFID.Init.Arrival.%s' %(ID)
        	vc.triggerEvent(eventName,None)

    dictTimeStamps[ID]=time.time()


def trackStatus(delay):    
    while 1:
        time.sleep(delay) # pause between loops
        now = time.time()
        try:
            with mylock:  #make sure the other thread does not modify the dictionary while we are reading / deleting
                for ID, TS in dictTimeStamps.items():
                    elapsed = now - TS
                    if (elapsed >30):
                        #this tagID has not pinged for over 30 seconds so we and send a 'Departure' event to VC and then remove it from our dict
                        eventName='RFID.Departure.%s' %(ID)
                        vc.triggerEvent(eventName,None)                
                        del dictTimeStamps[ID]            
        except:
            print "python.trackstatus.error"
            vc.triggerEvent("python.trackstatus.error",None)
            continue
    
def myTCPserver(TCP_PORT):
    TCP_IP = ''
    BUFFER_SIZE = 8

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))

    while 1:
        try:
            s.listen(1)
            conn, addr = s.accept()
            #vc.triggerEvent("Connection is established after accept",None)
	    #print 'Connection address:', addr

            while 1:
		data = conn.recv(BUFFER_SIZE)                                
                if not data: break
		if len(data) < 8 : break
		
		for i in range(0,int(len(data)/8)):

	        	#eventName='RFID.Loop.%s' %(i)
        		#vc.triggerEvent(eventName,None)

			if data[i*8]!="\xFB" or data[i*8+1]!="\x10" or data[i*8+2]!="\x00" or data[i*8+3]!="\x00" or data[i*8+7]!="\x1F": break


                	strLog= "-".join("%02x" % ord(c) for c in data)
                	#vc.log("tcp data:"+strLog)
                	with open("pyLog.txt", "a") as myfile:
                    		myfile.write(strLog+"\n")
		
                                
			tagID =ord(data[i*8+4])
                	with mylock:
                    		updateId(tagID)

        except:
            print "python.tcp.error"
            vc.triggerEvent("python.tcp.error",None)
            continue
        conn.close()
        
def whoIsHome():    
    with mylock:  #make sure the other thread does not modify the dictionary while we are reading / deleting
        if (dictTimeStamps):
            strIDs = ', '.join('ID: {0}'.format(key) for key in dictTimeStamps.keys())
        else:
            strIDs = 'No one is home'
    return strIDs

thread.start_new_thread( myTCPserver, (3333,) )
thread.start_new_thread( trackStatus, (30,) )
thread.start_new_thread( InitTag, (30,) )
