Autóban lévő ESP

 avatar
user_4999651
plain_text
7 months ago
12 kB
1
Indexable
Never
////////////////////////////////////////////////////////////////////////////////////////////////////
// Modify these values for your environment
const char *wifiSSID = "";                  // Your WiFi network name
const char *wifiPassword = "";          // Your WiFi network password
const char *otaPassword = "";                       // OTA update password
const char *mqttServer = "";            // Your MQTT server IP address
const char *mqttUser = "";                          // mqtt username, set to "" for no user
const char *mqttPassword = "";                      // mqtt password, set to "" for no password
const String mqttNode = "ACCORD";              // Your unique hostname for this device
const String mqttDiscoveryPrefix = "homeassistant"; // Home Assistant MQTT Discovery, see https://home-assistant.io/docs/mqtt/discovery/
String wifiAP="";
////////////////////////////////////////////////////////////////////////////////////////////////////

// Home Assistant MQTT Discovery, see https://home-assistant.io/docs/mqtt/discovery/
// We'll create one binary_sensor device to track MQTT connectivity
const String mqttDiscoBinaryStateTopic = mqttDiscoveryPrefix + "/binary_sensor/" + mqttNode + "/state";
const String mqttDiscoBinaryConfigTopic = mqttDiscoveryPrefix + "/binary_sensor/" + mqttNode + "/config";
// And a sensor for WiFi signal strength
const String mqttDiscoSignalStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-signal/state";
const String mqttDiscoSignalConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-signal/config";
// And a sensor for device uptime
const String mqttDiscoUptimeStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-uptime/state";
const String mqttDiscoUptimeConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-uptime/config";

// And a sensor for device BSSID
const String mqttDiscoBSSIDStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-bssid/state";
const String mqttDiscoBSSIDConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-bssid/config";

// The strings below will spill over the PubSubClient_MAX_PACKET_SIZE 128
// You'll need to manually set MQTT_MAX_PACKET_SIZE in PubSubClient.h to 512
const String mqttDiscoBinaryConfigPayload = "{\"name\": \"" + mqttNode + "\", \"device_class\": \"connectivity\", \"state_topic\": \"" + mqttDiscoBinaryStateTopic + "\"}";
const String mqttDiscoSignalConfigPayload = "{\"name\": \"" + mqttNode + "-signal\", \"state_topic\": \"" + mqttDiscoSignalStateTopic + "\", \"unit_of_measurement\": \"dBm\", \"value_template\": \"{{ value }}\"}";
const String mqttDiscoUptimeConfigPayload = "{\"name\": \"" + mqttNode + "-uptime\", \"state_topic\": \"" + mqttDiscoUptimeStateTopic + "\", \"unit_of_measurement\": \"sec\", \"value_template\": \"{{ value }}\"}";
const String mqttDiscoBSSIDConfigPayload = "{\"name\": \"" + mqttNode + "-bssid\", \"state_topic\": \"" + mqttDiscoBSSIDStateTopic + "\"}";

// Set the signal strength and uptime reporting interval in milliseconds
const unsigned long reportInterval = 200;
unsigned long reportTimer = millis();

// Set LED "twinkle" time for maximum daylight visibility
const unsigned long twinkleInterval = 50;
unsigned long twinkleTimer = millis();

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

////////////////////////////////////////////////////////////////////////////////////////////////////
// System setup
void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
//  Serial.begin(115200);

//  Serial.println("\nHardware initialized, starting program load");

  // Start up networking
  setupWifi();

  // Create server and assign callbacks for MQTT
  mqttClient.setServer(mqttServer, 1883);
  mqttClient.setCallback(mqtt_callback);
  mqttConnect();

  // Start up OTA
  if (otaPassword[0])
  {
    setupOTA();
  }

