-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrfid.py
215 lines (181 loc) · 6.75 KB
/
rfid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
import Adafruit_CharLCD as LCD
import time
import datetime
from bson.dbref import DBRef
from ConnectionDB import ConnectionDB
class RFID:
def __init__(self):
pass
@staticmethod
def save_in(mydb, id_user, dt):
entrada = {
"iEmpleado": [
DBRef(collection="empleados", id=id_user)
],
"horaEntrada": dt
}
entradas = mydb.entradas
entrada_id = entradas.insert_one(entrada).inserted_id
print("ID de la entrada: %s" % str(entrada_id))
@staticmethod
def save_out(mydb, id_user, dt):
salida = {
"iEmpleado": [
DBRef(collection="empleados", id=id_user)
],
"horaSalida": dt
}
salidas = mydb.salidas
salida_id = salidas.insert_one(salida).inserted_id
print("ID de la salida: %s" % str(salida_id))
@staticmethod
def get_user(mydb, id_card):
user = mydb.empleados.find_one(
{
"iTarjeta.$id": id_card
}
)
return user
@staticmethod
def get_card_id(mydb, serie):
card = mydb.tarjetas.find_one(
{
"serie": serie
}, {"serie": 0}
)
return card
@staticmethod
def check_entrance(mydb, id_user, today):
try:
check = list(mydb.entradas.find(
{
"iEmpleado.$id": id_user
}, {"horaEntrada": 1, "_id": 0}
).sort("horaEntrada", -1).limit(1))
yesterday = today - datetime.timedelta(1)
print "Ayer: %s" % yesterday
print "Entrada DB: %s" % check[0]["horaEntrada"]
print "Hoy: %s" % today
if check[0]["horaEntrada"].date() == today.date():
return True
else:
return False
except IndexError:
print "No hay registros de entrada"
return False
@staticmethod
def check_exit(mydb, id_user, today):
try:
check = list(mydb.salidas.find(
{
"iEmpleado.$id": id_user
}, {"horaSalida": 1, "_id": 0}
).sort("horaSalida", -1).limit(1))
print "Hora de salida: %s" % check[0]["horaSalida"]
if check[0]["horaSalida"] < today:
return True
else:
return False
except IndexError:
print "No hay registros de salida"
return False
@staticmethod
def get_id_inc(mydb, tpi):
idi = mydb.tipos_incidencias.find_one(
{
"nombre": tpi
}, {"nombre": 0}
)
return idi
@staticmethod
def save_incidence(mydb, id_user, today, idi):
incidence = {
"iEmpleado": [
DBRef(collection="empleados", id=id_user)
],
"idTIncidencia": [
DBRef(collection="tipos_incidencias", id=idi)
],
"fecha": today
}
incidencias = mydb.incidencias
inc_id = incidencias.insert_one(incidence).inserted_id
print("ID de la incidencia: %s" % str(inc_id))
def main():
test = RFID()
connection = ConnectionDB().con
db = connection.accesslogic
continue_reading = True
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal, frame):
global continue_reading
print "Ctrl+C capturado, Finalizando lectura."
continue_reading = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
reader = MFRC522.MFRC522()
# Configure the GPIOs of the LCD
lcd = LCD.Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=27, cols=16, lines=2)
# Clear de screen
lcd.clear()
# Welcome message
print "Bienvenido al ejemplo de lectura de tarjetas NFC"
print "Presiona Ctrl-C para cerrar"
time.sleep(1)
print "Listo!"
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
# Scan for cards
(status, TagType) = reader.MFRC522_Request(reader.PICC_REQIDL)
# If a card is found
if status == reader.MI_OK:
print "Tarjeta detectada"
# Get the UID of the card
(status, uid) = reader.MFRC522_Anticoll()
# If we have the UID, continue
if status == reader.MI_OK:
# Print UID in the LCD
seriec = str(uid[0]) + "," + str(uid[1]) + "," + str(uid[2]) + "," + str(uid[3])
# print seriec
idc = test.get_card_id(db, seriec)
print idc['_id']
usuario = test.get_user(db, idc['_id'])
time_now = datetime.datetime.now()
ontime = datetime.datetime.replace(time_now, hour=16, minute=00, second=00, microsecond=0)
retardo = datetime.datetime.replace(time_now, hour=16, minute=02, second=00, microsecond=0)
salida = datetime.datetime.replace(time_now, hour=16, minute=05, second=00, microsecond=0)
if test.check_entrance(db, usuario['_id'], time_now):
if time_now >= salida:
if test.check_exit(db, usuario['_id'], time_now):
lcd.message("Ya checaste\nsalida")
else:
lcd.message("Hasta pronto\n" + usuario['nombre'] + " " + usuario['apPaterno'])
test.save_out(db, usuario['_id'], time_now)
else:
lcd.message("Aun no es hora \nde salida")
else: # Es entrada
if time_now <= ontime:
lcd.message(" Bienvenido:\n" + usuario['nombre'] + " " + usuario['apPaterno'])
test.save_in(db, usuario['_id'], time_now)
elif (time_now <= retardo) and (time_now > ontime):
lcd.message("Tienes retardo:\n" + usuario['nombre'] + " " + usuario['apPaterno'])
idi = test.get_id_inc(db, "Retardo")
test.save_in(db, usuario['_id'], time_now)
test.save_incidence(db, usuario['_id'], time_now, idi['_id'])
elif time_now >= retardo:
lcd.message("Llegas tarde:\n" + usuario['nombre'] + " " + usuario['apPaterno'])
idi = test.get_id_inc(db, "Falta")
test.save_in(db, usuario['_id'], time_now)
test.save_incidence(db, usuario['_id'], time_now, idi['_id'])
# Clear de screen
time.sleep(4)
lcd.clear()
if __name__ == "__main__":
main()