#include <ESP32Servo.h>
#include <DHT.h>
#include <UniversalTelegramBot.h>
#include <FastLED.h>
#include <LiquidCrystal_I2C.h>
#include <NTPClient.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
#include <Wire.h>
const unsigned long BOT_MTBS = 1000;
#define BOT_TOKEN "7084252810:AAH_P3xoTpyDmIo3GErFyvEyBv_kYXrs0LQ"
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime; // last time messages' scan has been done
#define NUM_LEDS 6
CRGB leds[NUM_LEDS];
#define LED_PIN 15
#define COLOR_ORDER GRB
#define CHIPSET WS2812 // тип светодиодов
#define NUM_LEDS2 10 // количество светодиодов в матрице
CRGB leds2[NUM_LEDS2]; // определяем матрицу (FastLED библиотека)
#define LED_PIN2 5
#define PH 35
bool door = false;
String t1, h1;
String nn = "\n";
#define PiR 32
int Pir;
String status;
String stV;
String stH;
bool flag3 = false;
bool led3 = false;
uint32_t timer7;
uint32_t btnTimer = 0;
boolean led2 = true;
#define Dht 14
const int servoPin = 17;
DHT dht1(Dht, DHT22);
Servo servo;
Servo servo2;
Servo servo3;
#define Co2 33
int pos = 0;
int phot, phot2;
int dhtT, dhtH;
#define ECHO_PIN 23
#define TRIG_PIN 19
Servo servo4;
uint32_t tim23;
#define NTP_SERVER "pool.ntp.org"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
const char *ssid = "Wokwi-GUEST";
const char *password = "";
int hum1, wind1, temp1, pr1, pr2;
String openWeatherMapApiKey = "29703c5d164dcdaa6be62345402106fc";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
String city = "Dovol'noye";
String countryCode = "RU";
bool flag1 = LOW;
unsigned long last_time = 0;
unsigned long timer_delay = 10000;
String jsonBuffer;
LiquidCrystal_I2C lcd(0x27, 20, 4);
void handleNewMessages(int numNewMessages)
{
Serial.print("handleNewMessages ");
Serial.println(numNewMessages);
for (int i = 0; i < numNewMessages; i++)
{
String chat_id = bot.messages[i].chat_id;
String text = bot.messages[i].text;
String from_name = bot.messages[i].from_name;
int i2=0;
do{
if (dfda[i2] == chat_id) {
if (text == "/doklad")
{
String dokl = "Улица" + nn;
dokl += t1 + nn;
dokl += h1 + nn;
dokl += p3 + nn;
dokl += nn;
dokl += "Помещение" + nn;
dokl += t11 + nn;
dokl += h11 + nn;
dokl += otp + nn;
dokl += nn;
dokl += "Концентрация СO₂" + nn;
dokl += PPM1 + nn;
dokl += smail + nn;
dokl += nn;
dokl += "Прогноз погоды:" + nn;
dokl += pogoda23 + nn;
bot.sendMessage(chat_id,dokl, "");
}
if (text == "/settings")
{
String dw = "Настройки" + nn;
dw += "/regim : Настройка режима." + nn;
bot.sendMessage(chat_id,dw, "");
}
if (text == "/regim")
{
String dod = "/status : статус режима работы." + nn;
dod += "/zima : зимний режим." + nn;
dod += "/leto : летний режим." + nn;
bot.sendMessage(chat_id,dod, "");
}
if (text == "Лето" || text == "/leto" )
{
cht = 0;
bot.sendMessage(chat_id,"☀Включён летний режим☀", "");
if(millis() - timer4 >= 3000){
timer4 = millis();
oled.clear();
oled.drawBitmap(0, 2, bitmapso_128x64, 128, 64);
op343 = HIGH;
}
}
if (text == "Зима" || text == "/zima" )
{
cht = 1;
bot.sendMessage(chat_id,"❄Включён зимний режим❄", "");
if(millis() - timer4 >= 3000){
timer4 = millis();
oled.clear();
oled.drawBitmap(0, 0, bitmapz_128x64, 128, 64);
op343 = LOW;
}
}
if (text == "/status" || text == "Статус" )
{
if (op343) {
bot.sendMessage(chat_id,"Текущий cтатус режима работы: ☀Включён летний режим☀", "");
}else{
bot.sendMessage(chat_id,"Текущий cтатус режима работы: ❄Включён зимний режим❄", "");
}
}
if (text == "/link")
{
bot.sendMessage(chat_id,ssil, "");
}
if (text == "/start")
{
String welcome = "Вас приветствует бот смарт-системы мониторинга среды обитания, " + from_name + toch + nn;
welcome += "У вас есть права администратора системы." + nn;
welcome += "Вам доступно меню:" + nn;
welcome += "/doklad : нажми, чтобы получить полный отчёт смарт системы." + nn;
welcome += "/settings : нажми, чтобы запустить настройки." + nn;
welcome += "/link : нажми, чтобы получить ссылку на гугл-таблицу с архивом всех измерений." + nn;
bot.sendMessage(chat_id, welcome, "");
}
break;
}
if (dfdp[i2] == chat_id) {
if (text == "/start") {
String welcome1 = "Вас приветствует бот смарт-системы мониторинга среды обитания, " + from_name + toch + nn;
welcome1 += "У вас есть права пользователя системы." + nn;
welcome1 += "Вам доступно меню:" + nn;
welcome1 += "/doklad : нажми, чтобы получить полный отчёт смарт системы." + nn;
welcome1 += "/link : нажми, чтобы получить ссылку на гугл-таблицу с архивом всех измерений." + nn;
bot.sendMessage(chat_id, welcome1, "");
}
if (text == "/link")
{
bot.sendMessage(chat_id,ssil, "");
}
if (text == "/doklad")
{
String dokl = "Улица" + nn;
dokl += t1 + nn;
dokl += h1 + nn;
dokl += p3 + nn;
dokl += nn;
dokl += "Помещение" + nn;
dokl += t11 + nn;
dokl += h11 + nn;
dokl += otp + nn;
dokl += nn;
dokl += "Концентрация СO₂" + nn;
dokl += PPM1 + nn;
dokl += smail + nn;
dokl += nn;
dokl += "Прогноз погоды:" + nn;
dokl += pogoda23 + nn;
bot.sendMessage(chat_id,dokl, "");
}
if (text == "/settings" || text == "Зима" || text == "/zima" || text == "/status" || text == "Статус" || text == "/regim" || text == "Лето" || text == "/leto")
{
bot.sendMessage(chat_id,"У вас нет доступа к этой функции!", "");
}
break;
}
if (i2==((sizeof(dfda)/sizeof(int))-1)&&text == "/start"||(sizeof(dfda)/sizeof(int))==0&&text == "/start") {
if (i2==((sizeof(dfdp)/sizeof(int))-1)&&text == "/start"||(sizeof(dfdp)/sizeof(int))==0&&text == "/start") {
String keyboardStart = "[[{ \"text\" : \"👨🏻💻Telegram администратора системы👨🏻💻\", \"url\" : \"https://t.me/Kriko11\" }]]";
String ww1 = "Вас приветствует бот смарт-системы мониторинга среды обитания, " + from_name + toch + nn;
ww1 += "В настоящее время у Вас нет прав на использование системы." + nn;
ww1 += "Чтобы получить доступ можете обратиться к администратору системы по ссылке ниже." + nn;
ww1 += "Ваш chat_id: " + chat_id;
bot.sendMessageWithInlineKeyboard(chat_id, ww1 , "", keyboardStart);
break;
}
}
++i2;
}while (i2<(sizeof(dfda)/sizeof(int)));
}
}
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 1);
lcd.print(" <INITIALIZATION> ");
servo.attach(servoPin, 500, 2400);
servo2.attach(13, 500, 2400);
servo3.attach(16, 500, 2400);
dht1.begin();
pinMode(Co2, INPUT);
pinMode(26, INPUT_PULLUP);
pinMode(PiR, INPUT);
pinMode(34, INPUT_PULLUP);
pinMode(21, OUTPUT);
pinMode(PH, INPUT);
FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
FastLED.addLeds<NEOPIXEL, LED_PIN2>(leds2, NUM_LEDS2);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
servo4.attach(4);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
Serial.print("\nWiFi connected. IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Retrieving time: ");
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
time_t now = time(nullptr);
while (now < 24 * 3600)
{
Serial.print(".");
delay(100);
now = time(nullptr);
}
Serial.println(now);
timeClient.begin();
timeClient.setTimeOffset(3600 * 7);
configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
}
bool flag = false;
uint32_t btnTimer1 = 0;
int lightLevel;
int ecran = 0;
boolean but_led = true; // включен ли свет кнопкой?
boolean light_led = false; // включен ли свет фотодатчиком?
boolean led = false;
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
return;
}
timeClient.update();
phot = analogRead(Co2);
phot2 = map(phot, 4063, 32, 0, 10000);
dhtT = dht1.readTemperature();
dhtH = dht1.readHumidity();
int Hour1 = timeClient.getHours();
int Minute1 = timeClient.getMinutes();
struct tm *ptm = gmtime ((time_t *)&getLocalTime);
int Day = ptm->tm_mday+12;
int Month = ptm->tm_mon-4;
int Year = ptm->tm_year+2003;
if(phot2 > 600){
servo3.write(90);
}
if(phot2 < 1000){
servo3.write(0);
}
if(dhtT == 24){
stV = "Vent: off ";
stH = "Heat: off ";
servo2.write(0);
}
if(dhtT > 21 && dhtT < 24){
servo2.write(45);
stV = "Vent: off ";
stH = "Heat: on ";
}
if(dhtT < 21){
servo2.write(90);
stH = "Heat: MAX ";
stV = "Vent: off ";
}
if(dhtT > 25){
servo2.write(0);
stV = "Vent: on ";
stH = "Heat: off ";
for (pos = 0; pos <= 180; pos += 1) {
servo.write(pos);
}
for (pos = 180; pos >= 0; pos -= 1) {
servo.write(pos);
}
}
status = stH +stV;
if(Hour1 > 8 && Hour1 < 20){
bool btnState = digitalRead(26);
if (btnState && !flag3 && millis() - btnTimer1 > 100) {
flag3 = true;
btnTimer1 = millis();
Serial.println("press");
led2 = !led2;
}
if (!btnState && flag3 && millis() - btnTimer1 > 100) {
flag3 = false;
btnTimer1 = millis();
}
if (millis() - timer7 >= 1000) {
timer7 = millis();
Pir = digitalRead(PiR);
Serial.println(Pir);
delay(1000);
if (Pir == 1){
led3 = true;
}else{
}
if (led2 == true && led3 == true){
fill_solid(leds, NUM_LEDS, CRGB(0, 0, 0));
}
FastLED.show();
if (led2 == true && led3 == false){
fill_solid(leds, NUM_LEDS, CRGB::White);
}
if (led3 == true && led2 == false){
fill_solid(leds, NUM_LEDS, CRGB::White);
}
FastLED.show();
if (led3 == false && led2 == false){
fill_solid(leds, NUM_LEDS, CRGB(0, 0, 0));
}
}
}else{
bool btnState = digitalRead(26);
if (btnState && !flag3 && millis() - btnTimer1 > 100) {
flag3 = true;
btnTimer1 = millis();
Serial.println("press");
led2 = !led2;
}
if (!btnState && flag3 && millis() - btnTimer1 > 100) {
flag3 = false;
btnTimer1 = millis();
}
if(led2 == true){
fill_solid(leds, NUM_LEDS, CRGB::White);
FastLED.show();
}
if(led2 == false) {
fill_solid(leds, NUM_LEDS, CRGB(0,0,0));
}
}
int i3r = analogRead(PH);
int svet2 = map(i3r, 32, 4507, 0, 284);
if(Hour1 > 8 && Hour1 < 20){
bool btnState1 = !digitalRead(34);
if (btnState1 && !flag && millis() - btnTimer > 100) {
flag = true;
btnTimer = millis();
Serial.println("press");
but_led = !but_led;
}
if (!btnState1 && flag && millis() - btnTimer > 100) {
flag = false;
btnTimer = millis();
//Serial.println("release");
}
if (i3r > 2000) {
light_led= true;
Serial.println(i3r);
delay(100);
}
else {
light_led= false;
Serial.println(i3r);
delay(100);
}
if (light_led== true && but_led==true) {
fill_solid(leds2, NUM_LEDS2, CRGB(0, 0, 0));}
FastLED.show();
if (light_led== true && but_led==false) {
fill_solid(leds2, NUM_LEDS2, CRGB(svet2, svet2, svet2));}
FastLED.show();
if (light_led== false&& but_led==true) {
fill_solid(leds2, NUM_LEDS2, CRGB::White);
}
if (light_led== false&& but_led==false) {
fill_solid(leds2, NUM_LEDS2, CRGB(0, 0, 0));
}
}
else{
bool btnState1 = !digitalRead(34);
if (btnState1 && !flag && millis() - btnTimer > 100) {
flag = true;
btnTimer = millis();
Serial.println("press");
but_led = !but_led;
}
if (!btnState1 && flag && millis() - btnTimer > 100) {
flag = false;
btnTimer = millis();
}
if(but_led ==true){
fill_solid(leds2, NUM_LEDS2, CRGB::White);
FastLED.show();
}
if(but_led == false){
fill_solid(leds2, NUM_LEDS2, CRGB(0,0,0));
}
}
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();
}
h1 ="Влажность: " + dhtH;
Serial.println(t1);
float distance = readDistanceCM();
if(Hour1 > 8 && Hour1 < 20){
if(distance < 100){
servo4.write(180);
}
if(distance > 100){
servo4.write(0);
}
}
else{
if(door == true){
servo4.write(180);
}
else{
servo4.write(0);
}
}
// Serial.print("Measured distance: ");
// Serial.println(readDistanceCM());
switch(ecran){
case 0:
if (millis() - tim23 >= 10000){
tim23 = millis();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temperature: ");
lcd.print(dhtT);
lcd.print(" \xDF");
lcd.print("C ");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(dhtH);
lcd.print(" % ");
lcd.setCursor(0, 2);
lcd.print(status);
lcd.setCursor(0, 3);
lcd.print(Hour1);
lcd.print(":");
lcd.print(Minute1);
lcd.print(" ");
if(Hour1 == 11 && Minute1 <= 15 || Hour1 == 11 && Minute1 <= 15 || Hour1 == 13 && Minute1 <= 30){
if(Hour1 == 13 && Minute1 <= 30){
lcd.setCursor(6, 3);
lcd.print(" Lunch Time ");
}
if(Hour1 == 19 && Minute1 <= 15 || Hour1 == 11 && Minute1 <= 15){
lcd.setCursor(6, 3);
lcd.print("Coffee Break");
}
}else{
lcd.setCursor(6, 3);
lcd.print(" Work Time ");
}
ecran = ecran + 1;
}
break;
case 1:
if (millis() - tim23 >= 10000){
tim23 = millis();
lcd.clear();
lcd.setCursor(0, 0);
lcd.println(&timeinfo, "%d.%m.%Y");
lcd.setCursor(11, 0);
lcd.print("Dovolnoe");
lcd.setCursor(0,1);
lcd.print("Temperature: ");
lcd.print(temp1);
lcd.print(" \xDF");
lcd.print("C ");
lcd.setCursor(0,2);
lcd.print("Humidity: "); //LCD Printing Humidity
lcd.print(hum1);
lcd.print("% ");
lcd.setCursor(0,3);
lcd.print("Press: ");
lcd.print(pr2);
lcd.print(" mm.rts");
ecran = 0;
}
break;
}
if ((millis() - last_time) > timer_delay) {
// Check WiFi connection status
if (WiFi.status() == WL_CONNECTED) {
String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&units=metric" + "&APPID=" + openWeatherMapApiKey;
jsonBuffer = httpGETRequest(serverPath.c_str());
Serial.println(jsonBuffer);
JSONVar myObject = JSON.parse(jsonBuffer);
// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}
Serial.print("JSON object = ");
Serial.println(myObject);
temp1 = myObject["main"]["temp"];
hum1 = myObject["main"]["humidity"];
wind1 = myObject["wind"]["speed"];
pr1 = myObject["main"]["pressure"];
pr2 = pr1 - 256;
}
else {
Serial.println("WiFi Disconnected");
}
last_time = millis();
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "{}";
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}
Board not found
wokwi-custom-board
wokwi-custom-board