#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include "DHT.h"
#include <ESP32Servo.h>
#define DHTPIN 4
#define DHTTYPE DHT22
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define BOT_TOKEN "6909017954:AAGWt6AKMxLsRO4D2F7yEb82i9qEIU9lEaY"
#define CHAT_ID "5300423945"
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
DHT dht(DHTPIN, DHTTYPE);
Servo ServoPin;
const unsigned long BOT_MTBS = 1000;
unsigned long bot_lasttime;
float temperatureC;
void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
dht.begin();
Serial.print("Connecting to Wifi SSID ");
Serial.print(WIFI_SSID);
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());
ServoPin.attach(15);
}
void loop() {
temperatureC = dht.readTemperature();
if (millis() - bot_lasttime > BOT_MTBS) {
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();
}
}
void handleNewMessages(int numNewMessages) {
Serial.print("handleNewMessages ");
Serial.println(numNewMessages);
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID) {
bot.sendMessage(chat_id, "Unauthorized user", "");
} else {
String text = bot.messages[i].text;
String from_name = bot.messages[i].from_name;
if (from_name == "") from_name = "Guest";
if (text == "/tempC") {
String msg = "Temperature is ";
msg += temperatureC;
msg += "C";
bot.sendMessage(chat_id, msg, "");
}
if (text == "/start") {
String welcome = "DHTxx sensor readings.\n";
welcome += "/tempC : Temperature in Celsius \n";
bot.sendMessage(chat_id, welcome, "Markdown");
}
if (temperatureC < 12) {
ServoPin.write(0);
String msg = "Suhu Dingin, Servo Mati";
bot.sendMessage(chat_id, msg, "");
} else if (temperatureC >= 12 && temperatureC <= 30) {
ServoPin.write(90);
String msg = "Suhu Normal, Servo Mati";
bot.sendMessage(chat_id, msg, "");
} else if (temperatureC > 30) {
ServoPin.write(180);
String msg = "Suhu Panas, Servo Hidup";
bot.sendMessage(chat_id, msg, "");
}
}
}
}