Избавляемся от указания логина и пароля WiFi в sketch для ESP8266/ESP32

Поскольку жестко прописывать в код sketch-а — некорректно, воспользуемся WiFiManager. Код вынесен в отдельный WiFi.ino файл (для создания нажать сочетение Ctrl-Shft-N).

#include "ESP8266WiFi.h"
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
//#include <PersWiFiManager.h>

//SSID of your network
char ssidWiFi[32]; //SSID of your Wi-Fi router
char passWiFi[32]; //Password of your Wi-Fi router
//String ssidWiFi = "";
//String passWiFi = ""; 
//char* host = "api.thingspeak.com";

//ESP8266WebServer server(80);
//DNSServer dnsServer;
//PersWiFiManager wifiManager(server, dnsServer);

//int numOfRepeat = 0;

void setupWiFi()
{
  //Static parameters for AP
  IPAddress _ip = IPAddress(192,168, 1, 5);
  IPAddress _gw = IPAddress(192, 168, 1, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);
  
  //WiFiManager intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset saved settings
  //wifiManager.resetSettings();
  wifiManager.setAPStaticIPConfig(_ip, _gw, _sn);
  //wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
    
  //fetches ssid and pass from eeprom and tries to connect
  //if it does not connect it starts an access point with the specified name
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("ResourcesMeterAP")) 
  {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.reset();
    delay(5000);
  }
  else
  {
    String pass = WiFi.psk();
    String ssid = WiFi.SSID();

    //passWiFi = pass.c_str();
    strcpy(passWiFi, pass.c_str());
    strcpy(ssidWiFi, ssid.c_str());
    
    Serial.print("Wi-Fi connected to " + String(ssidWiFi) + ". IP address: ");
    Serial.println(WiFi.localIP()); //IP2STR( WiFi.localIP()));
    Serial.print("Strength ...: ");
    Serial.println(WiFi.RSSI());
  }
}

bool connectWiFi()
{
  if (WiFi.status() != WL_CONNECTED)
  {
    //Serial.println("Tryng to connect to Wi-Fi AP with SSID [" + String(ssidWiFi) + "]");
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssidWiFi, passWiFi);
    //WiFi.begin();
  
    int connRes = WiFi.waitForConnectResult();
  
    if (connRes != WL_CONNECTED)
    {
      Serial.println("Wi-Fi connection to " + WiFi.SSID() + " failed. Status " + String(WiFi.status()) + ", " + WiFiconnectionStatus(WiFi.status()) + ", Retrying later...\n");
      WiFi.disconnect();
      return false;
    }
    else {
      Serial.print("Wi-Fi connected to " + WiFi.SSID() + ". IP address: ");
      Serial.println(WiFi.localIP()); //IP2STR( WiFi.localIP()));
      Serial.print("Strength ...: ");
      Serial.println(WiFi.RSSI());
    }
  }
  return true;
}

String WiFiconnectionStatus(int which)
{
  switch (which)
  {
  case WL_CONNECTED:
    return "Connected";
    break;
  case WL_NO_SSID_AVAIL:
    return "Network is not availible";
    break;
  case WL_CONNECT_FAILED:
    return "Wrong password";
    break;
  case WL_IDLE_STATUS:
    return "Idle status";
    break;
  case WL_DISCONNECTED:
    return "Disconnected";
    break;
  default:
    return "Unknown";
    break;
  }
}

Полезные ссылки

Spread the love
Запись опубликована в рубрике IT рецепты с метками . Добавьте в закладки постоянную ссылку.