#include <ESP32Servo.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define ROW_NUM 4
#define COLUMN_NUM 4
char keys[ROW_NUM][COLUMN_NUM] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte pin_rows[ROW_NUM] = {19, 18, 5, 17};
byte pin_column[COLUMN_NUM] = {16, 4, 0, 2};
Keypad keypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
Servo myServo1; // Create a servo object
Servo myServo2;
Servo myServo3;
String inputString = ""; // String to hold the input from the keypad
const int buttonPin = 12; // Pin for the button
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
const char* ssid = "HCMUS-Thuvien"; // Replace with your Wi-Fi SSID
const char* password = "123456789"; // Replace with your Wi-Fi password
const char* lockPasswordEndpoint = "http://192.168.1.103:5000/user/current-lock-password"; // Endpoint to fetch current lock password
String currentLockPassword = "";
//Flow code
void setup() {
Serial.begin(115200);
myServo1.attach(25); // Attach the 1st servo to pin 25
myServo2.attach(26); // Attach the 2nd servo to pin 26
myServo3.attach(27); // Attach the 3rd servo to pin 27
pinMode(buttonPin, INPUT_PULLDOWN); // Set the button pin as input with pull-down resistor
// Initialize I2C communication with default pins (SDA = GPIO 21, SCL = GPIO 22)
Wire.begin(21, 22); // SDA = GPIO 21, SCL = GPIO 22
// Initialize the LCD
lcd.init(); // Initialize the LCD
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("ESP32 IP Address: ");
Serial.println(WiFi.localIP());
fetchLockPassword();
}
void loop() {
char key = keypad.getKey();
if (key) {
inputString += key; // Add the key to the input string
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Input: ");
lcd.print(inputString);
}
// Check if the button is pressed
if (digitalRead(buttonPin) == HIGH) {
lcd.clear();
if (inputString == currentLockPassword) {
lcd.setCursor(0, 0);
lcd.print("Welcome!!");
} else {
lcd.setCursor(0, 0);
lcd.print("Try Again :((");
}
sendPasswordToServer(inputString); // Send the password to the server
Serial.println(inputString); // Print the input string to the console
inputString = ""; // Clear the input string
delay(500); // Debounce delay
}
}
//Ham phu
void fetchLockPassword() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(lockPasswordEndpoint); // Specify the URL
Serial.println("Fetching lock password...");
int httpResponseCode = http.GET(); // Send the request
if (httpResponseCode > 0) {
String response = http.getString(); // Get the response to the request
Serial.println(httpResponseCode); // Print return code
Serial.println(response); // Print request answer
// Parse the JSON response to get the lock password
DynamicJsonDocument doc(1024);
deserializeJson(doc, response);
currentLockPassword = doc["lockPassword"].as<String>();
Serial.println("Current Lock Password: " + currentLockPassword);
} else {
Serial.print("Error on fetching lock password: ");
Serial.println(httpResponseCode);
Serial.println(http.errorToString(httpResponseCode)); // Print detailed error message
}
http.end(); // Free the resources
} else {
Serial.println("Error in WiFi connection");
}
}
void sendPasswordToServer(String password) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(lockPasswordEndpoint); // Specify the URL
http.addHeader("Content-Type", "application/json"); // Specify content-type header
String jsonData = "{\"password\":\"" + password + "\"}";
int httpResponseCode = http.POST(jsonData); // Send the request
if (httpResponseCode > 0) {
String response = http.getString(); // Get the response to the request
Serial.println(httpResponseCode); // Print return code
Serial.println(response); // Print request answer
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end(); // Free the resources
} else {
Serial.println("Error in WiFi connection");
}
}
/*Start: Tu khuc nay moi code, chua test ~GBao, 18.8 11:49AM
//Ho tro xac thuc token tu dien thoai -> Ho tro smart Lock/Unlock
bool validateToken(String token) {
// Logic để kiểm tra token (so khớp với token lưu trong hệ thống)
return (token == "expectedToken");
}
//Khoa cua
void lockDoor() {
// Điều khiển servo để khóa cửa
myservo.write(0); // Góc khóa
// Thay đổi trạng thái đèn LED nếu cần
digitalWrite(LED_BUILTIN, LOW); // Ví dụ: tắt đèn LED
}
//Mo cua
void unlockDoor() {
// Điều khiển servo để mở cửa
myservo.write(90); // Góc mở khóa
// Thay đổi trạng thái đèn LED nếu cần
digitalWrite(LED_BUILTIN, HIGH); // Ví dụ: bật đèn LED
}
//Luu mat khau vao database
void savePasswordToDatabase(String userId, String password) {
// Lưu mật khẩu vào bộ nhớ hoặc cơ sở dữ liệu
// Ví dụ: EEPROM hoặc SPIFFS trên ESP32
EEPROM.writeString(0, password);
EEPROM.commit();
}
//Kich hoat coi bao dong
void triggerAlarm() {
// Kích hoạt còi hoặc đèn báo động
digitalWrite(ALARM_PIN, HIGH);
delay(10000); // Báo động trong 10 giây
digitalWrite(ALARM_PIN, LOW);
}
//Gui canh bao qua tin nhan dien thoai
void sendAlertToOwner() {
// Gửi cảnh báo qua tin nhắn hoặc email
// Sử dụng các dịch vụ như Twilio, IFTTT, hoặc HTTP POST đến một API
}
//Gui OTP toi dien thoai
String sendOTPToPhone(String phoneNumber) {
String otp = generateOTP();
// Gửi OTP qua SMS
// Sử dụng API SMS như Twilio hoặc bất kỳ dịch vụ nào bạn chọn
sendSMS(phoneNumber, otp);
return otp;
}
//Tao ma OTP
String generateOTP() {
String otp = "";
for (int i = 0; i < 6; i++) {
otp += String(random(0, 10));
}
return otp;
}
//Tinh nang 1: Tu dong khoa/mo cua
void autoLockOn(unsigned long inactivityDuration, bool isLocking) {
if (isLocking) {
// Check inactivity time and lock the door
if (millis() - lastActivityTime >= inactivityDuration) {
lockDoor();
}
} else {
// Auto-unlock logic here
unlockDoor();
}
}
//Tinh nang 2: Mo/khoa thong minh bang dien thoai
bool unlockSmart(String authToken, bool isPhoneNearby) {
if (validateToken(authToken) && isPhoneNearby) {
unlockDoor();
return true;
}
return false;
}
bool lockSmart(String authToken, bool isPhoneNearby) {
if (validateToken(authToken) && isPhoneNearby) {
lockDoor();
return true;
}
return false;
}
//Tinh nang 3: Tao ma khoa tuy chinh cho tung doi tuong
bool createCustomPassword(String userId, String newPassword) {
if (newPassword.length() >= 4 && newPassword.length() <= 8) {
savePasswordToDatabase(userId, newPassword);
return true;
}
return false;
}
//Tinh nang 4: Chong trom
void alarmThiefOn(bool isIntrusionDetected) {
if (isIntrusionDetected) {
triggerAlarm();
sendAlertToOwner();
}
}
//Tinh nang 5: Giu an toan tuyet doi nho xac thuc 2 buoc (2FA)
bool 2FASecurityOn(String phoneNumber, String userInputOTP) {
String generatedOTP = sendOTPToPhone(phoneNumber);
if (userInputOTP == generatedOTP) {
return true;
}
return false;
}
*/