safwan092

DR.Sahbi_Project_24-11-2024_Tested

Nov 24th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.80 KB | None | 0 0
  1. //***********************************************************************************************************************
  2. //***********************************************[ Included Libraries ]**************************************************
  3. #include <WiFi.h>
  4. #include <WiFiClientSecure.h>
  5. #include <UniversalTelegramBot.h>
  6. #include "Adafruit_MQTT.h"
  7. #include "Adafruit_MQTT_Client.h"
  8. #include <ArduinoJson.h>
  9. #include <OneWire.h>
  10. #include <DallasTemperature.h>
  11. //***********************************************************************************************************************
  12. //***********************************************************************************************************************
  13. //**************************************************[ Pin Definitions ]**************************************************
  14. //Pump Relay Connections
  15. const int pumpRelayPin = 21;
  16. //TDS Sensor Connections
  17. const int TdsSensorPin = 34;
  18. //DS18B20 Sensor Connections
  19. const int oneWireBus = 4;
  20. //Ultrasonic Sensor Connections
  21. const int trigPin = 5;
  22. const int echoPin = 18;
  23. //***********************************************************************************************************************
  24. //***********************************************************************************************************************
  25. //**************************************************[ Web Dashboard Setup ]**********************************************
  26. /************************* WiFi Access Point *********************************/
  27. const char* ssid = "network";
  28. const char* password = "123456789";
  29. /************************* Telegram Setup ************************************/
  30. #define BOTtoken "7659855835:AAH-p1outEnBtW4eWhUcFWD29kLYkdjFUPA"
  31. #define CHAT_ID "-4533797433"
  32. /*********************** MQTT Account Setup **********************************/
  33. #define AIO_USERNAME "project19102024"
  34. #define AIO_KEY "aio_oONO288tq2G4GFfzGQTyhL3jaNUw"
  35.  
  36. #define AIO_SERVER "io.adafruit.com"
  37. // Using port 8883 for MQTTS
  38. #define AIO_SERVERPORT 8883
  39. // Adafruit IO Account Configuration
  40. // (to obtain these values, visit https://io.adafruit.com and click on Active Key)
  41. /************ Global State (you don't need to change this!) ******************/
  42. // WiFiFlientSecure for SSL/TLS support
  43. WiFiClientSecure client;
  44. // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
  45. Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
  46. // io.adafruit.com root CA
  47. const char* adafruitio_root_ca =
  48. "-----BEGIN CERTIFICATE-----\n"
  49. "MIIEjTCCA3WgAwIBAgIQDQd4KhM/xvmlcpbhMf/ReTANBgkqhkiG9w0BAQsFADBh\n"
  50. "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
  51. "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\n"
  52. "MjAeFw0xNzExMDIxMjIzMzdaFw0yNzExMDIxMjIzMzdaMGAxCzAJBgNVBAYTAlVT\n"
  53. "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
  54. "b20xHzAdBgNVBAMTFkdlb1RydXN0IFRMUyBSU0EgQ0EgRzEwggEiMA0GCSqGSIb3\n"
  55. "DQEBAQUAA4IBDwAwggEKAoIBAQC+F+jsvikKy/65LWEx/TMkCDIuWegh1Ngwvm4Q\n"
  56. "yISgP7oU5d79eoySG3vOhC3w/3jEMuipoH1fBtp7m0tTpsYbAhch4XA7rfuD6whU\n"
  57. "gajeErLVxoiWMPkC/DnUvbgi74BJmdBiuGHQSd7LwsuXpTEGG9fYXcbTVN5SATYq\n"
  58. "DfbexbYxTMwVJWoVb6lrBEgM3gBBqiiAiy800xu1Nq07JdCIQkBsNpFtZbIZhsDS\n"
  59. "fzlGWP4wEmBQ3O67c+ZXkFr2DcrXBEtHam80Gp2SNhou2U5U7UesDL/xgLK6/0d7\n"
  60. "6TnEVMSUVJkZ8VeZr+IUIlvoLrtjLbqugb0T3OYXW+CQU0kBAgMBAAGjggFAMIIB\n"
  61. "PDAdBgNVHQ4EFgQUlE/UXYvkpOKmgP792PkA76O+AlcwHwYDVR0jBBgwFoAUTiJU\n"
  62. "IBiV5uNu5g/6+rkS7QYXjzkwDgYDVR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsG\n"
  63. "AQUFBwMBBggrBgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMDQGCCsGAQUFBwEB\n"
  64. "BCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEIGA1Ud\n"
  65. "HwQ7MDkwN6A1oDOGMWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEds\n"
  66. "b2JhbFJvb3RHMi5jcmwwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEW\n"
  67. "HGh0dHBzOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwDQYJKoZIhvcNAQELBQADggEB\n"
  68. "AIIcBDqC6cWpyGUSXAjjAcYwsK4iiGF7KweG97i1RJz1kwZhRoo6orU1JtBYnjzB\n"
  69. "c4+/sXmnHJk3mlPyL1xuIAt9sMeC7+vreRIF5wFBC0MCN5sbHwhNN1JzKbifNeP5\n"
  70. "ozpZdQFmkCo+neBiKR6HqIA+LMTMCMMuv2khGGuPHmtDze4GmEGZtYLyF8EQpa5Y\n"
  71. "jPuV6k2Cr/N3XxFpT3hRpt/3usU/Zb9wfKPtWpoznZ4/44c1p9rzFcZYrWkj3A+7\n"
  72. "TNBJE0GmP2fhXhP1D/XVfIW/h0yCJGEiV9Glm/uGOa3DXHlmbAcxSyCRraG+ZBkA\n"
  73. "7h4SeM6Y8l/7MBRpPCz6l8Y=\n"
  74. "-----END CERTIFICATE-----\n";
  75. /****************************** Feeds ***************************************/
  76. //Data Rate Limit: The free account has a limit of 30 data points per minute
  77. //e.g. [5] Data points every [10] seconds gives [30] data points every [1 minute]
  78. //increasing interval between sending data points to avoid restriction on the account
  79. static unsigned long timeBetweenDataPointsToBeSent = 12000;
  80. Adafruit_MQTT_Publish distance_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/distance_mqtt");
  81. Adafruit_MQTT_Publish volume_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/volume_mqtt");
  82. Adafruit_MQTT_Publish waterLevel_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/waterLevel_mqtt");
  83. Adafruit_MQTT_Publish temprature_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temprature_mqtt");
  84. Adafruit_MQTT_Publish tds_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/tds_mqtt");
  85. //***********************************************************************************************************************
  86. //***********************************************************************************************************************
  87. //******************************************[ Variables for TDS Sensor ]*************************************************
  88. #define VREF 3.3 // Reference voltage of ESP32 (3.3V for most ESP32 boards)
  89. #define ADC_RESOLUTION 4095 // 12-bit ADC resolution for ESP32
  90. float temperature = 25; // Temperature in Celsius, adjust as needed
  91. float calibrationFactor = 2; // TDS calibration factor (default 0.5 for most sensors)
  92. //86 ppm
  93. int analogValueTDS;
  94. float voltageTDS;
  95. float tdsValue;
  96. //***********************************************************************************************************************
  97. //***********************************************************************************************************************
  98. //***********************************************[ Read TDS Sensor Function ]********************************************
  99. void ReadTDSSensor() {
  100. analogValueTDS = analogRead(TdsSensorPin); // Read analog value from sensor
  101. voltageTDS = analogValueTDS * VREF / ADC_RESOLUTION; // Convert to voltageTDS
  102. tdsValue = (voltageTDS / calibrationFactor) * 1000; // Calculate TDS in ppm
  103. tdsValue = tdsValue / (1.0 + 0.02 * (25 - 25.0)); // Temperature compensation
  104. Serial.println("-------------------------");
  105. Serial.print("TDS Value: ");
  106. Serial.print(tdsValue, 2);
  107. Serial.println(" ppm");
  108. Serial.println("-------------------------");
  109. }
  110. //***********************************************************************************************************************
  111. //***********************************************************************************************************************
  112. //**************************************************[ Telegram Setup ]***************************************************
  113. WiFiClientSecure Sclient;
  114. UniversalTelegramBot bot(BOTtoken, Sclient);
  115. unsigned long bot_lasttime;
  116. unsigned long mqtt_lasttime;
  117. bool Start = false;
  118. float value1 = 0;
  119. float value2 = 0;
  120. //***********************************************************************************************************************
  121. //***********************************************************************************************************************
  122. //******************************************[ Variables for Ultrasonic Sensor ]******************************************
  123. //define sound speed in cm/uS
  124. #define SOUND_SPEED 0.034
  125. float radius = 17; //half the diameter in [CM]
  126. float hight = 22; //hight of the container in [CM]
  127. long duration;
  128. float distanceCm;
  129. float volume_cm3;
  130. int waterLevel;
  131. int pumpONFlag = 0;
  132. int lastSentRange = -1; // Stores the last level sent to avoid repeated messages
  133. //***********************************************************************************************************************
  134. //***********************************************************************************************************************
  135. //*****************************************[ Temprature Sensor Setup ]***************************************************
  136. OneWire oneWire(oneWireBus);
  137. DallasTemperature sensors(&oneWire);
  138. float temperatureC;
  139. //***********************************************************************************************************************
  140. //***********************************************************************************************************************
  141. //**************************************************[ Main Setup Function ]**********************************************
  142. void setup() {
  143. Serial.begin(115200);
  144. SetupSensors();
  145. pumpOFF();
  146. SetupWiFiandTelegramBot();
  147. bot.sendMessage(CHAT_ID, "ESP32 Started");
  148. }
  149. //***********************************************************************************************************************
  150. //***********************************************************************************************************************
  151. //**************************************************[ Main Loop Function ]***********************************************
  152. void loop() {
  153. ReadDistanceUsingUltrasonicSensor();
  154. ReceiveMessageFromTelegram();
  155. ReadTempratureSensor();
  156. Publish_Sensor_Data();
  157. ReadTDSSensor();
  158. if (waterLevel < 10 && pumpONFlag == 0) {
  159. pumpON();
  160. pumpONFlag = 1;
  161. }
  162. else if (waterLevel > 90 && pumpONFlag == 1) {
  163. pumpOFF();
  164. pumpONFlag = 0;
  165. }
  166. int currentRange = getRange(waterLevel);
  167. // Check if the water level has changed
  168. if (currentRange != lastSentRange) {
  169. sendWaterLevelMessage(currentRange);
  170. lastSentRange = currentRange; // Update the last sent range
  171. }
  172. /*
  173. if (waterLevel == 50) {
  174. bot.sendMessage(CHAT_ID, "Did you see the action message?");
  175. }
  176. */
  177. //delay(500);
  178. }
  179. //***********************************************************************************************************************
  180. //***********************************************************************************************************************
  181. //*************************************************[ Setup Sensors Function ]********************************************
  182. void SetupSensors() {
  183. pinMode(pumpRelayPin, OUTPUT);
  184. pinMode(TdsSensorPin, INPUT);
  185. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  186. pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  187. sensors.begin();
  188. }
  189. //***********************************************************************************************************************
  190. //***********************************************************************************************************************
  191. //*************************************************[ Pump Functions ]********************************************
  192. void pumpON() {
  193. digitalWrite(pumpRelayPin, 1);
  194. delay(500);
  195. }
  196. void pumpOFF() {
  197. digitalWrite(pumpRelayPin, 0);
  198. delay(500);
  199. }
  200. //***********************************************************************************************************************
  201. //***********************************************************************************************************************
  202. //**********************************************[ Setup WiFi and Telegram Function]**************************************
  203. void SetupWiFiandTelegramBot() {
  204. // Connect to Wi-Fi
  205. WiFi.mode(WIFI_STA);
  206. WiFi.begin(ssid, password);
  207. Sclient.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  208. while (WiFi.status() != WL_CONNECTED) {
  209. delay(1000);
  210. Serial.println("Wifi Connected..");
  211. }
  212. // Print ESP32 Local IP Address
  213. Serial.println(WiFi.localIP());
  214. Serial.print("Retrieving time: ");
  215. configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  216. time_t now = time(nullptr);
  217. while (now < 24 * 3600) {
  218. Serial.print(".");
  219. delay(100);
  220. now = time(nullptr);
  221. }
  222. Serial.println(now);
  223. // Set Adafruit IO's root CA
  224. client.setCACert(adafruitio_root_ca);
  225. }
  226. //***********************************************************************************************************************
  227. //***********************************************************************************************************************
  228. //*********************************************[ Telegram Messages Function ]********************************************
  229. void handleNewMessages(int numNewMessages) {
  230. Serial.println("handleNewMessages");
  231. Serial.println(String(numNewMessages));
  232. for (int i = 0; i < numNewMessages; i++) {
  233. String chat_id = bot.messages[i].chat_id;
  234. String text = bot.messages[i].text;
  235. String from_name = bot.messages[i].from_name;
  236. if (from_name == "")
  237. from_name = "Guest";
  238. // Find position of ',' and '='
  239. int posA = text.indexOf("a=");
  240. int posB = text.indexOf("b=");
  241. if (posA != -1 && posB != -1) {
  242. // Extract values of a and b
  243. String value1String = text.substring(posA + 2, posB - 1);
  244. String value2String = text.substring(posB + 2);
  245. // Convert string values to integers
  246. value1 = value1String.toFloat();
  247. value2 = value2String.toFloat();
  248. }
  249. // Print extracted values for debugging
  250. Serial.print("Value of a: ");
  251. Serial.println(value1);
  252. Serial.print("Value of b: ");
  253. Serial.println(value2);
  254. if (text == "/send_test_action") {
  255. bot.sendChatAction(chat_id, "typing");
  256. delay(4000);
  257. bot.sendMessage(chat_id, "Did you see the action message?");
  258. }
  259. if (text == "/start") {
  260. String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
  261. welcome += "This is Chat Action Bot example.\n\n";
  262. welcome += "/send_test_action : to send test chat action message\n";
  263. bot.sendMessage(chat_id, welcome);
  264. }
  265. }
  266. }
  267. //***********************************************************************************************************************
  268. //***********************************************************************************************************************
  269. //******************************************[ Handel Telegram Messages Function ]****************************************
  270. void ReceiveMessageFromTelegram() {
  271. if (millis() - bot_lasttime > 1000) {
  272. int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  273. while (numNewMessages) {
  274. Serial.println("got response");
  275. handleNewMessages(numNewMessages);
  276. numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  277. }
  278. bot_lasttime = millis();
  279. }
  280. }
  281. //***********************************************************************************************************************
  282. //***********************************************************************************************************************
  283. //*************************************[ Read Ultrasonic Sensor Function ]***********************************************
  284. void ReadDistanceUsingUltrasonicSensor() {
  285. // Clears the trigPin
  286. digitalWrite(trigPin, LOW);
  287. delayMicroseconds(2);
  288. // Sets the trigPin on HIGH state for 10 micro seconds
  289. digitalWrite(trigPin, HIGH);
  290. delayMicroseconds(10);
  291. digitalWrite(trigPin, LOW);
  292. // Reads the echoPin, returns the sound wave travel time in microseconds
  293. duration = pulseIn(echoPin, HIGH);
  294. // Calculate the distance
  295. distanceCm = duration * SOUND_SPEED / 2;
  296. // Convert to Volume
  297. // ↓ Calibration Factor
  298. //volume_cm3 = int((hight - (-2 + distanceCm)) * 3.14 * radius * radius);
  299.  
  300. waterLevel = map((distanceCm - 2), 0, hight, 100, 0);
  301. if (waterLevel < 0) {
  302. waterLevel = 0;
  303. }
  304. if (waterLevel > 100) {
  305. waterLevel = 100;
  306. }
  307. // Prints the distance in the Serial Monitor
  308. Serial.print("Distance (cm): ");
  309. Serial.println(distanceCm);
  310. //Serial.print("Volume (CM^3): ");
  311. //Serial.println(volume_cm3);
  312. Serial.print("Water Level (%): ");
  313. Serial.println(waterLevel);
  314. }
  315. //***********************************************************************************************************************
  316. //***********************************************************************************************************************
  317. //*******************************************[ Read Temprature Sensor Function ]*****************************************
  318. void ReadTempratureSensor() {
  319. sensors.requestTemperatures();
  320. temperatureC = sensors.getTempCByIndex(0);
  321. Serial.print("Temprature (ΒΊC): ");
  322. Serial.println(temperatureC);
  323. }
  324. //***********************************************************************************************************************
  325. //***********************************************************************************************************************
  326. //******************************************[ Publish Data To Dashboard Function ]***************************************
  327. void Publish_Sensor_Data() {
  328. if (millis() - mqtt_lasttime > timeBetweenDataPointsToBeSent) {
  329. // Ensure the connection to the MQTT server is alive (this will make the first
  330. // connection and automatically reconnect when disconnected). See the MQTT_connect
  331. // function definition further below.
  332. MQTT_connect();
  333. // Publish distance to MQTT Server
  334. if (!distance_mqtt_Publish.publish(distanceCm)) {
  335. Serial.println(F("distance_mqtt_Publish: Failed"));
  336. } else {
  337. Serial.println(F("distance_mqtt_Publish: OK!"));
  338. }
  339. // Publish volume to MQTT Server
  340. if (!volume_mqtt_Publish.publish(volume_cm3)) {
  341. Serial.println(F("volume_mqtt_Publish: Failed"));
  342. } else {
  343. Serial.println(F("volume_mqtt_Publish: OK!"));
  344. }
  345. // Publish waterLevel to MQTT Server
  346. if (!waterLevel_mqtt_Publish.publish(waterLevel)) {
  347. Serial.println(F("waterLevel_mqtt_Publish: Failed"));
  348. } else {
  349. Serial.println(F("waterLevel_mqtt_Publish: OK!"));
  350. }
  351. // Publish Temprature to MQTT Server
  352. if (!temprature_mqtt_Publish.publish(temperatureC)) {
  353. Serial.println(F("temprature_mqtt_Publish: Failed"));
  354. } else {
  355. Serial.println(F("temprature_mqtt_Publish: OK!"));
  356. }
  357. // Publish TDS to MQTT Server
  358. if (!tds_mqtt_Publish.publish(tdsValue)) {
  359. Serial.println(F("tds_mqtt_Publish: Failed"));
  360. } else {
  361. Serial.println(F("tds_mqtt_Publish: OK!"));
  362. }
  363. mqtt_lasttime = millis();
  364. }
  365. }
  366. //***********************************************************************************************************************
  367. //***********************************************************************************************************************
  368. //******************************************[ Re/Connect to MQTT Server Function ]***************************-***********
  369. void MQTT_connect() {
  370. int8_t ret;
  371. // Stop if already connected.
  372. if (mqtt.connected()) {
  373. return;
  374. }
  375. Serial.print("Connecting to MQTT... ");
  376. uint8_t retries = 3;
  377. while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
  378. Serial.println(mqtt.connectErrorString(ret));
  379. Serial.println("Retrying MQTT connection in 5 seconds...");
  380. mqtt.disconnect();
  381. delay(5000); // wait 5 seconds
  382. retries--;
  383. if (retries == 0) {
  384. // basically die and wait for WDT to reset me
  385. while (1);
  386. }
  387. }
  388. Serial.println("MQTT Connected!");
  389. }
  390. //***********************************************************************************************************************
  391. //***********************************************************************************************************************
  392.  
  393. // Function to determine the range of the water level
  394. int getRange(int level) {
  395. if (level >= 0 && level < 10) return 0; // 0% range
  396. if (level >= 10 && level < 40) return 25; // 25% range
  397. if (level >= 40 && level <= 60) return 50; // 50% range
  398. if (level > 60 && level <= 90) return 75; // 75% range
  399. if (level > 90) return 100; // 100% range
  400. return -1; // Invalid range
  401. }
  402.  
  403. // Function to send a water level message
  404. void sendWaterLevelMessage(int range) {
  405. switch (range) {
  406. case 0:
  407. bot.sendMessage(CHAT_ID, "Water Level is at 0% - Critical low level!");
  408. break;
  409. case 25:
  410. bot.sendMessage(CHAT_ID, "Water Level is at 25% - Low level warning.");
  411. break;
  412. case 50:
  413. bot.sendMessage(CHAT_ID, "Water Level is at 50% - Half full.");
  414. break;
  415. case 75:
  416. bot.sendMessage(CHAT_ID, "Water Level is at 75% - Almost full.");
  417. break;
  418. case 100:
  419. bot.sendMessage(CHAT_ID, "Water Level is at 100% - Tank full!");
  420. break;
  421. default:
  422. // Do nothing for invalid ranges
  423. break;
  424. }
  425. }
Advertisement
Add Comment
Please, Sign In to add comment