//  Serial.println("Initialization complete\n");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Main execution loop
void loop()
{
  // check WiFi connection
  wifirestart();
  if (WiFi.status() != WL_CONNECTED)
  {
    setupWifi();
  }

  // check MQTT connection
  if (!mqttClient.connected())
  {
    mqttConnect();
  }

  // MQTT client loop
  if (mqttClient.connected())
  {
    mqttClient.loop();
  }

  // LED twinkle
  if (mqttClient.connected() && ((millis() - twinkleTimer) >= twinkleInterval))
  {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    twinkleTimer = millis();
  }
  
  wifiAP=WiFi.BSSIDstr();
 // Wifi AP name
      //if WiFi.BSSIDstr() = "34:60:F9:63:BF:36"
 //   if (WiFi.BSSIDstr() = "14:EB:B6:A6:BE:C6")
 //     wifiAP="Iroda";
 //   else if (WiFi.BSSIDstr() = "22:EB:B6:A6:BE:C6")
 //     wifiAP="Iroda";  
 //   else if (WiFi.BSSIDstr() = "34:60:F9:63:BF:36")
 //     wifiAP="Első Udvar";
 //   else if (WiFi.BSSIDstr() = "28:87:BA:14:06:08")
 //     wifiAP="Kisgarázs";
 //   else if (WiFi.BSSIDstr() = "1a:87:BA:14:06:08")
 //     wifiAP="Kisgarázs";
 //   else if (WiFi.BSSIDstr() = "1a:87:ba:14:07:41")
 //     wifiAP="Műhely-Garázs";
 //   else if (WiFi.BSSIDstr() = "28:87:ba:14:07:41")
 //     wifiAP="Műhely-Garázs";
 //   else if (WiFi.BSSIDstr() = "1a:87:ba:14:07:47")
 //     wifiAP="Terasz";
 //   else if (WiFi.BSSIDstr() = "28:87:ba:14:07:47")
 //     wifiAP="Terasz";      
 //   WiFi.BSSIDstr(bssid);
  // check MQTT connection


  // Report signal strength and uptime
  if (mqttClient.connected() && ((millis() - reportTimer) >= reportInterval))
  {
    wifiAP=WiFi.BSSIDstr();
    String signalStrength = String(WiFi.RSSI());
    String uptimeTimer = String(millis() / 1000);
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    mqttClient.publish(mqttDiscoUptimeStateTopic.c_str(), uptimeTimer.c_str());
    mqttClient.publish(mqttDiscoBSSIDStateTopic.c_str(), wifiAP.c_str());
    reportTimer = millis();
    if (WiFi.status() != WL_CONNECTED)
    {
      setupWifi();
    } 
  }

  // OTA loop
  if (otaPassword[0])
  {
    ArduinoOTA.handle();
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions

////////////////////////////////////////////////////////////////////////////////////////////////////
// Handle incoming commands from MQTT
void mqtt_callback(char *topic, byte *payload, unsigned int payloadLength)
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Connect to WiFi
void setupWifi()
{
//  Serial.print("Connecting to WiFi network: " + String(wifiSSID));
  WiFi.hostname(mqttNode.c_str());
  WiFi.mode(WIFI_STA);
  WiFi.setSleepMode(WIFI_NONE_SLEEP);
  WiFi.begin(wifiSSID, wifiPassword);

  while (WiFi.status() != WL_CONNECTED)
  {
    wifiAP=WiFi.BSSIDstr();
    delay(1);
  }
//  Serial.println("\nWiFi connected successfully and assigned IP: " + WiFi.localIP().toString());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// WiFi connection restart
void wifirestart()
{
    if (WiFi.RSSI() <= -82)
    {
    String signalStrength = String(WiFi.RSSI());
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    WiFi.disconnect(true);
    WiFi.persistent(false);
    //Serial.println(signalStrength);
    //Serial.println("\n");
    //Serial.println("RESTARTING Wifi\n\n");
    
    setupWifi();
    //ESP.restart();
    }
    else
    {
    wifiAP=WiFi.BSSIDstr();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// MQTT connection and subscriptions
void mqttConnect()
{
  digitalWrite(LED_BUILTIN, HIGH);
//  Serial.println("Attempting MQTT connection to broker: " + String(mqttServer));
  // Attempt to connect to broker, setting last will and testament
  if (mqttClient.connect(mqttNode.c_str(), mqttUser, mqttPassword, mqttDiscoBinaryStateTopic.c_str(), 1, 1, "OFF"))
  {
    // when connected, record signal strength and reset reporting timer
    String signalStrength = String(WiFi.RSSI());
    reportTimer = millis();
    String uptimeTimer = String(millis() / 1000);
    // publish MQTT discovery topics and device state
    wifiAP=WiFi.BSSIDstr();
//    Serial.println("MQTT discovery connectivity config: [" + mqttDiscoBinaryConfigTopic + "] : [" + mqttDiscoBinaryConfigPayload + "]");
//    Serial.println("MQTT discovery connectivity state: [" + mqttDiscoBinaryStateTopic + "] : [ON]");
//    Serial.println("MQTT discovery signal config: [" + mqttDiscoSignalConfigTopic + "] : [" + mqttDiscoSignalConfigPayload + "]");
//    Serial.println("MQTT discovery signal state: [" + mqttDiscoSignalStateTopic + "] : " + WiFi.RSSI());
//    Serial.println("MQTT discovery uptime config: [" + mqttDiscoUptimeConfigTopic + "] : [" + mqttDiscoUptimeConfigPayload + "]");
//    Serial.println("MQTT discovery uptime state: [" + mqttDiscoUptimeStateTopic + "] : " + uptimeTimer);
    mqttClient.publish(mqttDiscoUptimeConfigTopic.c_str(), mqttDiscoUptimeConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoUptimeStateTopic.c_str(), uptimeTimer.c_str());
    mqttClient.publish(mqttDiscoBinaryConfigTopic.c_str(), mqttDiscoBinaryConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoBinaryStateTopic.c_str(), "ON");
    mqttClient.publish(mqttDiscoSignalConfigTopic.c_str(), mqttDiscoSignalConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    mqttClient.publish(mqttDiscoBSSIDConfigTopic.c_str(), mqttDiscoBSSIDConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoBSSIDStateTopic.c_str(), wifiAP.c_str());    
//    Serial.println("MQTT connected");
    digitalWrite(LED_BUILTIN, LOW);
    
    if (WiFi.status() != WL_CONNECTED)
    {
      setupWifi();
    }
  }
  else
  {
    if (WiFi.status() != WL_CONNECTED)
    {
      setupWifi();
    }
//    Serial.println("MQTT connection failed, rc=" + String(mqttClient.state()));
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// (mostly) boilerplate OTA setup from library examples
void setupOTA()
{
  // Start up OTA
  // ArduinoOTA.setPort(8266); // Port defaults to 8266
  ArduinoOTA.setHostname(mqttNode.c_str());
  ArduinoOTA.setPassword(otaPassword);

  ArduinoOTA.onStart([]() {
//    Serial.println("ESP OTA:  update start");
  });
  ArduinoOTA.onEnd([]() {
//    Serial.println("ESP OTA:  update complete");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    //Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
//  ArduinoOTA.onError([](ota_error_t error) {
//    Serial.println("ESP OTA:  ERROR code " + String(error));
//    if (error == OTA_AUTH_ERROR)
//      Serial.println("ESP OTA:  ERROR - Auth Failed");
//    else if (error == OTA_BEGIN_ERROR)
//      Serial.println("ESP OTA:  ERROR - Begin Failed");
//    else if (error == OTA_CONNECT_ERROR)
//      Serial.println("ESP OTA:  ERROR - Connect Failed");
//    else if (error == OTA_RECEIVE_ERROR)
//      Serial.println("ESP OTA:  ERROR - Receive Failed");
//    else if (error == OTA_END_ERROR)
//      Serial.println("ESP OTA:  ERROR - End Failed");
//  });
  ArduinoOTA.begin();
//  Serial.println("ESP OTA:  Over the Air firmware update ready");
}
Leave a Comment