forked from SH-Nihil-Mukkesh-25/Vaultify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhardware_code.ino
More file actions
548 lines (487 loc) · 16.5 KB
/
hardware_code.ino
File metadata and controls
548 lines (487 loc) · 16.5 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <MPU6050_light.h>
#include <SPI.h>
#include <MFRC522.h>
#include <ESP32Servo.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <base64.h>
#include "secrets.h" // <-- Include secrets here
// -------------------- PIN ASSIGNMENTS --------------------
#define BUZZER_PIN 25
#define SERVO_PIN 26
#define I2C_SDA_PIN 21
#define I2C_SCL_PIN 22
#define RFID_SS_PIN 5
#define RFID_RST_PIN 4
// -------------------- CONFIG --------------------
#define SERVO_LOCKED_POS 70
#define SERVO_UNLOCKED_POS 160
#define ACCEL_THRESHOLD 0.6
#define DOOR_AUTO_CLOSE 120000
#define ALARM_DURATION 120000
// -------------------- OBJECTS --------------------
LiquidCrystal_I2C lcd(0x27,16,2);
MPU6050 mpu(Wire);
MFRC522 rfid(RFID_SS_PIN, RFID_RST_PIN);
Servo doorServo;
// -------------------- STATES --------------------
bool alarmActive = false;
bool theftLockActive = false;
unsigned long alarmStartTime = 0;
bool doorOpen = false;
unsigned long doorOpenTime = 0;
// -------------------- VALID CARDS --------------------
byte validCards[][4] = {
{0x3D, 0xF3, 0x3B, 0x06},
{0x6C, 0x82, 0x8C, 0x00}
};
const int NUM_VALID_CARDS = sizeof(validCards) / sizeof(validCards[0]);
// -------------------- BUZZER --------------------
unsigned long lastBeepTime = 0;
bool buzzerState = false;
// -------------------- HELPERS --------------------
void shortBeep(int times){
for(int i=0;i<times;i++){
tone(BUZZER_PIN,2500);
delay(150);
noTone(BUZZER_PIN);
delay(150);
}
}
String urlencode(const String &str) {
String encoded = "";
char c;
char buf[4];
for (size_t i = 0; i < str.length(); i++) {
c = str.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
c == '-' || c == '_' || c == '.' || c == '~') encoded += c;
else if (c == ' ') encoded += '+';
else { sprintf(buf, "%%%02X", (unsigned char)c); encoded += buf; }
}
return encoded;
}
// -------------------- SMS --------------------
void sendSms(String msg){
if(WiFi.status() != WL_CONNECTED) return;
HTTPClient http;
String url = "https://api.twilio.com/2010-04-01/Accounts/" + TWILIO_ACCOUNT_SID + "/Messages.json";
http.begin(url);
String basicAuth = base64::encode(TWILIO_ACCOUNT_SID + ":" + TWILIO_AUTH_TOKEN);
http.addHeader("Authorization", "Basic " + basicAuth);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String body = "To=" + DEST_PHONE + "&From=" + TWILIO_FROM_NUMBER + "&Body=" + urlencode(msg);
http.POST(body);
http.end();
}
// -------------------- BACKEND LOGGING --------------------
void sendToBackend(String eventType, String detail){
if(WiFi.status() != WL_CONNECTED){
Serial.println("WiFi not connected, skipping backend log");
return;
}
HTTPClient http;
http.begin(BACKEND_URL + "/api/logs");
http.addHeader("Content-Type","application/json");
String payload = "{\"event\":\""+eventType+"\",\"detail\":\""+detail+"\"}";
http.setTimeout(5000); // 5 second timeout
int httpCode = http.POST(payload);
if(httpCode > 0){
Serial.printf("Backend responded: %d\n", httpCode);
if(httpCode == 200){
Serial.println("Log sent successfully");
}
} else {
Serial.printf("Backend request failed: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
// -------------------- LCD --------------------
void updateLcdDisplay(){
lcd.clear();
if(alarmActive){
lcd.setCursor(0,0); lcd.print("!!! THEFT ALERT !!!");
lcd.setCursor(0,1); lcd.print("Door Locked!");
} else if(doorOpen){
lcd.setCursor(0,0); lcd.print("Door is Unlocked");
unsigned long timeLeft = (DOOR_AUTO_CLOSE-(millis()-doorOpenTime))/1000;
lcd.setCursor(0,1); lcd.print("Auto-Lock in "); lcd.print(timeLeft); lcd.print("s");
} else {
lcd.setCursor(0,0); lcd.print("System Normal");
lcd.setCursor(0,1); lcd.print("Door is Locked");
}
}
// -------------------- LOGIC --------------------
void handleMotionSensor(){
mpu.update();
float acc = sq(mpu.getAccX()) + sq(mpu.getAccY());
if(acc > sq(ACCEL_THRESHOLD) && !alarmActive){
alarmActive = true;
theftLockActive = true;
alarmStartTime = millis();
doorServo.write(SERVO_LOCKED_POS);
doorOpen = false;
updateLcdDisplay();
sendSms("ALERT: Theft detected!");
sendToBackend("motion_alert","Possible intrusion detected");
}
}
void handleRfidReader(){
if(rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()){
bool valid = false;
for(int i=0;i<NUM_VALID_CARDS;i++){
if(rfid.uid.size==sizeof(validCards[i]) &&
memcmp(rfid.uid.uidByte, validCards[i], sizeof(validCards[i]))==0) { valid=true; break; }
}
if(valid){
shortBeep(1);
if(alarmActive && theftLockActive){
alarmActive = false; theftLockActive = false;
lcd.clear(); lcd.setCursor(0,0); lcd.print("Theft Alarm Off"); delay(1500);
sendSms("Theft alarm deactivated.");
sendToBackend("rfid_valid","Theft alarm deactivated");
} else if(!theftLockActive){
doorOpen = !doorOpen;
if(doorOpen){
doorServo.write(SERVO_UNLOCKED_POS);
doorOpenTime=millis();
sendSms("Door unlocked.");
sendToBackend("door_unlocked","RFID authorized");
} else {
doorServo.write(SERVO_LOCKED_POS);
sendSms("Door locked.");
sendToBackend("door_locked","RFID authorized");
}
}
} else {
shortBeep(3);
lcd.clear(); lcd.setCursor(0,0); lcd.print("Access Denied!");
sendSms("ALERT: Invalid RFID attempt!");
sendToBackend("rfid_invalid","Unauthorized card scanned");
delay(2000);
}
updateLcdDisplay();
rfid.PICC_HaltA(); rfid.PCD_StopCrypto1();
}
}
void handleAlarmState(){
if(alarmActive){
unsigned long current = millis();
if(buzzerState && (current - lastBeepTime >= 1000)){ noTone(BUZZER_PIN); buzzerState=false; lastBeepTime=current; }
else if(!buzzerState && (current - lastBeepTime >= 100)){ tone(BUZZER_PIN,3000); buzzerState=true; lastBeepTime=current; }
} else { noTone(BUZZER_PIN); buzzerState=false; }
}
void handleDoorState(){
if(doorOpen && (millis()-doorOpenTime > DOOR_AUTO_CLOSE)){
doorServo.write(SERVO_LOCKED_POS); doorOpen=false;
sendSms("Door auto-locked.");
sendToBackend("door_autolock","Auto-lock executed");
updateLcdDisplay();
}
}
// -------------------- SETUP --------------------
void setup(){
Serial.begin(115200);
Wire.begin(I2C_SDA_PIN,I2C_SCL_PIN);
lcd.init(); lcd.backlight(); lcd.setCursor(0,0); lcd.print("System Booting...");
delay(1500);
WiFi.begin(WIFI_SSID,WIFI_PASS); lcd.setCursor(0,1); lcd.print("Connecting Wi-Fi...");
while(WiFi.status()!=WL_CONNECTED){ delay(500); Serial.print("."); }
lcd.setCursor(0,1); lcd.print("Wi-Fi Connected ");
doorServo.attach(SERVO_PIN); doorServo.write(SERVO_LOCKED_POS);
if(mpu.begin()!=0){ lcd.clear(); lcd.setCursor(0,0); lcd.print("MPU-6050 ERROR!"); while(1); }
mpu.calcOffsets();
SPI.begin(); rfid.PCD_Init();
updateLcdDisplay();
Serial.println("System Ready.");
}
// -------------------- LOOP --------------------
unsigned long lastLcdUpdate = 0;
const long LCD_UPDATE_INTERVAL = 1000; // Update every 1 second
void loop(){
handleMotionSensor();
handleRfidReader();
handleAlarmState();
handleDoorState();
// Only update LCD every second
if(millis() - lastLcdUpdate > LCD_UPDATE_INTERVAL){
updateLcdDisplay();
lastLcdUpdate = millis();
}
}
// old v1 code 👇
// #include <Arduino.h>
// #include <Wire.h>
// #include <LiquidCrystal_I2C.h>
// #include <MPU6050_light.h>
// #include <SPI.h>
// #include <MFRC522.h>
// #include <ESP32Servo.h>
// #include <WiFi.h>
// #include <HTTPClient.h>
// #include <base64.h> // For Basic Auth
// // -------------------- PIN ASSIGNMENTS --------------------
// #define BUZZER_PIN 25
// #define SERVO_PIN 26
// #define I2C_SDA_PIN 21
// #define I2C_SCL_PIN 22
// #define RFID_SS_PIN 5
// #define RFID_RST_PIN 4
// // -------------------- CONFIG --------------------
// #define SERVO_LOCKED_POS 70
// #define SERVO_UNLOCKED_POS 160
// #define ACCEL_THRESHOLD 0.6
// // -------------------- WIFI --------------------
// const char* ssid = "YOUR_WIFI_SSID"; // <-- Fill your Wi-Fi SSID
// const char* password = "YOUR_WIFI_PASS"; // <-- Fill your Wi-Fi Password
// // -------------------- TWILIO --------------------
// const String TWILIO_ACCOUNT_SID = "YOUR_TWILIO_SID"; // <-- Fill Twilio Account SID
// const String TWILIO_AUTH_TOKEN = "YOUR_TWILIO_TOKEN"; // <-- Fill Twilio Auth Token
// const String DEST_PHONE = "+91XXXXXXXXXX"; // <-- Fill destination phone number
// const String TWILIO_FROM_NUMBER = "+1XXXXXXXXXX"; // <-- Fill Twilio phone number
// // -------------------- OBJECTS --------------------
// LiquidCrystal_I2C lcd(0x27,16,2);
// MPU6050 mpu(Wire);
// MFRC522 rfid(RFID_SS_PIN, RFID_RST_PIN);
// Servo doorServo;
// // -------------------- STATES & TIMERS --------------------
// bool alarmActive = false;
// bool theftLockActive = false; // door locked due to theft
// unsigned long alarmStartTime = 0;
// const unsigned long ALARM_DURATION = 120000;
// bool doorOpen = false;
// unsigned long doorOpenTime = 0;
// const unsigned long DOOR_AUTO_CLOSE = 120000;
// // -------------------- VALID CARDS --------------------
// byte validCards[][4] = {
// {0x3D, 0xF3, 0x3B, 0x06}, // <-- Example card 1
// {0x6C, 0x82, 0x8C, 0x00} // <-- Example card 2
// };
// const int NUM_VALID_CARDS = sizeof(validCards) / sizeof(validCards[0]);
// // -------------------- BUZZER TIMING --------------------
// unsigned long lastBeepTime = 0;
// bool buzzerState = false; // ON/OFF
// // -------------------- HELPERS --------------------
// void shortBeep(int times){
// for(int i=0;i<times;i++){
// tone(BUZZER_PIN,2500);
// delay(150);
// noTone(BUZZER_PIN);
// delay(150);
// }
// }
// String urlencode(const String &str) {
// String encoded = "";
// char c;
// char buf[4];
// for (size_t i = 0; i < str.length(); i++) {
// c = str.charAt(i);
// if ((c >= '0' && c <= '9') ||
// (c >= 'a' && c <= 'z') ||
// (c >= 'A' && c <= 'Z') ||
// c == '-' || c == '_' || c == '.' || c == '~') {
// encoded += c;
// } else if (c == ' ') {
// encoded += '+';
// } else {
// sprintf(buf, "%%%02X", (unsigned char)c);
// encoded += buf;
// }
// }
// return encoded;
// }
// // -------------------- SMS FUNCTION WITH RETRY --------------------
// const int MAX_RETRIES = 3;
// const int RETRY_DELAY = 5000; // ms
// void sendSms(String msg){
// if(WiFi.status() != WL_CONNECTED){
// Serial.println("WiFi not connected - cannot send SMS");
// return;
// }
// int attempt = 0;
// bool sent = false;
// while(attempt < MAX_RETRIES && !sent){
// attempt++;
// HTTPClient http;
// String url = "https://api.twilio.com/2010-04-01/Accounts/" + TWILIO_ACCOUNT_SID + "/Messages.json";
// http.begin(url);
// String basicAuth = base64::encode(TWILIO_ACCOUNT_SID + ":" + TWILIO_AUTH_TOKEN);
// http.addHeader("Authorization", "Basic " + basicAuth);
// http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// String body = "To=" + DEST_PHONE + "&From=" + TWILIO_FROM_NUMBER + "&Body=" + urlencode(msg);
// int httpCode = http.POST(body);
// if(httpCode > 0){
// Serial.print("HTTP code: "); Serial.println(httpCode);
// String response = http.getString();
// Serial.println("Response: " + response);
// sent = true;
// } else {
// Serial.print("HTTP POST failed, attempt "); Serial.print(attempt); Serial.print(", error: "); Serial.println(httpCode);
// delay(RETRY_DELAY);
// }
// http.end();
// }
// if(!sent){
// Serial.println("Failed to send SMS after multiple attempts!");
// }
// }
// // -------------------- LCD --------------------
// void updateLcdDisplay(){
// lcd.clear();
// if(alarmActive){
// lcd.setCursor(0,0);
// lcd.print("!!! THEFT ALERT !!!");
// lcd.setCursor(0,1);
// lcd.print("Door Locked!");
// } else if(doorOpen){
// lcd.setCursor(0,0);
// lcd.print("Door is Unlocked");
// unsigned long timeLeft = (DOOR_AUTO_CLOSE-(millis()-doorOpenTime))/1000;
// lcd.setCursor(0,1);
// lcd.print("Auto-Lock in ");
// lcd.print(timeLeft);
// lcd.print("s");
// } else {
// lcd.setCursor(0,0);
// lcd.print("System Normal");
// lcd.setCursor(0,1);
// lcd.print("Door is Locked");
// }
// }
// // -------------------- LOGIC HANDLERS --------------------
// void handleMotionSensor(){
// mpu.update();
// float acc = sq(mpu.getAccX()) + sq(mpu.getAccY());
// if(acc > sq(ACCEL_THRESHOLD) && !alarmActive){
// alarmActive = true;
// theftLockActive = true; // Door locked due to theft
// alarmStartTime = millis();
// Serial.println("Theft detected!");
// updateLcdDisplay();
// sendSms("ALERT: Theft detected!");
// doorServo.write(SERVO_LOCKED_POS);
// doorOpen = false;
// }
// }
// void handleRfidReader(){
// if(rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()){
// bool valid = false;
// // compare against all valid cards
// for(int i=0; i<NUM_VALID_CARDS; i++){
// if(rfid.uid.size == sizeof(validCards[i]) &&
// memcmp(rfid.uid.uidByte, validCards[i], sizeof(validCards[i])) == 0){
// valid = true;
// break;
// }
// }
// if(valid){
// Serial.println("Valid card.");
// shortBeep(1);
// if(alarmActive && theftLockActive){
// // Only deactivate theft alarm, DO NOT open door immediately
// alarmActive = false;
// theftLockActive = false;
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print("Theft Alarm Off");
// delay(1500);
// sendSms("Theft alarm deactivated.");
// } else if(!theftLockActive){
// // Normal door toggle
// doorOpen = !doorOpen;
// if(doorOpen){
// doorServo.write(SERVO_UNLOCKED_POS);
// doorOpenTime = millis();
// Serial.println("Door Unlocked.");
// sendSms("Door unlocked.");
// } else {
// doorServo.write(SERVO_LOCKED_POS);
// Serial.println("Door Locked.");
// sendSms("Door locked.");
// }
// }
// } else {
// Serial.println("Invalid card.");
// shortBeep(3);
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print("Access Denied!");
// sendSms("ALERT: Invalid RFID attempt!");
// delay(2000);
// }
// updateLcdDisplay();
// rfid.PICC_HaltA();
// rfid.PCD_StopCrypto1();
// }
// }
// void handleAlarmState(){
// if(alarmActive){
// unsigned long current = millis();
// if(buzzerState && (current - lastBeepTime >= 1000)){ // ON for 1000ms
// noTone(BUZZER_PIN);
// buzzerState = false;
// lastBeepTime = current;
// } else if(!buzzerState && (current - lastBeepTime >= 100)){ // OFF for 100ms
// tone(BUZZER_PIN, 3000); // 3kHz
// buzzerState = true;
// lastBeepTime = current;
// }
// } else {
// noTone(BUZZER_PIN);
// buzzerState = false;
// }
// }
// void handleDoorState(){
// if(doorOpen && (millis()-doorOpenTime > DOOR_AUTO_CLOSE)){
// doorServo.write(SERVO_LOCKED_POS);
// doorOpen = false;
// Serial.println("Door auto-locked.");
// sendSms("Door auto-locked.");
// updateLcdDisplay();
// }
// }
// // -------------------- SETUP --------------------
// void setup(){
// Serial.begin(115200);
// Wire.begin(I2C_SDA_PIN,I2C_SCL_PIN);
// lcd.init();
// lcd.backlight();
// lcd.setCursor(0,0);
// lcd.print("System Booting...");
// delay(1500);
// WiFi.begin(ssid,password);
// lcd.setCursor(0,1);
// lcd.print("Connecting Wi-Fi...");
// while(WiFi.status()!=WL_CONNECTED){
// delay(500);
// Serial.print(".");
// }
// Serial.println("Wi-Fi Connected");
// lcd.setCursor(0,1);
// lcd.print("Wi-Fi Connected ");
// doorServo.attach(SERVO_PIN);
// doorServo.write(SERVO_LOCKED_POS);
// if(mpu.begin()!=0){
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print("MPU-6050 ERROR!");
// Serial.println("MPU-6050 NOT connected!");
// while(1);
// }
// mpu.calcOffsets();
// SPI.begin();
// rfid.PCD_Init();
// updateLcdDisplay();
// Serial.println("System Ready.");
// }
// // -------------------- MAIN LOOP --------------------
// void loop(){
// handleMotionSensor();
// handleRfidReader();
// handleAlarmState();
// handleDoorState();
// updateLcdDisplay();
// }