import bluetooth
import os
import time
import codecs

def bloquea():
    winpath=os.environ['windir']
    os.system(winpath + '\system32\\rundll32 user32.dll, LockWorkStation')


file = 'config.txt'
logfile = 'bluelog.txt'

infile = open(file,"r")
outfile = open(logfile,"a")

dump = infile.readline()

#print "%s" % (dump) 

#print "performing inquiry..."


initial_devices = bluetooth.discover_devices(lookup_names=True,duration=18, flush_cache=True)

#print initial_devices 

btinicial = []

btruntime = []

now = time.ctime()
    
print >> outfile, "%s Dispositivos localizados:" % (now)
outfile.flush()


for addr, name in initial_devices:
    
    name.encode
    
    print >> outfile, "%s %s" % (addr, name)
    outfile.flush()
    
    btinicial.append(addr)

while 1:

    nearby_devices = bluetooth.discover_devices(lookup_names=True,duration=18, flush_cache=True)

    cond = 0 
    
    btruntime = []
    
    for addr, name in nearby_devices:
    
        #print "%s %s" % (addr, name)
        
        btruntime.append(addr)
        
        if addr not in btinicial:
            
            namedevice = bluetooth.lookup_name( addr, timeout=10 )
            now = time.ctime()
            
            out = namedevice.encode('utf-8', "ignore")

            print "%s Nueva Device encontrada %s %s" % (now, addr, out)
            
            print >> outfile, "%s Nueva Device encontrada %s %s" % (now, addr, out)
            outfile.flush()
        
        if addr == dump:
        
            cond = 1
        
            services = bluetooth.find_service(address=addr)
            if len(services) < 1:
                
                cond = 0
    
    for addr in btinicial:
        
        if addr not in btruntime:
            
            now = time.ctime()
            print "%s Device %s fuera de alcance" % (now, addr)
            print >> outfile, "%s Device %s fuera de alcance" % (now, addr)
            outfile.flush()
            
    del (btinicial)
    btinicial = btruntime
    
    if cond == 0:
    
        bloquea()
    
    time.sleep(2)
