#include <WiFi.h>
#include <HTTPClient.h>
#include <UniversalTelegramBot.h>
#include <WiFiClientSecure.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Telegram bot token
#define BOTtoken "7174316314:AAHfDQHUK7e8KWstBAL-pd_iO2xdX8p-UyU"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
// Google Script Deployment ID
const char* GScriptId = "AKfycbwEsSQwtDPnM801kTsKd1b-fsX3stcYFgsON5Zv-0kJnXQqR48fKOWNX5yhALLybCzI";
const char* host = "script.google.com";
const int httpsPort = 443;
const int trigPin = 5; // Define the trigPin
const int echoPin = 18; // Define the echoPin
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
void handleNewMessages(int numNewMessages);
float getDistance(String &status);
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
client.setInsecure();
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (millis() > lastTimeBotRan + botRequestDelay) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi not connected. Reconnecting...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("Reconnected to WiFi");
}
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);
}
lastTimeBotRan = millis();
}
}
void sendDataToGoogleSheets(String chat_id, String from_name) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String("https://script.google.com/macros/s/") + GScriptId + "/exec";
http.begin(url);
String payload = "{\"command\":\"append_row\", \"sheet_name\":\"Sheet1\", \"values\":\"" + chat_id + "," + from_name + "\"}";
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Response from server: " + response);
} else {
Serial.println("Error sending data to Google Sheets: " + String(httpResponseCode));
}
http.end();
} else {
Serial.println("WiFi not connected");
}
}
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
String text = bot.messages[i].text;
String from_name = bot.messages[i].from_name;
Serial.println("Received message: " + text);
if (from_name == "") from_name = "Guest";
if (text == "/start") {
String welcome = "Hallo <b>" + from_name + "</b>.\n";
welcome += "Selamat datang di Robot <b>SIM-KPOB</b> (Sistem Informasi, Monitoring, dan Kontrol pada Bendungan). Gunakan perintah /menu untuk mengetahui fitur apa saja yang tersedia pada robot ini.";
bot.sendMessage(chat_id, welcome, "HTML");
} else if (text == "/menu") {
String menu = "Berikut perintah yang dapat kamu gunakan pada robot SIM-KPOB ini:\n\n";
menu += "/start _ Perintah untuk mengaktifkan Robot <b>SIM-KPOB</b> \n";
menu += "/menu _ Gunakan perintah ini untuk melihat seluruh format perintah yang dapat digunakan untuk mengakses fitur fitur pada Robot <b>SIM-KPOB</b> \n";
menu += "/info _ Gunakan perintah ini untuk mendapatkan ringkasan kondisi terkini bendungan\n";
menu += "/copyright _ Perintah ini menampillan informasi terkait Robot <b>SIM-KPOB</b> ";
bot.sendMessage(chat_id, menu, "HTML");
} else if (text == "/info") {
String status;
float distance = getDistance(status);
String info = "Tinggi Muka Air: " + String(distance) + " cm\n";
info += "Status Bendungan: " + status + "\n";
info += "------------------------------\n";
info += "Informasi Lengkap dan Real Time dapat diakses melalui:\n";
info += "http://localhost/IoT_MonitoringBendunganSungapan/\n";
bot.sendMessage(chat_id, info, "");
} else if (text == "/peringatan") {
Serial.println("Peringatan received from: " + from_name + " (Chat ID: " + chat_id + ")");
sendDataToGoogleSheets(chat_id, from_name);
bot.sendMessage(chat_id, "Peringatan telah diterima dan disimpan.", "");
} else if (text == "/copyright") {
String copy = "Robot Telegram ini dibuat oleh <b>Rizal Budi Santoso</b> dalam hal Lomba <b>KRENOVA</b> kab, Pemalang Tahun 2024";
bot.sendMessage(chat_id, copy, "HTML");
} else {
String invalid = "Perintah tidak valid. Gunakan /menu untuk melihat perintah yang tersedia.";
bot.sendMessage(chat_id, invalid, "");
}
}
}
float getDistance(String &status) {
// Send a pulse to the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse from the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
float distance = duration * 0.034 / 2;
Serial.print("Measured distance: ");
Serial.println(distance);
if (distance <= 80) {
status = "KERING";
} else if (distance > 80 && distance <= 160) {
status = "NORMAL";
} else if (distance > 160 && distance <= 240) {
status = "SIAGA";
} else if (distance > 240 && distance <= 320) {
status = "WASPADA";
} else if (distance > 320) {
status = "BAHAYA";
} else {
status = "UNKNOWN";
}
return distance;
}