#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include "DHT.h"
#define pin_led 12
#define pin_led2 33
#define DHT22PIN 23
bool ledState = LOW;
#define WIFI_AP "Wokwi-GUEST"
#define WIFI_PASS ""
#define BOTtoken "7080775992:AAFVw42vqvveY41QGO16Iv1P-louePEnFtU"
#define CHAT_ID "1564703747"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
DHT dht(DHT22PIN, DHT22);
int botRequestDelay = 100;
unsigned long lastTimeBotRan;
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
for (int i=0; i<numNewMessages; i++) {
// Chat id of the requester
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
// Print the received message
String text = bot.messages[i].text;
Serial.println(text);
String from_name = bot.messages[i].from_name;
if (text == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following commands to control your outputs.\n\n";
welcome += "/led_on to turn GPIO ON \n";
welcome += "/led_off to turn GPIO OFF \n";
welcome += "/state to request current GPIO state \n";
bot.sendMessage(chat_id, welcome, "");
}
if (text == "/led_on") {
bot.sendMessage(chat_id, "LED state set to ON", "");
ledState = HIGH;
digitalWrite(pin_led2, ledState);
}
if (text == "/led_off") {
bot.sendMessage(chat_id, "LED state set to OFF", "");
ledState = LOW;
digitalWrite(pin_led2, ledState);
}
if (text == "/state") {
if (digitalRead(pin_led2)){
bot.sendMessage(chat_id, "LED is ON", "");
}
else{
bot.sendMessage(chat_id, "LED is OFF", "");
}
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(pin_led, OUTPUT);
pinMode(pin_led2, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_AP, WIFI_PASS);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
dht.begin();
}
void loop() {
// put your main code here, to run repeatedly:
if (millis() > lastTimeBotRan + botRequestDelay) {
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();
}
float humi = dht.readHumidity();
float temp = dht.readTemperature();
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("ºC ");
Serial.print("Humidity: ");
Serial.println(humi);
if(temp > 35){
digitalWrite(pin_led, HIGH);
}else if(temp < 30){
digitalWrite(pin_led, LOW);
}
delay(500);
}