Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*******************************************************************
- A telegram bot for your ESP32 that demonstrates a bot
- that show bot action message
- Parts:
- ESP32 D1 Mini stlye Dev board* - http://s.click.aliexpress.com/e/C6ds4my
- (or any ESP32 board)
- = Affilate
- If you find what I do useful and would like to support me,
- please consider becoming a sponsor on Github
- https://github.com/sponsors/witnessmenow/
- Example originally written by Vadim Sinitski
- Library written by Brian Lough
- YouTube: https://www.youtube.com/brianlough
- Tindie: https://www.tindie.com/stores/brianlough/
- Twitter: https://twitter.com/witnessmenow
- *******************************************************************/
- /***********************************************************************
- Adafruit MQTT Library ESP32 Adafruit IO SSL/TLS example
- Use the latest version of the ESP32 Arduino Core:
- https://github.com/espressif/arduino-esp32
- Works great with Adafruit Huzzah32 Feather and Breakout Board:
- https://www.adafruit.com/product/3405
- https://www.adafruit.com/products/4172
- Adafruit invests time and resources providing this open source code,
- please support Adafruit and open-source hardware by purchasing
- products from Adafruit!
- Written by Tony DiCola for Adafruit Industries.
- Modified by Brent Rubell for Adafruit Industries
- MIT license, all text above must be included in any redistribution
- Modified by <programmer_name>
- **********************************************************************/
- #include <DHT.h>
- #include <WiFi.h>
- #include "WiFiClientSecure.h"
- #include "Adafruit_MQTT.h"
- #include "Adafruit_MQTT_Client.h"
- #include <UniversalTelegramBot.h>
- /************************* Telegram Setup *********************************/
- // Telegram BOT Token (Get from Botfather)
- #define BOT_TOKEN "6347871203:AAHWCFbTNmDwYbJaj2pdXixsHwAYNEbjAVY"//"6361876638:AAGQGnzloA-aK4Ck7PU7VInzkKRLS_5jOxc"
- String chat_id_1 = "-951130290";//"473975732";
- /************************* WiFi Access Point *********************************/
- #define WLAN_SSID "network"
- #define WLAN_PASS "123456789"
- /************************* Adafruit.io Setup *********************************/
- #define AIO_SERVER "io.adafruit.com"
- // Using port 8883 for MQTTS
- #define AIO_SERVERPORT 8883
- // Adafruit IO Account Configuration
- // (to obtain these values, visit https://io.adafruit.com and click on Active Key)
- #define AIO_USERNAME "coltokesti"
- #define AIO_KEY "aio_vMJM57FOuX6m0ipW0RLTrBiM7sqq"
- /************ Global State (you don't need to change this!) ******************/
- // WiFiFlientSecure for SSL/TLS support
- WiFiClientSecure client;
- // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
- Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
- // io.adafruit.com root CA
- const char* adafruitio_root_ca = \
- "-----BEGIN CERTIFICATE-----\n"
- "MIIEjTCCA3WgAwIBAgIQDQd4KhM/xvmlcpbhMf/ReTANBgkqhkiG9w0BAQsFADBh\n"
- "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
- "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\n"
- "MjAeFw0xNzExMDIxMjIzMzdaFw0yNzExMDIxMjIzMzdaMGAxCzAJBgNVBAYTAlVT\n"
- "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
- "b20xHzAdBgNVBAMTFkdlb1RydXN0IFRMUyBSU0EgQ0EgRzEwggEiMA0GCSqGSIb3\n"
- "DQEBAQUAA4IBDwAwggEKAoIBAQC+F+jsvikKy/65LWEx/TMkCDIuWegh1Ngwvm4Q\n"
- "yISgP7oU5d79eoySG3vOhC3w/3jEMuipoH1fBtp7m0tTpsYbAhch4XA7rfuD6whU\n"
- "gajeErLVxoiWMPkC/DnUvbgi74BJmdBiuGHQSd7LwsuXpTEGG9fYXcbTVN5SATYq\n"
- "DfbexbYxTMwVJWoVb6lrBEgM3gBBqiiAiy800xu1Nq07JdCIQkBsNpFtZbIZhsDS\n"
- "fzlGWP4wEmBQ3O67c+ZXkFr2DcrXBEtHam80Gp2SNhou2U5U7UesDL/xgLK6/0d7\n"
- "6TnEVMSUVJkZ8VeZr+IUIlvoLrtjLbqugb0T3OYXW+CQU0kBAgMBAAGjggFAMIIB\n"
- "PDAdBgNVHQ4EFgQUlE/UXYvkpOKmgP792PkA76O+AlcwHwYDVR0jBBgwFoAUTiJU\n"
- "IBiV5uNu5g/6+rkS7QYXjzkwDgYDVR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsG\n"
- "AQUFBwMBBggrBgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMDQGCCsGAQUFBwEB\n"
- "BCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEIGA1Ud\n"
- "HwQ7MDkwN6A1oDOGMWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEds\n"
- "b2JhbFJvb3RHMi5jcmwwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEW\n"
- "HGh0dHBzOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwDQYJKoZIhvcNAQELBQADggEB\n"
- "AIIcBDqC6cWpyGUSXAjjAcYwsK4iiGF7KweG97i1RJz1kwZhRoo6orU1JtBYnjzB\n"
- "c4+/sXmnHJk3mlPyL1xuIAt9sMeC7+vreRIF5wFBC0MCN5sbHwhNN1JzKbifNeP5\n"
- "ozpZdQFmkCo+neBiKR6HqIA+LMTMCMMuv2khGGuPHmtDze4GmEGZtYLyF8EQpa5Y\n"
- "jPuV6k2Cr/N3XxFpT3hRpt/3usU/Zb9wfKPtWpoznZ4/44c1p9rzFcZYrWkj3A+7\n"
- "TNBJE0GmP2fhXhP1D/XVfIW/h0yCJGEiV9Glm/uGOa3DXHlmbAcxSyCRraG+ZBkA\n"
- "7h4SeM6Y8l/7MBRpPCz6l8Y=\n"
- "-----END CERTIFICATE-----\n";
- /****************************** Feeds ***************************************/
- Adafruit_MQTT_Publish Humidity_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
- Adafruit_MQTT_Publish Temperature_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
- Adafruit_MQTT_Publish gas_CO2_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/gas_CO2");
- Adafruit_MQTT_Publish gas_Methane_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/gas_Methane");
- /********************** Telegram Bot Parameters *****************************/
- const unsigned long BOT_MTBS = 1000; // mean time between scan messages
- WiFiClientSecure secured_client;
- UniversalTelegramBot bot(BOT_TOKEN, secured_client);
- unsigned long bot_lasttime; // last time messages' scan has been done
- bool Start = false;
- /************************* I/O Pin Definitions *****************************/
- #define MQ135_pin 34 // CO2 Gas Sensor
- #define MQ4_pin 35 // Methane Gas Sensor
- #define DHT11_pin 23 // Temperature and Humidity Sensor
- #define Buzzer_pin 18 // Buzzer (+) Connection
- #define RED_LED_Pin 4 // Red LED Anode (+) Connection
- /************************** Global Variables *******************************/
- int MQ135_gas_RAW_Reading_CO2 = 0;
- int MQ4_gas_RAW_Reading_Methane = 0;
- float Temperature = 0;
- float Humidity = 0;
- DHT dht(DHT11_pin, DHT11);
- /*************************** Sketch Code ************************************/
- void setup() {
- Serial.begin(115200);
- Initialize_Sensors();
- Connect_To_WiFi_And_MQTT_Server();
- Connect_To_Telegram_Server();
- bot.sendMessage(chat_id_1, "Bot Started Up - Ready");
- Alert_LED_and_Buzzer(3, 50);
- }
- void loop() {
- Read_Sensor_Data();
- if (MQ135_gas_RAW_Reading_CO2 > 700 || MQ4_gas_RAW_Reading_Methane > 4000) {
- Alert_LED_and_Buzzer(1, 2000);
- bot.sendMessage(chat_id_1, "Alert - High Gas Concentration !!");
- }
- Handle_Telegram_Messages_From_Users_Loop();
- Show_Sensor_Data_on_Serial_Monitor();
- Publish_Sensor_Data();
- delay(8000);
- }
- /*************************** Functions ************************************/
- void Initialize_Sensors() {
- dht.begin();
- pinMode(MQ135_pin, INPUT);
- pinMode(MQ4_pin, INPUT);
- pinMode(Buzzer_pin, OUTPUT);
- pinMode(RED_LED_Pin, OUTPUT);
- digitalWrite(Buzzer_pin, LOW);
- digitalWrite(RED_LED_Pin, LOW);
- }
- void Read_Sensor_Data() {
- Humidity = dht.readHumidity(); //0-100%
- Temperature = dht.readTemperature(); //20-60°C
- MQ135_gas_RAW_Reading_CO2 = analogRead(MQ135_pin); //0-4096
- MQ4_gas_RAW_Reading_Methane = analogRead(MQ4_pin); //0-4096
- }
- void Show_Sensor_Data_on_Serial_Monitor() {
- Serial.print("Humidity: ");
- Serial.print(Humidity);
- Serial.print(" [%]");
- Serial.print("Temperature: ");
- Serial.print(Temperature);
- Serial.print(" [°C]");
- Serial.print("Gas CO2: ");
- Serial.print(MQ135_gas_RAW_Reading_CO2);
- Serial.print(" [VoltageLevel]");
- Serial.print("Gas Methane: ");
- Serial.print(MQ4_gas_RAW_Reading_Methane);
- Serial.print(" [VoltageLevel]");
- Serial.println("-----------------------------");
- }
- void Publish_Sensor_Data() {
- // Ensure the connection to the MQTT server is alive (this will make the first
- // connection and automatically reconnect when disconnected). See the MQTT_connect
- // function definition further below.
- MQTT_connect();
- // Publish Humidity to MQTT Server
- if (!Humidity_Publish.publish(Humidity)) {
- Serial.println(F("Humidity_Publish: Failed"));
- } else {
- Serial.println(F("Humidity_Publish: OK!"));
- }
- // Publish Temperature to MQTT Server
- if (!Temperature_Publish.publish(Temperature)) {
- Serial.println(F("Temperature_Publish: Failed"));
- } else {
- Serial.println(F("Temperature_Publish: OK!"));
- }
- // Publish CO2 to MQTT Server
- if (!gas_CO2_Publish.publish(MQ135_gas_RAW_Reading_CO2)) {
- Serial.println(F("gas_CO2_Publish: Failed"));
- } else {
- Serial.println(F("gas_CO2_Publish: OK!"));
- }
- // Publish Methane to MQTT Server
- if (!gas_Methane_Publish.publish(MQ4_gas_RAW_Reading_Methane)) {
- Serial.println(F("gas_Methane_Publish: Failed"));
- } else {
- Serial.println(F("gas_Methane_Publish: OK!"));
- }
- }
- // Function to connect and reconnect as necessary to the MQTT server.
- // Should be called in the loop function and it will take care if connecting.
- void MQTT_connect() {
- int8_t ret;
- // Stop if already connected.
- if (mqtt.connected()) {
- return;
- }
- Serial.print("Connecting to MQTT... ");
- uint8_t retries = 3;
- while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
- Serial.println(mqtt.connectErrorString(ret));
- Serial.println("Retrying MQTT connection in 5 seconds...");
- mqtt.disconnect();
- delay(5000); // wait 5 seconds
- retries--;
- if (retries == 0) {
- // basically die and wait for WDT to reset me
- while (1);
- }
- }
- Serial.println("MQTT Connected!");
- }
- void Connect_To_WiFi_And_MQTT_Server() {
- delay(10);
- Serial.println(F("Adafruit IO MQTTS (SSL/TLS) Example"));
- // Connect to WiFi access point.
- Serial.println();
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(WLAN_SSID);
- delay(1000);
- WiFi.begin(WLAN_SSID, WLAN_PASS);
- delay(2000);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println();
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- // Set Adafruit IO's root CA
- client.setCACert(adafruitio_root_ca);
- }
- void Connect_To_Telegram_Server() {
- secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
- 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);
- }
- void handleNewMessages(int numNewMessages) {
- Serial.println("handleNewMessages");
- Serial.println(String(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;
- if (from_name == "")
- from_name = "Guest";
- if (text == "/sensor_data") {
- String data_To_Send = "Humidity: ";
- data_To_Send += String(Humidity);
- data_To_Send += " [%]\n";
- data_To_Send += "Temperature: ";
- data_To_Send += String(Temperature);
- data_To_Send += " [°C]\n";
- data_To_Send += "Gas CO2: ";
- data_To_Send += String(MQ135_gas_RAW_Reading_CO2);
- data_To_Send += " [VoltageLevel]\n";
- data_To_Send += "Gas Methane: ";
- data_To_Send += String(MQ4_gas_RAW_Reading_Methane);
- data_To_Send += " [VoltageLevel]\n";
- bot.sendMessage(chat_id, data_To_Send);
- }
- if (text == "/start") {
- String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
- welcome += "This is Chat Action Bot example.\n\n";
- welcome += "/send_test_action : to send test chat action message\n";
- bot.sendMessage(chat_id, welcome);
- }
- }
- }
- void Handle_Telegram_Messages_From_Users_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();
- }
- }
- void Alert_LED_and_Buzzer(int n, int T) {
- for (int i = 0; i < n; i++) {
- digitalWrite(Buzzer_pin, HIGH);
- digitalWrite(RED_LED_Pin, HIGH);
- delay(T);
- digitalWrite(Buzzer_pin, LOW);
- digitalWrite(RED_LED_Pin, LOW);
- delay(T);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement