#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 = 100;
#define BOT_TOKEN "***************************************" // ВМЕСТО ЗВЁЗДОЧЕК ВСТАТЬ СВОЙ ТОКЕН!!!!
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 25
#define PH 35
bool door = false;
String t1, h1, dok;
String nn = "\n", stO, stOS = " Svet: off";
#define PiR 32
int Pir;
String stat1;
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, timer2;
#define NTP_SERVER "pool.ntp.org"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
boolean but_led = true;
String dfdp[] = {"***********", "***********"}; //ВМЕСТО ЗВЁЗДОЧЕК ВСТАВЬ Chat_id ПОЛЬЗОВАТЕЛЕЙ СИСТЕМЫ!!!!
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;
boolean light_led = false;
LiquidCrystal_I2C lcd(0x27, 20, 4);
#define Font 5
uint32_t Fonttimer;
int font;
#define Pogar 18
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;
String Cel = " °C";
String Proc = " %";
String Pre = " мм.рт.ст";
String Cel2 = "Температура: ";
String Proc2 = "Влажность: ";
String Pre2 = "Давление: ";
int temp2 = dht1.readTemperature();
int hum2 = dht1.readHumidity();
do{
if (dfdp[i2] == chat_id) {
if (text == "/otchet"){
dok = "🏢Офис🏢" + nn;
dok += Cel2 + temp2 + Cel + nn;
dok += Proc2 + hum2 + Proc + nn;
dok += stat1 + stO + stOS + nn;
dok += nn;
dok += "🏘Улица🏘" + nn;
dok += "Село Довольное." + nn;
dok += Cel2 + temp1 + Cel + nn;
dok += Proc2 + hum1 + Proc + nn;
dok += Pre2 + pr2 + Pre + nn;
bot.sendMessage(chat_id, dok, "");
}
if (text == "/svet"){
but_led =! but_led;
if (light_led== true && but_led==true) {
bot.sendMessage(chat_id, "🔅Свет выключен.🔅", "");
}
if (light_led== true && but_led==false) {
bot.sendMessage(chat_id, "☀️Свет включен.☀️", "");
}
if (light_led== false&& but_led==true) {
bot.sendMessage(chat_id, "☀️Свет включен.☀️", "");
}
if (light_led== false&& but_led==false) {
bot.sendMessage(chat_id, "🔅Свет выключен.🔅", "");
}
}
if (text == "/door"){
door =! door;
if(door == true){
bot.sendMessage(chat_id, "🔓Дверь открыта.🔓", "");
}else{
bot.sendMessage(chat_id, "🔒Дверь закрыта.🔒", "");
}
}
if (text == "/start") {
String welcome1 = "Вас приветствует бот Умного офиса команды *Кибер Пельмени*, " + from_name + nn;
welcome1 += "У вас есть права пользователя системы." + nn;
welcome1 += "Вам доступно меню:" + nn;
welcome1 += "/otchet : нажми, чтобы получить полный отчёт системы." + nn;
welcome1 += "/svet : нажми, чтобы включить свет." + nn;
welcome1 += "Команды работающие в не рабочее время:" + nn;
welcome1 += "/door : нажми, чтобы открыть дверь." + nn;
bot.sendMessage(chat_id, welcome1, "");
}
break;
}
if (i2==((sizeof(dfdp)/sizeof(String))-1)&&text == "/start"||(sizeof(dfdp)/sizeof(String))==0&&text == "/start") {
String keyboardStart = "[[{ \"text\" : \"👨🏻💻Telegram администратора системы👨🏻💻\", \"url\" : \"https://t.me/Kriko11\" }]]";
String ww1 = "Вас приветствует бот Умного офиса команды *Кибер Пельмени*, " + from_name + nn;
ww1 += "🔒В настоящее время у Вас нет прав на использование системы🔒." + nn;
ww1 += "Чтобы получить доступ можете обратиться к администратору системы по ссылке ниже." + nn;
ww1 += "Ваш chat_id: " + chat_id;
bot.sendMessageWithInlineKeyboard(chat_id, ww1 , "", keyboardStart);
break;
}
++i2;
}while (i2<(sizeof(dfdp)/sizeof(String)));
}
}
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(Font, INPUT);
pinMode(Pogar, 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 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() {
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();
}
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();
if(dhtT < 21 || dhtT > 25){
for (int i = 0; i < sizeof(dfdp)/sizeof(String); i++){
bot.sendMessage(dfdp[i], "🟡Внимание! Нарушен температурный режим!🟡" + nn + "Температура: " + dhtT + " °C", "");
}
}
int Hour1 = timeClient.getHours();
int Minute1 = timeClient.getMinutes();
bool fire = !digitalRead(Pogar);
if (millis() - Fonttimer >= 3000) {
Fonttimer = millis();
font = digitalRead(Font);
Serial.println(font);
if(font == 1){
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
Serial.println("💧Водичка буль, буль, хлюп, хлюп.💧");
}
}
if(fire == HIGH){
fill_solid(leds, NUM_LEDS, CRGB::Red);
fill_solid(leds2, NUM_LEDS2, CRGB::Red);
FastLED.show();
servo4.write(90);
for (int i = 0; i < sizeof(dfdp)/sizeof(String); i++){
bot.sendMessage(dfdp[i], "🔴Внимание! Возможно пожар!🔴", "");
}
}
while(fire == HIGH){
bool fire1 = !digitalRead(Pogar);
lcd.setCursor(0, 0);
lcd.print(" Attention! ");
lcd.setCursor(0, 1);
lcd.print("There may be a fire!");
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
if(fire1 == LOW){
fire = LOW;
}
}
if(phot2 > 1000){
servo3.write(90);
stO = "Prov: on ";
for (int i = 0; i < sizeof(dfdp)/sizeof(String); i++){
bot.sendMessage(dfdp[i], "🟤Внимание! Превышен CO₂!", "");
}
}
if(phot2 < 1000){
servo3.write(0);
stO = "Prov: off ";
}
if(dhtT == 24){
servo2.write(0);
stV = "Vent: off ";
stH = "Heat: off ";
}
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 ";
servo.write(0);
delay(300);
servo.write(180);
delay(300);
}
Serial.println(dok);
stat1 = 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);
FastLED.show();
}
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));
FastLED.show();
}
}
}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));
FastLED.show();
}
}
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);
}
else {
light_led= false;
Serial.println(i3r);
}
if (light_led== true && but_led==true) {
fill_solid(leds2, NUM_LEDS2, CRGB(0, 0, 0)); stOS = "Svet: off";}
FastLED.show();
if (light_led== true && but_led==false) {
fill_solid(leds2, NUM_LEDS2, CRGB(svet2, svet2, svet2)); stOS = "Svet: on";}
FastLED.show();
if (light_led== false&& but_led==true) {
fill_solid(leds2, NUM_LEDS2, CRGB::White);
stOS = "Svet: on";
FastLED.show();
}
if (light_led== false&& but_led==false) {
fill_solid(leds2, NUM_LEDS2, CRGB(0, 0, 0));
stOS = "Svet: off";
FastLED.show();
}
}
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));
FastLED.show();
}
}
float distance = readDistanceCM();
if(Hour1 > 8 && Hour1 < 20){
if(distance < 100){
servo4.write(90);
}
if(distance > 100){
servo4.write(0);
}
}
else{
if(door == true){
servo4.write(90);
}
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(stat1);
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"];
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