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")
    
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 >30):
                        #this tagID has not pinged for over 20 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 = 256
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))
    while 1:
        try:
            s.listen(8)
            conn, addr = s.accept()
            print 'Connection address:', addr
            while 1:
                data = conn.recv(BUFFER_SIZE)                                
                if not data: break
                if len(data)!=8: break
                if data[0]!="\xFB": break                
                tagID =ord(data[4])
                updateId(tagID)
        except:
            #print "python.tcp.error"
            vc.triggerEvent("python.tcp.error",None)
            continue
        conn.close()
        
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):        
            eventName='RFID.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, (1000,) )
thread.start_new_thread( trackStatus, (30,) )

