-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUrity-Arduino.ino
271 lines (220 loc) · 6.78 KB
/
Urity-Arduino.ino
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
//Arduino Libraries
#include <Arduino.h>
#include <SPI.h>
#include <MFRC522.h>
//Wifi Libraries
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
//Web Libraries
#include <ArduinoJson.h>
#include <SocketIOclient.h>
//Password Libraries
#include "page.h"
/*#ifdef DEBUG_ESP_PORT
#define DEBUG_MSG(...) DEBUG_ESP_PORT( __VA_ARGS__)
#else
#define DEBUG_MSG(...)
#endif
#define DEBUG_ESP_PORT Serial*/
//RC522 pins
const uint8_t RST_PIN = 27;
const uint8_t SS_PIN = 5;
//Chapa Pin
const uint8_t chapa = 13;
//Piezo Pin
//const uint8_t piezo = 33
//Variables
String lecturaUID = "";
bool rfidStatus = false;
bool chapaStatus = false;
unsigned long beforeRead = 0;
unsigned long beforeDoor = 0;
//Constantes
const int TiempoEsperaWifi = 5000;
const long chapaTime = 4000000;
const int intervalRFID = 3000;
//Objects
MFRC522 mfrc522(SS_PIN, RST_PIN);
WiFiMulti wifiMulti;
WebSocketsClient webSocket;
SocketIOclient socketIO;
//Functions
void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length);
void hexdump(const void *mem, uint32_t len, uint8_t cols = 16);
void readRFID();
String almacenarUID();
void sendMessage();
void receiveMessege(uint8_t* payload, size_t length);
//Serial mode
#define USE_SERIAL Serial
void setup() {
USE_SERIAL.begin(115200);
USE_SERIAL.setDebugOutput(true);
//Internet Conexions
wifiMulti.addAP(ssid_1, password_1);
wifiMulti.addAP(ssid_2, password_2);
wifiMulti.addAP(ssid_3, password_3);
WiFi.mode(WIFI_STA);
Serial.print("Conectando a Wifi...");
int conecctionTry = 0;
while (wifiMulti.run(TiempoEsperaWifi) != WL_CONNECTED && conecctionTry < 10){
USE_SERIAL.print(".");
conecctionTry++;
}
if (WiFi.status() == WL_CONNECTED)
{
USE_SERIAL.println("Conectado exitosamente");
USE_SERIAL.print("SSID: ");
USE_SERIAL.print(WiFi.SSID());
USE_SERIAL.print("IP: ");
USE_SERIAL.println(WiFi.localIP());
}else{
USE_SERIAL.println("No se pudo conectar a Wifi, verifique sus credenciales");
return;
}
//socket ip conexion
socketIO.setExtraHeaders("Authorization: 1234567890");
socketIO.begin("192.168.100.26", 3000, "/socket.io/?EIO=4");
// event handler
socketIO.onEvent(socketIOEvent);
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("user", "Password");
// try ever 5000 again if connection has failed
//webSocket.setReconnectInterval(5000);
pinMode(chapa, OUTPUT);
digitalWrite(chapa, LOW);
SPI.begin();
mfrc522.PCD_Init();
USE_SERIAL.println("Setup Done");
}
void loop() {
socketIO.loop();
if (chapaStatus) {
digitalWrite(chapa, HIGH);
}
readRFID();
unsigned long currentMillis = micros();
if (currentMillis - beforeDoor >= chapaTime) {
digitalWrite(chapa, LOW);
chapaStatus = false;
mfrc522.PCD_Init();
beforeDoor = currentMillis;
}
}
/*------------FUNCTIONS---------------*/
//WebsocketIO function
void socketIOEvent(socketIOmessageType_t type, uint8_t* payload, size_t length) {
switch(type){
case sIOtype_DISCONNECT:
Serial.printf("[IOc] Disconnected!\n");
break;
case sIOtype_CONNECT:
Serial.printf("[IOc] Connected to url: %s\n", payload);
// join default namespace (no auto join in Socket.IO V3)
socketIO.send(sIOtype_CONNECT, "/");
break;
case sIOtype_EVENT:
receiveMessege(payload, length);
break;
case sIOtype_ACK:
Serial.printf("[IOc] get ack: %u\n", length);
hexdump(payload, length);
break;
case sIOtype_ERROR:
Serial.printf("[IOc] get error: %u\n", length);
hexdump(payload, length);
break;
case sIOtype_BINARY_EVENT:
Serial.printf("[IOc] get binary: %u\n", length);
hexdump(payload, length);
break;
case sIOtype_BINARY_ACK:
Serial.printf("[IOc] get binary ack: %u\n", length);
hexdump(payload, length);
break;
}
}
void hexdump(const void *mem, uint32_t len, uint8_t cols) {
const uint8_t* src = (const uint8_t*) mem;
USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
for(uint32_t i = 0; i < len; i++) {
if(i % cols == 0) {
USE_SERIAL.printf("\n[0x%0hola8X] 0x%08X: ", (ptrdiff_t)src, i);
}
USE_SERIAL.printf("%02X ", *src);
src++;
}
USE_SERIAL.printf("\n");
}
void readRFID() {
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()){
if (millis() - beforeRead > intervalRFID){
beforeRead = millis();
lecturaUID = almacenarUID();
sendMessage();
lecturaUID = "";
mfrc522.PICC_HaltA();
}
}
}
//Read NFC card Function
String almacenarUID() {
String variableUID;
Serial.println("\nUID:"); // Utiliza println para imprimir una nueva línea automáticamente
for (byte i = 0; i < mfrc522.uid.size; i++) {
// Utiliza operador ternario para agregar '0' si es necesario
String hexByte = String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "") + String(mfrc522.uid.uidByte[i], HEX);
hexByte.toUpperCase(); // Convierte a mayúsculas antes de agregar a variableUID
Serial.print(" "); // Imprime un espacio en blanco
Serial.print(hexByte); // Imprime el byte del UID leido en hexadecimal
variableUID += hexByte; // Almacena en String el byte del UID leido
}
return variableUID; // Retorna la variableUID ya convertida a mayúsculas
}
void sendMessage(){
Serial.println("\nSe enviara un JSON a Node.js con la siguiente información: ");
Serial.println(lecturaUID);
// creat JSON message for Socket.IO (event)
JsonDocument doc;
JsonArray array = doc.to<JsonArray>();
// add event namer
// Hint: socket.on('event_name', ....
array.add("event_name");
// add payload (parameters) for the event
JsonObject param1 = array.createNestedObject();
param1["UID"] = lecturaUID;
// JSON to String (serializion)
String output;
serializeJson(doc, output);
// Send event
socketIO.sendEVENT(output);
// Print JSON for debugging
Serial.println(output);
}
void receiveMessege(uint8_t* payload, size_t length){
char* sptr = NULL;
int id = strtol((char*)payload, &sptr, 10);
USE_SERIAL.printf("[IOc] get event: %s id: %d\n", payload, id);
if(id){
payload = (uint8_t *)sptr;
}
JsonDocument doc;
DeserializationError err = deserializeJson(doc, payload, length);
if(err) {
USE_SERIAL.print(F("deserializeJson() failed: "));
USE_SERIAL.println(err.c_str());
return;
}
// Acceder a los valores
const char* nameEvent = doc[0]; // "UID"
Serial.println(nameEvent);
JsonObject persona = doc[1];
//long Codigo = persona["Codigo"];
//const char* UID_persona = persona["UID"];
//const char* Nombre = persona["Nombre"];
//int Ubicacion = persona["Ubicacion"];
//const char* DatoAcademico = persona["DatoAcademico"];
//int Estatus = persona["Estatus"];
chapaStatus = persona["Estatus"];
}