Paso 3: Etiquetas de Rfid
Para guardar la etiqueta de RFID utilizamos un archivo de texto simple. Con un script en Python vamos a leer la etiqueta y si el archivo contiene, grabamos una nueva fila en el archivo attendance.txt. Al mismo tiempo el script envía un mensaje para mostrar.
Crear un nuevo /home/pi/tag.txt archivo con algunas etiquetas
Crear un nuevo /home/pi/attendance.txt archivo donde guardaremos los movimientos de entrada y salidos
Crear el archivo /home/pi/rfid.py con este contenido
#!/usr/bin/env python #Basic imports from ctypes import * import sys import time import datetime import urllib2 import urllib #Phidget specific imports from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs, OutputChangeEventArgs, TagEventArgs from Phidgets.Devices.RFID import RFID, RFIDTagProtocol tagsList=list() tagStatus=list() with open('tag.txt') as f: tagsList = f.read().splitlines() for index in range(len(tagsList)): tagStatus.append(0) #Create an RFID object try: rfid = RFID() except RuntimeError as e: print("Runtime Exception: %s" % e.details) print("Exiting....") exit(1) #Information Display Function def displayDeviceInfo(): print("|------------|----------------------------------|--------------|------------|") print("|- Attached -|- Type -|- Serial No. -|- Version -|") print("|------------|----------------------------------|--------------|------------|") print("|- %8s -|- %30s -|- %10d -|- %8d -|" % (rfid.isAttached(), rfid.getDeviceName(), rfid.getSerialNum(), rfid.getDeviceVersion())) print("|------------|----------------------------------|--------------|------------|") print("Number of outputs: %i -- Antenna Status: %s -- Onboard LED Status: %s" % (rfid.getOutputCount(), rfid.getAntennaOn(), rfid.getLEDOn())) #Event Handler Callback Functions def rfidAttached(e): attached = e.device print("RFID %i Attached!" % (attached.getSerialNum())) def rfidDetached(e): detached = e.device print("RFID %i Detached!" % (detached.getSerialNum())) def rfidError(e): try: source = e.device print("RFID %i: Phidget Error %i: %s" % (source.getSerialNum(), e.eCode, e.description)) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) def rfidOutputChanged(e): source = e.device print("RFID %i: Output %i State: %s" % (source.getSerialNum(), e.index, e.state)) def rfidTagGained(e): source = e.device rfid.setLEDOn(1) try: if tagStatus[tagsList.index(e.tag)]==0: postdata="Welcome, have a good day" tagStatus[tagsList.index(e.tag)]=1 else: postdata="Hi, see you tomorrow" tagStatus[tagsList.index(e.tag)]=0 if e.tag in tagsList: query_args={'direction':postdata} url='http://localhost/web/message.php' user_agent = 'Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4' headers = { 'User-Agent' : user_agent } data=urllib.urlencode(query_args) request=urllib2.Request(url,data,headers) request.add_header('Referer', 'http://localhost/web/') response=urllib2.urlopen(request).read() now = datetime.datetime.now() fh = open("/home/pi/attendance.txt", "a") #fh.write(now.strftime('%s')) #fh.write(";{};{};\n".format( tagStatus[tagsList.index(e.tag)], e.tag )) fh.write("{};{};{};\n".format( now.strftime('%s'), tagStatus[tagsList.index(e.tag)], e.tag )) fh.close except ValueError: print("Error unknown tag %s" % (e.tag)) def rfidTagLost(e): source = e.device rfid.setLEDOn(0) time.sleep(2) postdata="Ready.." query_args={'direction':postdata} url='http://localhost/web/message.php' user_agent = 'Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4' headers = { 'User-Agent' : user_agent } data=urllib.urlencode(query_args) request=urllib2.Request(url,data,headers) request.add_header('Referer', 'http://localhost/web/') response=urllib2.urlopen(request).read() #Main Program Code try: rfid.setOnAttachHandler(rfidAttached) rfid.setOnDetachHandler(rfidDetached) rfid.setOnErrorhandler(rfidError) rfid.setOnOutputChangeHandler(rfidOutputChanged) rfid.setOnTagHandler(rfidTagGained) rfid.setOnTagLostHandler(rfidTagLost) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Opening phidget object....") try: rfid.openPhidget() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Waiting for attach....") try: rfid.waitForAttach(10000) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) try: rfid.closePhidget() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Exiting....") exit(1) else: displayDeviceInfo() print("Turning on the RFID antenna....") rfid.setAntennaOn(True) print("Press Enter to quit....") chr = sys.stdin.read(1) try: lastTag = rfid.getLastTag() print("Last Tag: %s" % (lastTag)) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Closing...") try: rfid.closePhidget() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Done.") exit(0)
Ejecutar el script
sudo python /home/pi/rfid.py
El lector de RFID se pone en espera, si acercarse a una etiqueta del monitor muestra un mensaje de bienvenida.
Al mismo tiempo la secuencia de comandos guardar una nueva fila en attendance.txt.
Una variable almacena el estado de esa etiqueta y acercarse nuevamente a la misma etiqueta mostrará un mensaje de felicitación a la salida