blackscreener

water softener mqtt

Apr 8th, 2020
607
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 8.86 KB | None | 0 0
  1. #define MQTT_KEEPALIVE 10
  2. #include <ESP8266WiFi.h>
  3. #include <PubSubClient.h>
  4. #include <ArduinoOTA.h>
  5. #include <ESP8266mDNS.h>
  6. #include <WiFiUdp.h>
  7. #include <Bounce2.h>
  8.  
  9. #ifdef __AVR__
  10. #include <avr/power.h>
  11. #endif
  12.  
  13. #define PIN 14   //D5 - PIN fotorezystora
  14. //****************************************************     MQTT     ****************************************
  15. // Update these with values suitable for your network.
  16.  
  17. const char* ssid = "xxxxxxxxxx";
  18. const char* password = "xxxxxxxxxx";
  19. const char* mqtt_server = "xxxxxxxxxx";
  20. const char* mqttUser = "xxxxxxxxxx";
  21. const char* mqttPassword = "xxxxxxxxxx";
  22. const char* willTopic = "esp_zmiekczacz/availability";
  23. int willQoS = 1;
  24. bool willRetain = true;
  25. const char* willMessage = "offline";
  26. //***************************************************************************************************************
  27.  
  28. WiFiClient espClient;
  29. PubSubClient client(espClient);
  30. char msg[50];
  31. long lastReconnectAttempt = 0;
  32.  
  33. int quality;
  34. bool brak_soli = false;
  35. int PIN_2;
  36. long state = -1;
  37. const int RSSI_MAX = -50; // define maximum strength of signal in dBm
  38. const int RSSI_MIN = -100; // define minimum strength of signal in dBm
  39. unsigned long lastTimeChecked = 0;
  40. uint32_t currentMillis;
  41. unsigned long lastTimeChecked2 = 0;
  42. uint32_t currentMillis2;
  43.  
  44. // Instantiate a Bounce object
  45. Bounce debouncer_pin = Bounce();
  46.  
  47. void setup_wifi() {
  48.   delay(10);
  49.   // We start by connecting to a WiFi network
  50.   Serial.println();
  51.   Serial.print("Connecting to ");
  52.   Serial.println(ssid);
  53.   WiFi.begin(ssid, password);
  54.   WiFi.mode(WIFI_STA);
  55.   while (WiFi.status() != WL_CONNECTED) {
  56.     delay(500);
  57.     Serial.print(".");
  58.   }
  59.   randomSeed(micros());
  60.   Serial.println("");
  61.   Serial.println("WiFi connected");
  62.   Serial.println("IP address: ");
  63.   Serial.println(WiFi.localIP());
  64.   Serial.print(WiFi.RSSI());//Signal strength in dBm
  65.   Serial.print("dBm (");
  66.   Serial.print(dBmtoPercentage(WiFi.RSSI()));//Signal strength in %
  67.   //Serial.print(quality);//Signal strength in %
  68.   Serial.print("% )");
  69.  
  70.   //****************** ArduinoOTA ***************************
  71.   // Port defaults to 8266
  72.   // ArduinoOTA.setPort(8266);
  73.  
  74.   // Hostname defaults to esp8266-[ChipID]
  75.   ArduinoOTA.setHostname("ESP zmiekczacz");
  76.  
  77.   // No authentication by default
  78.   // ArduinoOTA.setPassword("admin");
  79.  
  80.   // Password can be set with it's md5 value as well
  81.   // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  82.   // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
  83.  
  84.   ArduinoOTA.onStart([]() {
  85.     String type;
  86.     if (ArduinoOTA.getCommand() == U_FLASH) {
  87.       type = "sketch";
  88.     } else { // U_FS
  89.       type = "filesystem";
  90.     }
  91.  
  92.     // NOTE: if updating FS this would be the place to unmount FS using FS.end()
  93.     Serial.println("Start updating " + type);
  94.   });
  95.   ArduinoOTA.onEnd([]() {
  96.     Serial.println("\nEnd");
  97.   });
  98.   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  99.     Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  100.   });
  101.   ArduinoOTA.onError([](ota_error_t error) {
  102.     Serial.printf("Error[%u]: ", error);
  103.     if (error == OTA_AUTH_ERROR) {
  104.       Serial.println("Auth Failed");
  105.     } else if (error == OTA_BEGIN_ERROR) {
  106.       Serial.println("Begin Failed");
  107.     } else if (error == OTA_CONNECT_ERROR) {
  108.       Serial.println("Connect Failed");
  109.     } else if (error == OTA_RECEIVE_ERROR) {
  110.       Serial.println("Receive Failed");
  111.     } else if (error == OTA_END_ERROR) {
  112.       Serial.println("End Failed");
  113.     }
  114.   });
  115.   ArduinoOTA.begin();
  116. //  Serial.println("Ready");
  117. //  Serial.print("IP address: ");
  118. //  Serial.println(WiFi.localIP());
  119.   //**********************************************************
  120.  
  121.  
  122. }
  123.  
  124. void callback(char* topic, byte* payload, unsigned int length) {
  125.   Serial.print("Message arrived [");
  126.   Serial.print(topic);
  127.   Serial.print("] ");
  128.   int i;
  129.   for (i = 0; i < length; i++) {
  130.     Serial.print((char)payload[i]);
  131.     msg[i] = payload[i];
  132.   }
  133.   msg[length] = '\0';
  134.  
  135.   Serial.println();
  136.   Serial.println(msg);
  137.   // Switch on the LED if an 1 was received as first character
  138.  
  139.   if (strcmp(topic, "esp_zmiekczacz/inTopic") == 0) {
  140.  
  141.     if (strcmp((char *)msg, "status") == 0) { /////////////////////////Restart HA
  142.       client.publish("esp_zmiekczacz/status", String(quality).c_str());
  143.       //client.publish("esp_zmiekczacz/status2", String(brak_soli).c_str());
  144.  
  145.       if (brak_soli) {
  146.         client.publish("esp_zmiekczacz/status2", "brak_soli_on");
  147.       }
  148.       else if (!brak_soli) {
  149.         client.publish("esp_zmiekczacz/status2", "brak_soli_off");
  150.       }
  151.       //
  152.       //      if (BREATHELEDS > 0) {
  153.       //        client.publish("esp_zmiekczacz/status", "BREATHELEDS_ON");
  154.       //      }
  155.       //      else if (BREATHELEDS == 0) {
  156.       //        client.publish("esp_zmiekczacz/status", "BREATHELEDS_OFF");
  157.       //      }
  158.     }
  159.  
  160.   }
  161. }
  162.  
  163. boolean reconnect() {
  164.  
  165.   Serial.println("Attempting MQTT connection...");
  166.   // Create a random client ID
  167.   String clientId = "ESP8266Client-zmiekczacz";
  168.   //clientId += String(random(0xffff), HEX);
  169.   // Attempt to connect
  170.   if (client.connect(clientId.c_str(), mqttUser, mqttPassword, willTopic, willQoS, willRetain, willMessage)) {
  171.     Serial.println("connected");
  172.     // Once connected, publish an announcement...
  173.     client.publish("esp_zmiekczacz/availability", "online", true);
  174.     // ... and resubscribe
  175.     client.subscribe("esp_zmiekczacz/inTopic");
  176.     client.publish("esp_zmiekczacz/status", String(quality).c_str()); //sygnał wifi
  177.     //client.publish("esp_schody/status2", String(brak_soli).c_str()); //brak_soli ON ? OFF
  178.     //    client.publish("esp_schody/status4", String(jasnosc_breathe).c_str());
  179.  
  180.     if (brak_soli) {
  181.       client.publish("esp_zmiekczacz/status2", "brak_soli_on");
  182.     }
  183.     else if (!brak_soli) {
  184.       client.publish("esp_zmiekczacz/status2", "brak_soli_off");
  185.     }
  186.  
  187.     //    if (BREATHELEDS > 0) {
  188.     //      client.publish("esp_schody/status", "BREATHELEDS_ON");
  189.     //    }
  190.     //    else if (BREATHELEDS == 0) {
  191.     //      client.publish("esp_schody/status", "BREATHELEDS_OFF");
  192.     //    }
  193.   }
  194.   return client.connected();
  195.  
  196. }
  197.  
  198. void setup() {
  199.  
  200.   //****************** MQTT **********************************
  201.   pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  202.   digitalWrite(BUILTIN_LED, HIGH); //LED OFF
  203.   Serial.begin(115200);
  204.   setup_wifi();
  205.   client.setServer(mqtt_server, 1883);
  206.   client.setCallback(callback);
  207.   lastReconnectAttempt = 0;
  208.   //**********************************************************
  209.   pinMode (PIN, INPUT_PULLUP);  //Dioda fotorezystor
  210.  
  211.   debouncer_pin.attach(PIN);
  212.   debouncer_pin.interval(5); // interval in ms
  213.  
  214. }
  215.  
  216. void loop() {
  217.   ArduinoOTA.handle();
  218.   diodaState();
  219.   currentMillis2 = millis();
  220.   //dBmtoPercentage(WiFi.RSSI());
  221.  
  222.   //    Serial.println("quality");
  223.   //  Serial.println(quality);
  224.   //delay (200);
  225.   //****************** MQTT **********************************
  226.   if (!client.connected()) {
  227.     long now = millis();
  228.     if (now - lastReconnectAttempt > 5000) {
  229.       lastReconnectAttempt = now;
  230.       // Attempt to reconnect
  231.       if (reconnect()) {
  232.         lastReconnectAttempt = 0;
  233.       }
  234.     }
  235.   } else {
  236.     // Client connected
  237.  
  238.     client.loop();
  239.   }
  240.   //**********************************************************
  241.  
  242.   // Update the Bounce instance:
  243.   debouncer_pin.update();
  244.  
  245.   // Get the updated value :
  246.   PIN_2 = debouncer_pin.read();
  247.  
  248.  
  249.   ////////////////// TELE ////////////////////////////////////
  250.   currentMillis = millis();
  251.   if ((currentMillis - lastTimeChecked) > (60000 * 5)) {    ///1 min * x min // Okres telemetrii
  252.     dBmtoPercentage(WiFi.RSSI());
  253.     lastTimeChecked = currentMillis;
  254.     client.publish("esp_zmiekczacz/status", String(quality).c_str()); //sygnał wifi
  255.     if (brak_soli) {  //status diody "brak soli"
  256.       client.publish("esp_zmiekczacz/status2", "brak_soli_on");
  257.     }
  258.     else if (!brak_soli) {
  259.       client.publish("esp_zmiekczacz/status2", "brak_soli_off");
  260.     }
  261.   }
  262.   /////////////////////////////////////////////////////////////
  263.  
  264.   if (PIN_2 == LOW) {
  265.     brak_soli = true;
  266.     lastTimeChecked2 = currentMillis2;
  267.   }
  268.   else if (PIN_2 == HIGH) {
  269.     if ((currentMillis2 - lastTimeChecked2) > 2000) {
  270.       brak_soli = false;
  271.     }
  272.   }
  273. }
  274.  
  275. void diodaState() {
  276.   long newState = brak_soli;
  277.   if (newState != state) {
  278.     if (newState) {
  279.       Serial.println("brak_soli_on");
  280.       client.publish("esp_zmiekczacz/status2", "brak_soli_on");
  281.     } else {
  282.       Serial.println("brak_soli_off");
  283.       client.publish("esp_zmiekczacz/status2", "brak_soli_off");
  284.     }
  285.     state = newState;
  286.   }
  287. }
  288.  
  289. int dBmtoPercentage(int dBm)
  290. {
  291.   if (dBm <= RSSI_MIN)
  292.   {
  293.     quality = 0;
  294.   }
  295.   else if (dBm >= RSSI_MAX)
  296.   {
  297.     quality = 100;
  298.   }
  299.   else
  300.   {
  301.     quality = 2 * (dBm + 100);
  302.   }
  303.   return quality;
  304. }
Advertisement
Add Comment
Please, Sign In to add comment