#include <WiFi.h>
#include <NewPing.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include "DHT.h"
#include "time.h"
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define BOT_TOKEN "8507473775:AAFQdIGKQxzYFdJUB4u21oJdC1wShi0VXGQ"
#define CHAT_ID "1704077186"
const char* mqtt_server = "67b795fba6c640109bf32dd1cdcd2d24.s1.eu.hivemq.cloud"; //URL CLUSTER
const int mqtt_port = 8883;
const char* mqtt_user = "hivemq.webclient.1762911908409";
const char* mqtt_password = "1023AEFBdcfeGbCa?&,<";
// topik MQTT
const char* temp_topic = "kelompok3/suhu";
const char* distance_topic= "kelompok3/jarak";
#define LAMPU_PIN 2
#define DHTPIN 4
#define DHTTYPE DHT11
#define TRIGGER_PIN 5
#define ECHO_PIN 18
#define MAX_DISTANCE 200
WiFiClientSecure mqttSecureClient;
WiFiClientSecure telegramSecureClient;
PubSubClient mqttClient(mqttSecureClient);
UniversalTelegramBot bot(BOT_TOKEN, telegramSecureClient);
DHT dht(DHTPIN, DHTTYPE);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
//waktu tele
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 7 * 3600;
const int daylightOffset_sec = 0;
String getTimeNow() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) return "Waktu tidak tersedia";
char buffer[25];
strftime(buffer, 25, "%d/%m/%Y %H:%M:%S", &timeinfo);
return String(buffer);
}
//setup wifi
void setup_wifi() {
digitalWrite(LAMPU_PIN, LOW);
Serial.print("Menghubungkan ke WiFi: ");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
digitalWrite(LAMPU_PIN, HIGH);
Serial.println("\nWiFi Terhubung");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
// koneksi mqtt
void reconnect_mqtt() {
while (!mqttClient.connected()) {
Serial.print("Mencoba koneksi ke HiveMQ Cloud... ");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (mqttClient.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
Serial.println("Terhubung ke HiveMQ Cloud");
} else {
Serial.print("Gagal, rc=");
Serial.print(mqttClient.state());
Serial.println(" Coba lagi 3 detik...");
delay(3000);
}
}
}
//pesan telegram
String getSensorDataForTelegram() {
float suhu = dht.readTemperature();
unsigned int jarak = sonar.ping_cm();
if (jarak == 0) jarak = MAX_DISTANCE;
String waktu = getTimeNow();
String msg = "*Status Sensor*\n";
msg += "Waktu: " + waktu + "\n\n";
if (isnan(suhu)) msg += " Suhu: Error\n";
else msg += "Suhu: " + String(suhu, 1) + " °C\n";
msg += "Jarak: " + String(jarak) + " cm\n";
return msg;
}
void handleNewMessages(int numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = bot.messages[i].chat_id;
String text = bot.messages[i].text;
text.toLowerCase();
String from_name = bot.messages[i].from_name;
if (chat_id != CHAT_ID) continue;
if (text == "/start") {
String welcome = "Halo " + from_name + "! 👋\nGunakan perintah:\n";
welcome += "/datasensor - Cek suhu & jarak\n/help - Bantuan\n";
String keyboardJson = "[[{\"text\":\"📊 Cek Data Sensor\", \"callback_data\":\"/datasensor\"}]]";
bot.sendMessageWithInlineKeyboard(chat_id, welcome, "", keyboardJson);
}
else if (text == "/datasensor") {
bot.sendMessage(chat_id, "Sedang membaca sensor...", "");
bot.sendMessage(chat_id, getSensorDataForTelegram(), "Markdown");
}
else if (text == "/help") {
String help = "*Bantuan:*\n/start - Menu utama\n/datasensor - Baca sensor\n/help - Bantuan";
bot.sendMessage(chat_id, help, "Markdown");
}
}
}
//setup
unsigned long lastMqttMsg = 0;
const long mqtt_interval = 5000;
unsigned long lastBotRan = 0;
const unsigned long bot_interval = 2000;
void setup() {
Serial.begin(115200);
pinMode(LAMPU_PIN, OUTPUT);
digitalWrite(LAMPU_PIN, LOW);
dht.begin();
setup_wifi();
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
mqttSecureClient.setInsecure();
telegramSecureClient.setInsecure();
mqttClient.setServer(mqtt_server, mqtt_port);
Serial.println("Gas Lanjut");
}
void loop() {
unsigned long now = millis();
if (!mqttClient.connected()) reconnect_mqtt();
mqttClient.loop();
//upload ke mqtt
if (now - lastMqttMsg > mqtt_interval) {
lastMqttMsg = now;
float t = dht.readTemperature();
unsigned int d = sonar.ping_cm();
if (d == 0) d = MAX_DISTANCE;
if (!isnan(t)) {
char tempStr[8];
dtostrf(t, 1, 2, tempStr);
mqttClient.publish(temp_topic, tempStr);
Serial.print("[MQTT] Suhu: "); Serial.println(tempStr);
}
char distStr[8];
dtostrf(d, 1, 0, distStr);
mqttClient.publish(distance_topic, distStr);
Serial.print("[MQTT] Jarak: "); Serial.println(distStr);
}
if (now - lastBotRan > bot_interval) {
lastBotRan = now;
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
}
}