Advertisement
safwan092

Project_12222_ESP32_DHT11_MQ13_MQ4_adafruit_IO_MQTT_Telegram

Jul 16th, 2023
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.53 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 "6361876638:AAGQGnzloA-aK4Ck7PU7VInzkKRLS_5jOxc"
  52. String chat_id_1 = "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. "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
  82. "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
  83. "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
  84. "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
  85. "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
  86. "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
  87. "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
  88. "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
  89. "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
  90. "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
  91. "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
  92. "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
  93. "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
  94. "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
  95. "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
  96. "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
  97. "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
  98. "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
  99. "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
  100. "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
  101. "-----END CERTIFICATE-----\n";
  102.  
  103. /****************************** Feeds ***************************************/
  104.  
  105. Adafruit_MQTT_Publish Humidity_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
  106. Adafruit_MQTT_Publish Temperature_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
  107. Adafruit_MQTT_Publish gas_CO2_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/gas_CO2");
  108. Adafruit_MQTT_Publish gas_Methane_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/gas_Methane");
  109.  
  110. /********************** Telegram Bot Parameters *****************************/
  111.  
  112. const unsigned long BOT_MTBS = 1000; // mean time between scan messages
  113. WiFiClientSecure secured_client;
  114. UniversalTelegramBot bot(BOT_TOKEN, secured_client);
  115. unsigned long bot_lasttime; // last time messages' scan has been done
  116. bool Start = false;
  117.  
  118. /************************* I/O Pin Definitions *****************************/
  119.  
  120. #define MQ135_pin 34 // CO2 Gas Sensor
  121. #define MQ4_pin 35 // Methane Gas Sensor
  122. #define DHT11_pin 23 // Temperature and Humidity Sensor
  123.  
  124. /************************** Global Variables *******************************/
  125.  
  126. int MQ135_gas_RAW_Reading_CO2 = 0;
  127. int MQ4_gas_RAW_Reading_Methane = 0;
  128. float Temperature = 0;
  129. float Humidity = 0;
  130.  
  131. DHT dht(DHT11_pin, DHT11);
  132.  
  133. /*************************** Sketch Code ************************************/
  134.  
  135. void setup() {
  136. Serial.begin(115200);
  137. Initialize_Sensors();
  138. Connect_To_WiFi_And_MQTT_Server();
  139. Connect_To_Telegram_Server();
  140. bot.sendMessage(chat_id_1, "Bot Started Up - Ready");
  141. }
  142.  
  143. void loop() {
  144. Read_Sensor_Data();
  145. Handle_Telegram_Messages_From_Users_Loop();
  146. Show_Sensor_Data_on_Serial_Monitor();
  147. Publish_Sensor_Data();
  148. delay(8000);
  149. }
  150.  
  151. /*************************** Functions ************************************/
  152.  
  153. void Initialize_Sensors() {
  154. dht.begin();
  155. pinMode(MQ135_pin, INPUT);
  156. pinMode(MQ4_pin, INPUT);
  157. }
  158.  
  159. void Read_Sensor_Data() {
  160. Humidity = dht.readHumidity(); //0-100%
  161. Temperature = dht.readTemperature(); //20-60°C
  162. MQ135_gas_RAW_Reading_CO2 = analogRead(MQ135_pin); //0-4096
  163. MQ4_gas_RAW_Reading_Methane = analogRead(MQ4_pin); //0-4096
  164. }
  165.  
  166. void Show_Sensor_Data_on_Serial_Monitor() {
  167. Serial.print("Humidity: ");
  168. Serial.print(Humidity);
  169. Serial.print(" [%]");
  170. Serial.print("Temperature: ");
  171. Serial.print(Temperature);
  172. Serial.print(" [°C]");
  173. Serial.print("Gas CO2: ");
  174. Serial.print(MQ135_gas_RAW_Reading_CO2);
  175. Serial.print(" [VoltageLevel]");
  176. Serial.print("Gas Methane: ");
  177. Serial.print(MQ4_gas_RAW_Reading_Methane);
  178. Serial.print(" [VoltageLevel]");
  179. Serial.println("-----------------------------");
  180. }
  181.  
  182. void Publish_Sensor_Data() {
  183. // Ensure the connection to the MQTT server is alive (this will make the first
  184. // connection and automatically reconnect when disconnected). See the MQTT_connect
  185. // function definition further below.
  186. MQTT_connect();
  187. // Publish Humidity to MQTT Server
  188. if (!Humidity_Publish.publish(Humidity)) {
  189. Serial.println(F("Humidity_Publish: Failed"));
  190. } else {
  191. Serial.println(F("Humidity_Publish: OK!"));
  192. }
  193. // Publish Temperature to MQTT Server
  194. if (!Temperature_Publish.publish(Temperature)) {
  195. Serial.println(F("Temperature_Publish: Failed"));
  196. } else {
  197. Serial.println(F("Temperature_Publish: OK!"));
  198. }
  199. // Publish CO2 to MQTT Server
  200. if (!gas_CO2_Publish.publish(MQ135_gas_RAW_Reading_CO2)) {
  201. Serial.println(F("gas_CO2_Publish: Failed"));
  202. } else {
  203. Serial.println(F("gas_CO2_Publish: OK!"));
  204. }
  205. // Publish Methane to MQTT Server
  206. if (!gas_Methane_Publish.publish(MQ4_gas_RAW_Reading_Methane)) {
  207. Serial.println(F("gas_Methane_Publish: Failed"));
  208. } else {
  209. Serial.println(F("gas_Methane_Publish: OK!"));
  210. }
  211. }
  212.  
  213. // Function to connect and reconnect as necessary to the MQTT server.
  214. // Should be called in the loop function and it will take care if connecting.
  215. void MQTT_connect() {
  216. int8_t ret;
  217.  
  218. // Stop if already connected.
  219. if (mqtt.connected()) {
  220. return;
  221. }
  222.  
  223. Serial.print("Connecting to MQTT... ");
  224.  
  225. uint8_t retries = 3;
  226. while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
  227. Serial.println(mqtt.connectErrorString(ret));
  228. Serial.println("Retrying MQTT connection in 5 seconds...");
  229. mqtt.disconnect();
  230. delay(5000); // wait 5 seconds
  231. retries--;
  232. if (retries == 0) {
  233. // basically die and wait for WDT to reset me
  234. while (1);
  235. }
  236. }
  237.  
  238. Serial.println("MQTT Connected!");
  239. }
  240.  
  241. void Connect_To_WiFi_And_MQTT_Server() {
  242. delay(10);
  243. Serial.println(F("Adafruit IO MQTTS (SSL/TLS) Example"));
  244. // Connect to WiFi access point.
  245. Serial.println();
  246. Serial.println();
  247. Serial.print("Connecting to ");
  248. Serial.println(WLAN_SSID);
  249. delay(1000);
  250. WiFi.begin(WLAN_SSID, WLAN_PASS);
  251. delay(2000);
  252. while (WiFi.status() != WL_CONNECTED) {
  253. delay(500);
  254. Serial.print(".");
  255. }
  256. Serial.println();
  257. Serial.println("WiFi connected");
  258. Serial.println("IP address: ");
  259. Serial.println(WiFi.localIP());
  260. // Set Adafruit IO's root CA
  261. client.setCACert(adafruitio_root_ca);
  262. }
  263.  
  264. void Connect_To_Telegram_Server() {
  265. secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  266. Serial.print("Retrieving time: ");
  267. configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  268. time_t now = time(nullptr);
  269. while (now < 24 * 3600) {
  270. Serial.print(".");
  271. delay(100);
  272. now = time(nullptr);
  273. }
  274. Serial.println(now);
  275. }
  276.  
  277. void handleNewMessages(int numNewMessages) {
  278. Serial.println("handleNewMessages");
  279. Serial.println(String(numNewMessages));
  280.  
  281. for (int i = 0; i < numNewMessages; i++) {
  282. String chat_id = bot.messages[i].chat_id;
  283. String text = bot.messages[i].text;
  284.  
  285. String from_name = bot.messages[i].from_name;
  286. if (from_name == "")
  287. from_name = "Guest";
  288.  
  289. if (text == "/sensor_data") {
  290. String data_To_Send = "Humidity: ";
  291. data_To_Send += String(Humidity);
  292. data_To_Send += " [%]\n";
  293. data_To_Send += "Temperature: ";
  294. data_To_Send += String(Temperature);
  295. data_To_Send += " [°C]\n";
  296. data_To_Send += "Gas CO2: ";
  297. data_To_Send += String(MQ135_gas_RAW_Reading_CO2);
  298. data_To_Send += " [VoltageLevel]\n";
  299. data_To_Send += "Gas Methane: ";
  300. data_To_Send += String(MQ4_gas_RAW_Reading_Methane);
  301. data_To_Send += " [VoltageLevel]\n";
  302. bot.sendMessage(chat_id, data_To_Send);
  303. }
  304.  
  305. if (text == "/start") {
  306. String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
  307. welcome += "This is Chat Action Bot example.\n\n";
  308. welcome += "/send_test_action : to send test chat action message\n";
  309. bot.sendMessage(chat_id, welcome);
  310. }
  311. }
  312. }
  313.  
  314. void Handle_Telegram_Messages_From_Users_Loop() {
  315. if (millis() - bot_lasttime > BOT_MTBS) {
  316. int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  317.  
  318. while (numNewMessages) {
  319. Serial.println("got response");
  320. handleNewMessages(numNewMessages);
  321. numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  322. }
  323.  
  324. bot_lasttime = millis();
  325. }
  326. }
  327.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement