import thread, threading
import socket
import time


mylock = threading.Lock()  #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 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 >90):
                        #this tagID has not pinged for over 90 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 handler(clientsock,addr):
        BUFFER_SIZE = 256
        while 1:
                try:
                        data = clientsock.recv(BUFFER_SIZE)
                        if not data: continue
                        if len(data)<8:continue
                        for i in range(0,int(len(data)/8)):
                                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": continue
                                tagID =ord(data[i*8+4])
                                updateId(tagID)
                except clientsocket,e:
                        vc.triggerEvent("python.tcp.error",None)
                        continue
        clientsock.close()
        vc.triggerEvent("python.socket.thread.exit",None)



    
def myTCPserver(TCP_PORT):
    TCP_IP = ''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))
    s.listen(8)
    s.settimeout(2)
    while 1:
            
            try:
                    conn, addr = s.accept()
                    thread.start_new_thread(handler, (conn,addr))
            except timeout:
                    vc.triggerEvent("python.accept.timeout",None)
                    continue
    vc.triggerEvent("python.program.exit",None)
                    
            
        
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
    with mylock:
        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 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, (60,) )
