Advertisement
safwan092

Untitled

Jul 29th, 2023
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.45 KB | None | 0 0
  1. /*******************************************************************
  2. A telegram bot for your ESP32 that demonstrates a bot
  3. that show bot action message
  4.  
  5. Parts:
  6. ESP32 D1 Mini stlye Dev board* - http://s.click.aliexpress.com/e/C6ds4my
  7. (or any ESP32 board)
  8.  
  9. = Affilate
  10.  
  11. If you find what I do useful and would like to support me,
  12. please consider becoming a sponsor on Github
  13. https://github.com/sponsors/witnessmenow/
  14.  
  15. Example originally written by Vadim Sinitski
  16.  
  17. Library written by Brian Lough
  18. YouTube: https://www.youtube.com/brianlough
  19. Tindie: https://www.tindie.com/stores/brianlough/
  20. Twitter: https://twitter.com/witnessmenow
  21. *******************************************************************/
  22. /***********************************************************************
  23. Adafruit MQTT Library ESP32 Adafruit IO SSL/TLS example
  24.  
  25. Use the latest version of the ESP32 Arduino Core:
  26. https://github.com/espressif/arduino-esp32
  27.  
  28. Works great with Adafruit Huzzah32 Feather and Breakout Board:
  29. https://www.adafruit.com/product/3405
  30. https://www.adafruit.com/products/4172
  31.  
  32. Adafruit invests time and resources providing this open source code,
  33. please support Adafruit and open-source hardware by purchasing
  34. products from Adafruit!
  35.  
  36. Written by Tony DiCola for Adafruit Industries.
  37. Modified by Brent Rubell for Adafruit Industries
  38. MIT license, all text above must be included in any redistribution
  39. Modified by <programmer_name>
  40. **********************************************************************/
  41. #include <DHT.h>
  42. #include <WiFi.h>
  43. #include "WiFiClientSecure.h"
  44. #include "Adafruit_MQTT.h"
  45. #include "Adafruit_MQTT_Client.h"
  46. #include <UniversalTelegramBot.h>
  47.  
  48. /************************* Telegram Setup *********************************/
  49.  
  50. // Telegram BOT Token (Get from Botfather)
  51. #define BOT_TOKEN "6347871203:AAHWCFbTNmDwYbJaj2pdXixsHwAYNEbjAVY"//"6361876638:AAGQGnzloA-aK4Ck7PU7VInzkKRLS_5jOxc"
  52. String chat_id_1 = "-951130290";//"473975732";
  53. /************************* WiFi Access Point *********************************/
  54.  
  55. #define WLAN_SSID "network"
  56. #define WLAN_PASS "123456789"
  57.  
  58. /************************* Adafruit.io Setup *********************************/
  59.  
  60. #define AIO_SERVER "io.adafruit.com"
  61.  
  62. // Using port 8883 for MQTTS
  63. #define AIO_SERVERPORT 8883
  64.  
  65. // Adafruit IO Account Configuration
  66. // (to obtain these values, visit https://io.adafruit.com and click on Active Key)
  67. #define AIO_USERNAME "coltokesti"
  68. #define AIO_KEY "aio_vMJM57FOuX6m0ipW0RLTrBiM7sqq"
  69.  
  70. /************ Global State (you don't need to change this!) ******************/
  71.  
  72. // WiFiFlientSecure for SSL/TLS support
  73. WiFiClientSecure client;
  74.  
  75. // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
  76. Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
  77.  
  78. // io.adafruit.com root CA
  79. const char* adafruitio_root_ca = \
  80. "-----BEGIN CERTIFICATE-----\n"
  81. "MIIEjTCCA3WgAwIBAgIQDQd4KhM/xvmlcpbhMf/ReTANBgkqhkiG9w0BAQsFADBh\n"
  82. "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
  83. "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\n"
  84. "MjAeFw0xNzExMDIxMjIzMzdaFw0yNzExMDIxMjIzMzdaMGAxCzAJBgNVBAYTAlVT\n"
  85. "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
  86. "b20xHzAdBgNVBAMTFkdlb1RydXN0IFRMUyBSU0EgQ0EgRzEwggEiMA0GCSqGSIb3\n"
  87. "DQEBAQUAA4IBDwAwggEKAoIBAQC+F+jsvikKy/65LWEx/TMkCDIuWegh1Ngwvm4Q\n"
  88. "y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GmEGZtYLyF8EQpa5Y\n"
  103. "jPuV6k2Cr/N3XxFpT3hRpt/3usU/Zb9wfKPtWpoznZ4/44c1p9rzFcZYrWkj3A+7\n"
  104. "TNBJE0GmP2fhXhP1D/XVfIW/h0yCJGEiV9Glm/uGOa3DXHlmbAcxSyCRraG+ZBkA\n"
  105. "7h4SeM6Y8l/7MBRpPCz6l8Y=\n"
  106. "-----END CERTIFICATE-----\n";
  107.  
  108. /****************************** Feeds ***************************************/
  109.  
  110. Adafruit_MQTT_Publish Humidity_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
  111. Adafruit_MQTT_Publish Temperature_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
  112. Adafruit_MQTT_Publish gas_CO2_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/gas_CO2");
  113. Adafruit_MQTT_Publish gas_Methane_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/gas_Methane");
  114.  
  115. /********************** Telegram Bot Parameters *****************************/
  116.  
  117. const unsigned long BOT_MTBS = 1000; // mean time between scan messages
  118. WiFiClientSecure secured_client;
  119. UniversalTelegramBot bot(BOT_TOKEN, secured_client);
  120. unsigned long bot_lasttime; // last time messages' scan has been done
  121. bool Start = false;
  122.  
  123. /************************* I/O Pin Definitions *****************************/
  124.  
  125. #define MQ135_pin 34 // CO2 Gas Sensor
  126. #define MQ4_pin 35 // Methane Gas Sensor
  127. #define DHT11_pin 23 // Temperature and Humidity Sensor
  128. #define Buzzer_pin 18 // Buzzer (+) Connection
  129. #define RED_LED_Pin 4 // Red LED Anode (+) Connection
  130.  
  131. /************************** Global Variables *******************************/
  132.  
  133. int MQ135_gas_RAW_Reading_CO2 = 0;
  134. int MQ4_gas_RAW_Reading_Methane = 0;
  135. float Temperature = 0;
  136. float Humidity = 0;
  137.  
  138. DHT dht(DHT11_pin, DHT11);
  139.  
  140. /*************************** Sketch Code ************************************/
  141.  
  142. void setup() {
  143. Serial.begin(115200);
  144. Initialize_Sensors();
  145. Connect_To_WiFi_And_MQTT_Server();
  146. Connect_To_Telegram_Server();
  147. bot.sendMessage(chat_id_1, "Bot Started Up - Ready");
  148. Alert_LED_and_Buzzer(3, 50);
  149. }
  150.  
  151. void loop() {
  152. Read_Sensor_Data();
  153. if (MQ135_gas_RAW_Reading_CO2 > 700 || MQ4_gas_RAW_Reading_Methane > 4000) {
  154. Alert_LED_and_Buzzer(1, 2000);
  155. bot.sendMessage(chat_id_1, "Alert - High Gas Concentration !!");
  156. }
  157. Handle_Telegram_Messages_From_Users_Loop();
  158. Show_Sensor_Data_on_Serial_Monitor();
  159. Publish_Sensor_Data();
  160. delay(8000);
  161. }
  162.  
  163. /*************************** Functions ************************************/
  164.  
  165. void Initialize_Sensors() {
  166. dht.begin();
  167. pinMode(MQ135_pin, INPUT);
  168. pinMode(MQ4_pin, INPUT);
  169. pinMode(Buzzer_pin, OUTPUT);
  170. pinMode(RED_LED_Pin, OUTPUT);
  171. digitalWrite(Buzzer_pin, LOW);
  172. digitalWrite(RED_LED_Pin, LOW);
  173. }
  174.  
  175. void Read_Sensor_Data() {
  176. Humidity = dht.readHumidity(); //0-100%
  177. Temperature = dht.readTemperature(); //20-60°C
  178. MQ135_gas_RAW_Reading_CO2 = analogRead(MQ135_pin); //0-4096
  179. MQ4_gas_RAW_Reading_Methane = analogRead(MQ4_pin); //0-4096
  180. }
  181.  
  182. void Show_Sensor_Data_on_Serial_Monitor() {
  183. Serial.print("Humidity: ");
  184. Serial.print(Humidity);
  185. Serial.print(" [%]");
  186. Serial.print("Temperature: ");
  187. Serial.print(Temperature);
  188. Serial.print(" [°C]");
  189. Serial.print("Gas CO2: ");
  190. Serial.print(MQ135_gas_RAW_Reading_CO2);
  191. Serial.print(" [VoltageLevel]");
  192. Serial.print("Gas Methane: ");
  193. Serial.print(MQ4_gas_RAW_Reading_Methane);
  194. Serial.print(" [VoltageLevel]");
  195. Serial.println("-----------------------------");
  196. }
  197.  
  198. void Publish_Sensor_Data() {
  199. // Ensure the connection to the MQTT server is alive (this will make the first
  200. // connection and automatically reconnect when disconnected). See the MQTT_connect
  201. // function definition further below.
  202. MQTT_connect();
  203. // Publish Humidity to MQTT Server
  204. if (!Humidity_Publish.publish(Humidity)) {
  205. Serial.println(F("Humidity_Publish: Failed"));
  206. } else {
  207. Serial.println(F("Humidity_Publish: OK!"));
  208. }
  209. // Publish Temperature to MQTT Server
  210. if (!Temperature_Publish.publish(Temperature)) {
  211. Serial.println(F("Temperature_Publish: Failed"));
  212. } else {
  213. Serial.println(F("Temperature_Publish: OK!"));
  214. }
  215. // Publish CO2 to MQTT Server
  216. if (!gas_CO2_Publish.publish(MQ135_gas_RAW_Reading_CO2)) {
  217. Serial.println(F("gas_CO2_Publish: Failed"));
  218. } else {
  219. Serial.println(F("gas_CO2_Publish: OK!"));
  220. }
  221. // Publish Methane to MQTT Server
  222. if (!gas_Methane_Publish.publish(MQ4_gas_RAW_Reading_Methane)) {
  223. Serial.println(F("gas_Methane_Publish: Failed"));
  224. } else {
  225. Serial.println(F("gas_Methane_Publish: OK!"));
  226. }
  227. }
  228.  
  229. // Function to connect and reconnect as necessary to the MQTT server.
  230. // Should be called in the loop function and it will take care if connecting.
  231. void MQTT_connect() {
  232. int8_t ret;
  233.  
  234. // Stop if already connected.
  235. if (mqtt.connected()) {
  236. return;
  237. }
  238.  
  239. Serial.print("Connecting to MQTT... ");
  240.  
  241. uint8_t retries = 3;
  242. while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
  243. Serial.println(mqtt.connectErrorString(ret));
  244. Serial.println("Retrying MQTT connection in 5 seconds...");
  245. mqtt.disconnect();
  246. delay(5000); // wait 5 seconds
  247. retries--;
  248. if (retries == 0) {
  249. // basically die and wait for WDT to reset me
  250. while (1);
  251. }
  252. }
  253.  
  254. Serial.println("MQTT Connected!");
  255. }
  256.  
  257. void Connect_To_WiFi_And_MQTT_Server() {
  258. delay(10);
  259. Serial.println(F("Adafruit IO MQTTS (SSL/TLS) Example"));
  260. // Connect to WiFi access point.
  261. Serial.println();
  262. Serial.println();
  263. Serial.print("Connecting to ");
  264. Serial.println(WLAN_SSID);
  265. delay(1000);
  266. WiFi.begin(WLAN_SSID, WLAN_PASS);
  267. delay(2000);
  268. while (WiFi.status() != WL_CONNECTED) {
  269. delay(500);
  270. Serial.print(".");
  271. }
  272. Serial.println();
  273. Serial.println("WiFi connected");
  274. Serial.println("IP address: ");
  275. Serial.println(WiFi.localIP());
  276. // Set Adafruit IO's root CA
  277. client.setCACert(adafruitio_root_ca);
  278. }
  279.  
  280. void Connect_To_Telegram_Server() {
  281. secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  282. Serial.print("Retrieving time: ");
  283. configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  284. time_t now = time(nullptr);
  285. while (now < 24 * 3600) {
  286. Serial.print(".");
  287. delay(100);
  288. now = time(nullptr);
  289. }
  290. Serial.println(now);
  291. }
  292.  
  293. void handleNewMessages(int numNewMessages) {
  294. Serial.println("handleNewMessages");
  295. Serial.println(String(numNewMessages));
  296.  
  297. for (int i = 0; i < numNewMessages; i++) {
  298. String chat_id = bot.messages[i].chat_id;
  299. String text = bot.messages[i].text;
  300.  
  301. String from_name = bot.messages[i].from_name;
  302. if (from_name == "")
  303. from_name = "Guest";
  304.  
  305. if (text == "/sensor_data") {
  306. String data_To_Send = "Humidity: ";
  307. data_To_Send += String(Humidity);
  308. data_To_Send += " [%]\n";
  309. data_To_Send += "Temperature: ";
  310. data_To_Send += String(Temperature);
  311. data_To_Send += " [°C]\n";
  312. data_To_Send += "Gas CO2: ";
  313. data_To_Send += String(MQ135_gas_RAW_Reading_CO2);
  314. data_To_Send += " [VoltageLevel]\n";
  315. data_To_Send += "Gas Methane: ";
  316. data_To_Send += String(MQ4_gas_RAW_Reading_Methane);
  317. data_To_Send += " [VoltageLevel]\n";
  318. bot.sendMessage(chat_id, data_To_Send);
  319. }
  320.  
  321. if (text == "/start") {
  322. String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
  323. welcome += "This is Chat Action Bot example.\n\n";
  324. welcome += "/send_test_action : to send test chat action message\n";
  325. bot.sendMessage(chat_id, welcome);
  326. }
  327. }
  328. }
  329.  
  330. void Handle_Telegram_Messages_From_Users_Loop() {
  331. if (millis() - bot_lasttime > BOT_MTBS) {
  332. int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  333.  
  334. while (numNewMessages) {
  335. Serial.println("got response");
  336. handleNewMessages(numNewMessages);
  337. numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  338. }
  339.  
  340. bot_lasttime = millis();
  341. }
  342. }
  343.  
  344. void Alert_LED_and_Buzzer(int n, int T) {
  345. for (int i = 0; i < n; i++) {
  346. digitalWrite(Buzzer_pin, HIGH);
  347. digitalWrite(RED_LED_Pin, HIGH);
  348. delay(T);
  349. digitalWrite(Buzzer_pin, LOW);
  350. digitalWrite(RED_LED_Pin, LOW);
  351. delay(T);
  352. }
  353. }
  354.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement