#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include "DHT.h"
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define BOT_TOKEN "7685692805:AAFp2s6oqgQ49LTtm4NxjnS6zxdBrn5rSdI"
#define DHTPIN 2
#define LDRPIN 34
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime;
unsigned long last_report_time;
const unsigned long REPORT_INTERVAL = 30000;
String last_chat_id = "";
void handleNewMessages(int numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = bot.messages[i].chat_id;
last_chat_id = chat_id;
String text = bot.messages[i].text;
if (text == "/status") {
float h = dht.readHumidity();
float t = dht.readTemperature();
int ldrValue = analogRead(LDRPIN);
String msg = "Status:\nTemp: " + String(t) + " C\nHumid: " + String(h) + " %\nLDR: " + String(ldrValue);
bot.sendMessage(chat_id, msg, "");
}
if (text == "/start") {
bot.sendMessage(chat_id, "System starts", "");
}
}
}
void setup() {
Serial.begin(115200);
Serial.println();
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());
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);
}
Serial.println(now);
}
void loop() {
if (millis() - bot_lasttime > 1000) {
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();
}
if (millis() - last_report_time > REPORT_INTERVAL) {
if (last_chat_id != "") {
float h = dht.readHumidity();
float t = dht.readTemperature();
int ldrValue = analogRead(LDRPIN);
String report = "Report:\nTemp: " + String(t) + " C\nHumid: " + String(h) + " %\nLDR: " + String(ldrValue);
bot.sendMessage(last_chat_id, report, "");
}
last_report_time = millis();
}
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4