Upload files to "/"

This commit is contained in:
MuhammadCondro 2024-07-16 12:51:08 +07:00
commit 44eabffc67
1 changed files with 330 additions and 0 deletions

View File

@ -0,0 +1,330 @@
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <vector> // Include vector library
#include <FirebaseESP32.h>
// Provide the token generation process info.
#include <addons/TokenHelper.h>
// Provide the RTDB payload printing info and other helper functions.
#include <addons/RTDBHelper.h>
#define buzer 2
#define relay 5
// Wifi network station credentials
#define WIFI_SSID "Hi"
#define WIFI_PASSWORD "1234567899"
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "6653694130:AAElDMIeCgqX9K-RZuTfuF6-1_FEWL0b0lY"
#define API_KEY "AIzaSyBAH3ycbUjpkdywVIgkMPUS8UvxoifkNoM"
#define DATABASE_URL "https://rfidlock-2cf24-default-rtdb.asia-southeast1.firebasedatabase.app/" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app
#define USER_EMAIL "superadmin@admin.com"
#define USER_PASSWORD "superadmin"
const unsigned long BOT_MTBS = 1000; // mean time between scan messages
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime;
#include <TinyGPS++.h>
#include <HardwareSerial.h>
HardwareSerial GPSSerial(1);
TinyGPSPlus gps;
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
byte sda = 21;
byte rst = 22;
#include <KRrfid.h>
int u = 0;
bool realtime = false;
String chat_id; // Added declaration of chat_id for use in loop()
bool updateRfid = false;
// last time messages' scan has been done
int relayStatus = 0;
FirebaseJsonArray IDs;
std::vector<String> authorizedIDs = {}; // Using vector for dynamic list
void addAuthorizedID(String newID) {
bool alreadyExists = false;
for (const auto& id : authorizedIDs) {
if (id == newID) {
alreadyExists = true;
break;
}
}
FirebaseJsonArray data;
for (int i = 0; i < authorizedIDs.size(); i++) {
data.add(authorizedIDs[i]);
}
Serial.println(alreadyExists);
if (!alreadyExists) {
data.add(newID);
Firebase.setArray(fbdo, F("/rfid"), data);
loadAuthorizedIDs();
bot.sendMessage(chat_id, "ID baru telah ditambahkan: " + newID, "");
}
}
void deleteAuthorizedID(String oldID) {
FirebaseJsonArray data;
for (int i = 0; i < authorizedIDs.size(); i++) {
if (authorizedIDs[i] != oldID) {
data.add(authorizedIDs[i]);
}
}
Firebase.setArray(fbdo, F("/rfid"), data);
loadAuthorizedIDs();
bot.sendMessage(chat_id, "ID " + oldID + " berhasil dihapus", "");
}
void loadAuthorizedIDs() {
Firebase.getArray(fbdo, F("/rfid"));
IDs = fbdo.jsonArray();
authorizedIDs = {};
for (int i = 0; i < IDs.size(); i++) {
FirebaseJsonData jsonData;
IDs.get(jsonData, i);
authorizedIDs.push_back(jsonData.stringValue);
}
}
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
for (int i = 0; i < numNewMessages; i++) {
chat_id = bot.messages[i].chat_id; // Assign chat_id for use in loop()
String text = bot.messages[i].text;
Serial.println(text);
String from_name = bot.messages[i].from_name;
//float currentLat = 0;
//float currentLng = 0;
if (text == "/menghidupkan") {
digitalWrite(relay, LOW);
relayStatus = 1;
digitalWrite(buzer, HIGH);
delay(100);
digitalWrite(buzer, LOW);
delay(100);
digitalWrite(buzer, HIGH);
delay(100);
digitalWrite(buzer, LOW);
bot.sendMessage(chat_id, "SEPEDA HIDUP", "");
}
if (text == "/matikan") {
relayStatus = 0;
digitalWrite(relay, HIGH);
digitalWrite(buzer, HIGH);
delay(500);
digitalWrite(buzer, LOW);
bot.sendMessage(chat_id, "SEPEDA MATI", "");
}
if (text == "/status") {
if (relayStatus) {
bot.sendMessage(chat_id, "SEPEDA HIDUP", "");
} else {
bot.sendMessage(chat_id, "SEPEDA MATI", "");
}
}
if (text == "/options") {
String keyboardJson = "[[\"/menghidupkan\", \"/matikan\"],[\"/status\", \"/lokasi\"]]";
bot.sendMessageWithReplyKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson, true);
}
if (text == "/lokasi_start") {
realtime = true;
}
if (text == "/lokasi_stop") {
realtime = false;
}
if (text == "/getid") {
String text = "There is authorized ID :\n";
for (int i = 0; i < authorizedIDs.size(); i++) {
text += "- " + authorizedIDs[i] + "\n";
}
bot.sendMessage(chat_id, text, "Markdown");
}
if (text == "/start") {
String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
welcome += "This is Reply Keyboard Markup example.\n\n";
welcome += "/menghidupkan : to switch the SEPEDA ON\n";
welcome += "/matikan : to switch the SEPEDA OFF\n";
welcome += "/status : Returns current status of LED\n";
welcome += "/lokasi_start : returns the reply keyboard\n";
welcome += "/lokasi_stop : returns the reply keyboard\n";
welcome += "/options : returns the reply keyboard\n";
welcome += "/getid <ID> : Get list of authorized RFID ID\n"; // New command
welcome += "/addid <ID> : Adds a new RFID ID to the authorized list\n"; // New command
welcome += "/deleteid <ID> : Delete a RFID ID from the authorized list\n";
bot.sendMessage(chat_id, welcome, "Markdown");
}
if (text.startsWith("/addid ")) {
String newID = text.substring(7);
addAuthorizedID(newID);
bot.sendMessage(chat_id, "ID " + newID + " has been added to the authorized list.", "");
}
if (text.startsWith("/deleteid")) {
String oldID = text.substring(10);
deleteAuthorizedID(oldID);
}
}
}
void setup() {
Serial.begin(115200);
GPSSerial.begin(9600, SERIAL_8N1, 16, 17);
rfidBegin();
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);
pinMode(buzer, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print("\nWiFi connected. IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Retrieving time: ");
configTime(0, 0, "pool.ntp.org");
time_t now = time(nullptr);
while (now < 24 * 3600) {
Serial.print(".");
delay(100);
now = time(nullptr);
}
/* Assign the api key (required) */
config.api_key = API_KEY;
/* Assign the user sign in credentials */
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
/* Assign the RTDB URL (required) */
config.database_url = DATABASE_URL;
/* Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
// Comment or pass false value when WiFi reconnection will control by your code or third party library e.g. WiFiManager
Firebase.reconnectNetwork(true);
fbdo.setBSSLBufferSize(4096 /* Rx buffer size in bytes from 512 - 16384 */, 1024 /* Tx buffer size in bytes from 512 - 16384 */);
Firebase.begin(&config, &auth);
Firebase.setDoubleDigits(5);
}
void loop() {
if (Firebase.ready() && millis() - bot_lasttime > BOT_MTBS) {
if (realtime == true) {
while (GPSSerial.available()) {
gps.encode(GPSSerial.read());
}
if (gps.charsProcessed() > 10)
//if (true)
{
float currentLat = gps.location.lat();
float currentLng = gps.location.lng();
String lokasi = "Lokasi : https://www.google.com/maps/place/";
lokasi += String(currentLat, 6);
lokasi += ",";
lokasi += String(currentLng, 6);
bot.sendMessage(chat_id, lokasi, "");
}
}
if (!updateRfid) {
updateRfid = true;
loadAuthorizedIDs();
}
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
bot_lasttime = millis();
}
getTAG();
if (TAG != "") {
bool isAuthorized = false;
for (const auto& id : authorizedIDs) {
if (TAG == id) {
isAuthorized = true;
break;
}
}
if (isAuthorized) {
if (u == 4) {
u == 0;
} else {
u++;
}
switch (u) {
case 1:
digitalWrite(relay, LOW);
relayStatus = 1;
digitalWrite(buzer, HIGH);
delay(100);
digitalWrite(buzer, LOW);
delay(100);
digitalWrite(buzer, HIGH);
delay(100);
digitalWrite(buzer, LOW);
delay(1000);
bot.sendMessage(chat_id, "RFID berhasil dipindai. SEPEDA HIDUP.", "");
break;
case 2:
digitalWrite(relay, HIGH);
relayStatus = 0;
digitalWrite(buzer, HIGH);
delay(500);
digitalWrite(buzer, LOW);
u = 0;
bot.sendMessage(chat_id, "RFID berhasil dipindai. SEPEDA MATI.", "");
break;
default:
u = 0;
break;
}
delay(500);
} else {
addAuthorizedID(TAG);
}
TAG = "";
}
}