Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define MQTT_KEEPALIVE 10
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #include <ArduinoOTA.h>
- #include <ESP8266mDNS.h>
- #include <WiFiUdp.h>
- #include <Bounce2.h>
- #ifdef __AVR__
- #include <avr/power.h>
- #endif
- #define PIN 14 //D5 - PIN fotorezystora
- //**************************************************** MQTT ****************************************
- // Update these with values suitable for your network.
- const char* ssid = "xxxxxxxxxx";
- const char* password = "xxxxxxxxxx";
- const char* mqtt_server = "xxxxxxxxxx";
- const char* mqttUser = "xxxxxxxxxx";
- const char* mqttPassword = "xxxxxxxxxx";
- const char* willTopic = "esp_zmiekczacz/availability";
- int willQoS = 1;
- bool willRetain = true;
- const char* willMessage = "offline";
- //***************************************************************************************************************
- WiFiClient espClient;
- PubSubClient client(espClient);
- char msg[50];
- long lastReconnectAttempt = 0;
- int quality;
- bool brak_soli = false;
- int PIN_2;
- long state = -1;
- const int RSSI_MAX = -50; // define maximum strength of signal in dBm
- const int RSSI_MIN = -100; // define minimum strength of signal in dBm
- unsigned long lastTimeChecked = 0;
- uint32_t currentMillis;
- unsigned long lastTimeChecked2 = 0;
- uint32_t currentMillis2;
- // Instantiate a Bounce object
- Bounce debouncer_pin = Bounce();
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- WiFi.mode(WIFI_STA);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- randomSeed(micros());
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- Serial.print(WiFi.RSSI());//Signal strength in dBm
- Serial.print("dBm (");
- Serial.print(dBmtoPercentage(WiFi.RSSI()));//Signal strength in %
- //Serial.print(quality);//Signal strength in %
- Serial.print("% )");
- //****************** ArduinoOTA ***************************
- // Port defaults to 8266
- // ArduinoOTA.setPort(8266);
- // Hostname defaults to esp8266-[ChipID]
- ArduinoOTA.setHostname("ESP zmiekczacz");
- // No authentication by default
- // ArduinoOTA.setPassword("admin");
- // Password can be set with it's md5 value as well
- // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
- // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
- ArduinoOTA.onStart([]() {
- String type;
- if (ArduinoOTA.getCommand() == U_FLASH) {
- type = "sketch";
- } else { // U_FS
- type = "filesystem";
- }
- // NOTE: if updating FS this would be the place to unmount FS using FS.end()
- Serial.println("Start updating " + type);
- });
- ArduinoOTA.onEnd([]() {
- Serial.println("\nEnd");
- });
- ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
- Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
- });
- ArduinoOTA.onError([](ota_error_t error) {
- Serial.printf("Error[%u]: ", error);
- if (error == OTA_AUTH_ERROR) {
- Serial.println("Auth Failed");
- } else if (error == OTA_BEGIN_ERROR) {
- Serial.println("Begin Failed");
- } else if (error == OTA_CONNECT_ERROR) {
- Serial.println("Connect Failed");
- } else if (error == OTA_RECEIVE_ERROR) {
- Serial.println("Receive Failed");
- } else if (error == OTA_END_ERROR) {
- Serial.println("End Failed");
- }
- });
- ArduinoOTA.begin();
- // Serial.println("Ready");
- // Serial.print("IP address: ");
- // Serial.println(WiFi.localIP());
- //**********************************************************
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- int i;
- for (i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- msg[i] = payload[i];
- }
- msg[length] = '\0';
- Serial.println();
- Serial.println(msg);
- // Switch on the LED if an 1 was received as first character
- if (strcmp(topic, "esp_zmiekczacz/inTopic") == 0) {
- if (strcmp((char *)msg, "status") == 0) { /////////////////////////Restart HA
- client.publish("esp_zmiekczacz/status", String(quality).c_str());
- //client.publish("esp_zmiekczacz/status2", String(brak_soli).c_str());
- if (brak_soli) {
- client.publish("esp_zmiekczacz/status2", "brak_soli_on");
- }
- else if (!brak_soli) {
- client.publish("esp_zmiekczacz/status2", "brak_soli_off");
- }
- //
- // if (BREATHELEDS > 0) {
- // client.publish("esp_zmiekczacz/status", "BREATHELEDS_ON");
- // }
- // else if (BREATHELEDS == 0) {
- // client.publish("esp_zmiekczacz/status", "BREATHELEDS_OFF");
- // }
- }
- }
- }
- boolean reconnect() {
- Serial.println("Attempting MQTT connection...");
- // Create a random client ID
- String clientId = "ESP8266Client-zmiekczacz";
- //clientId += String(random(0xffff), HEX);
- // Attempt to connect
- if (client.connect(clientId.c_str(), mqttUser, mqttPassword, willTopic, willQoS, willRetain, willMessage)) {
- Serial.println("connected");
- // Once connected, publish an announcement...
- client.publish("esp_zmiekczacz/availability", "online", true);
- // ... and resubscribe
- client.subscribe("esp_zmiekczacz/inTopic");
- client.publish("esp_zmiekczacz/status", String(quality).c_str()); //sygnał wifi
- //client.publish("esp_schody/status2", String(brak_soli).c_str()); //brak_soli ON ? OFF
- // client.publish("esp_schody/status4", String(jasnosc_breathe).c_str());
- if (brak_soli) {
- client.publish("esp_zmiekczacz/status2", "brak_soli_on");
- }
- else if (!brak_soli) {
- client.publish("esp_zmiekczacz/status2", "brak_soli_off");
- }
- // if (BREATHELEDS > 0) {
- // client.publish("esp_schody/status", "BREATHELEDS_ON");
- // }
- // else if (BREATHELEDS == 0) {
- // client.publish("esp_schody/status", "BREATHELEDS_OFF");
- // }
- }
- return client.connected();
- }
- void setup() {
- //****************** MQTT **********************************
- pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
- digitalWrite(BUILTIN_LED, HIGH); //LED OFF
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- lastReconnectAttempt = 0;
- //**********************************************************
- pinMode (PIN, INPUT_PULLUP); //Dioda fotorezystor
- debouncer_pin.attach(PIN);
- debouncer_pin.interval(5); // interval in ms
- }
- void loop() {
- ArduinoOTA.handle();
- diodaState();
- currentMillis2 = millis();
- //dBmtoPercentage(WiFi.RSSI());
- // Serial.println("quality");
- // Serial.println(quality);
- //delay (200);
- //****************** MQTT **********************************
- if (!client.connected()) {
- long now = millis();
- if (now - lastReconnectAttempt > 5000) {
- lastReconnectAttempt = now;
- // Attempt to reconnect
- if (reconnect()) {
- lastReconnectAttempt = 0;
- }
- }
- } else {
- // Client connected
- client.loop();
- }
- //**********************************************************
- // Update the Bounce instance:
- debouncer_pin.update();
- // Get the updated value :
- PIN_2 = debouncer_pin.read();
- ////////////////// TELE ////////////////////////////////////
- currentMillis = millis();
- if ((currentMillis - lastTimeChecked) > (60000 * 5)) { ///1 min * x min // Okres telemetrii
- dBmtoPercentage(WiFi.RSSI());
- lastTimeChecked = currentMillis;
- client.publish("esp_zmiekczacz/status", String(quality).c_str()); //sygnał wifi
- if (brak_soli) { //status diody "brak soli"
- client.publish("esp_zmiekczacz/status2", "brak_soli_on");
- }
- else if (!brak_soli) {
- client.publish("esp_zmiekczacz/status2", "brak_soli_off");
- }
- }
- /////////////////////////////////////////////////////////////
- if (PIN_2 == LOW) {
- brak_soli = true;
- lastTimeChecked2 = currentMillis2;
- }
- else if (PIN_2 == HIGH) {
- if ((currentMillis2 - lastTimeChecked2) > 2000) {
- brak_soli = false;
- }
- }
- }
- void diodaState() {
- long newState = brak_soli;
- if (newState != state) {
- if (newState) {
- Serial.println("brak_soli_on");
- client.publish("esp_zmiekczacz/status2", "brak_soli_on");
- } else {
- Serial.println("brak_soli_off");
- client.publish("esp_zmiekczacz/status2", "brak_soli_off");
- }
- state = newState;
- }
- }
- int dBmtoPercentage(int dBm)
- {
- if (dBm <= RSSI_MIN)
- {
- quality = 0;
- }
- else if (dBm >= RSSI_MAX)
- {
- quality = 100;
- }
- else
- {
- quality = 2 * (dBm + 100);
- }
- return quality;
- }
Advertisement
Add Comment
Please, Sign In to add comment