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 "6361876638:AAGQGnzloA-aK4Ck7PU7VInzkKRLS_5jOxc"
- String chat_id_1 = "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"
- "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
- "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
- "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
- "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
- "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
- "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
- "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
- "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
- "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
- "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
- "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
- "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
- "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
- "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
- "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
- "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
- "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
- "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
- "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
- "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\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
- /************************** 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");
- }
- void loop() {
- Read_Sensor_Data();
- 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);
- }
- 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();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement