khoih-prog / ESP_WiFiManager

This is an ESP32 / ESP8266 WiFi Connection Manager with fallback web configuration portal. Use this library for configuring ESP32 (including ESP32-S2 and ESP32-C3), ESP8266 modules' WiFi, etc. Credentials at runtime. You can also specify static DNS servers, personalized HostName, fixed or random AP WiFi channel. With examples supporting ArduinoJson
MIT License
371 stars 97 forks source link

Stationmode Static IP changes to dhcp when esp8266 is restarted #28

Closed 05prateek closed 4 years ago

05prateek commented 4 years ago
#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <ESP_WiFiManager.h> //Configuration Magic
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#if (defined(USE_STATIC_IP_CONFIG_IN_CP) && !USE_STATIC_IP_CONFIG_IN_CP)
// Force DHCP to be true
#if defined(USE_DHCP_IP)
#undef USE_DHCP_IP
#endif
#define USE_DHCP_IP     true
#else
// You can select DHCP or Static IP here
#define USE_DHCP_IP     false
#endif

#define USE_CONFIGURABLE_DNS      false
WiFiUDP Udp;
ESP_WiFiManager wifiManager;

unsigned int localUdpPort = 5000;
char incomingPacket[256];
char replyPacket[] = "color recieved";

void setup()
{
  Serial.begin(9600);
  Serial.println();

  wifiManager.setSTAStaticIPConfig(IPAddress(192,168,43,69),IPAddress(192,168,43,1),IPAddress(255, 255, 255, 0));
if (!wifiManager.autoConnect("rgbTower", "S1o2m3u4@")) {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.reset();
    delay(5000);
  }

  Serial.println(" connected");

  Udp.begin(localUdpPort);
  Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    // receive incoming UDP packets
    Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Serial.printf("UDP packet contents: %s\n", incomingPacket);

    // send back a reply, to the IP address and port we got the packet from
    Udp.beginPacket(Udp.remoteIP(), 5000);
    Udp.write(replyPacket);
    Udp.endPacket();
  }
} 

im very new to arduino and stuff, i made a code but i'm unable to keep the static IP persistent. it changes to dhcp as soon as i restart the esp. please correct me if i'm doing something wrong.

khoih-prog commented 4 years ago

Hi @05prateek

Thanks for using library. Don't worry about making error and

im very new to arduino and stuff

You can change your sketch as follows

#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#if (defined(USE_STATIC_IP_CONFIG_IN_CP) && !USE_STATIC_IP_CONFIG_IN_CP)
  // Force DHCP to be true
  #if defined(USE_DHCP_IP)
    #undef USE_DHCP_IP
  #endif
  #define USE_DHCP_IP     true
#else
  // You can select DHCP or Static IP here
  #define USE_DHCP_IP     false
#endif

#define USE_CONFIGURABLE_DNS      false

WiFiUDP Udp;

// SSID and PW for Config Portal
String ssid = "ESP_" + String(ESP.getChipId(), HEX);
const char* password = "your_password";

// SSID and PW for your Router
String Router_SSID;
String Router_Pass;

// Indicates whether ESP has WiFi credentials saved from previous session, or double reset detected
bool initialConfig = false;

unsigned int localUdpPort = 5000;
char incomingPacket[256];
char replyPacket[] = "color received";

IPAddress stationIP   = IPAddress(192, 168, 43, 69);
IPAddress gatewayIP   = IPAddress(192, 168, 43, 1);
IPAddress netMask     = IPAddress(255, 255, 255, 0);

#include <ESP_WiFiManager.h>              //https://github.com/khoih-prog/ESP_WiFiManager

void setup()
{
  Serial.begin(115200);
  while (!Serial);

  Serial.println("\nStarting AutoConnectAP on " + String(ARDUINO_BOARD));

  ESP_WiFiManager ESP_wifiManager("AutoConnectAP");

#if !USE_DHCP_IP    
  // Set static IP, Gateway, Subnetmask, Use auto DNS1 and DNS2.
  ESP_wifiManager.setSTAStaticIPConfig(stationIP, gatewayIP, netMask);
#endif

  // We can't use WiFi.SSID() in ESP32 as it's only valid after connected.
  // SSID and Password stored in ESP32 wifi_ap_record_t and wifi_config_t are also cleared in reboot
  // Have to create a new function to store in EEPROM/SPIFFS for this purpose
  Router_SSID = ESP_wifiManager.WiFi_SSID();
  Router_Pass = ESP_wifiManager.WiFi_Pass();

  //Remove this line if you do not want to see WiFi password printed
  Serial.println("Stored: SSID = " + Router_SSID + ", Pass = " + Router_Pass);

  // SSID to uppercase
  ssid.toUpperCase();

  if (Router_SSID != "")
  {
    ESP_wifiManager.setConfigPortalTimeout(120); //If no access point name has been previously entered disable timeout.
    Serial.println("Got stored Credentials. Timeout 120s");
  }
  else
  {
    Serial.println("No stored Credentials. No timeout");
    initialConfig = true;
  }

  if (initialConfig)
  {
    Serial.println("Starting configuration portal.");

    //sets timeout in seconds until configuration portal gets turned off.
    //If not specified device will remain in configuration mode until
    //switched off via webserver or device is restarted.
    //ESP_wifiManager.setConfigPortalTimeout(600);

    //it starts an access point
    //and goes into a blocking loop awaiting configuration
    if (!ESP_wifiManager.startConfigPortal((const char *) ssid.c_str(), password))
      Serial.println("Not connected to WiFi but continuing anyway.");
    else
      Serial.println("WiFi connected...yeey :)");
  }

#define WIFI_CONNECT_TIMEOUT        30000L
#define WHILE_LOOP_DELAY            200L
#define WHILE_LOOP_STEPS            (WIFI_CONNECT_TIMEOUT / ( 3 * WHILE_LOOP_DELAY ))

unsigned long startedAt = millis();

  while ( (WiFi.status() != WL_CONNECTED) && (millis() - startedAt < WIFI_CONNECT_TIMEOUT ) )
  {
    WiFi.mode(WIFI_STA);
    WiFi.persistent (true);
    // We start by connecting to a WiFi network

    Serial.print("Connecting to ");
    Serial.println(Router_SSID);

    WiFi.config(stationIP, gatewayIP, netMask);
    //WiFi.config(stationIP, gatewayIP, netMask, dns1IP, dns2IP);

    WiFi.begin(Router_SSID.c_str(), Router_Pass.c_str());

    int i = 0;
    while ((!WiFi.status() || WiFi.status() >= WL_DISCONNECTED) && i++ < WHILE_LOOP_STEPS)
    {
      delay(WHILE_LOOP_DELAY);
    }
  }

  Serial.print("After waiting ");
  Serial.print((millis() - startedAt) / 1000);
  Serial.print(" secs more in setup(), connection result is ");

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.print("connected. Local IP: ");
    Serial.println(WiFi.localIP());
  }
  else
    Serial.println(ESP_wifiManager.getStatus(WiFi.status()));  

  Serial.println(" connected");

  Udp.begin(localUdpPort);
  Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    // receive incoming UDP packets
    Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Serial.printf("UDP packet contents: %s\n", incomingPacket);

    // send back a reply, to the IP address and port we got the packet from
    Udp.beginPacket(Udp.remoteIP(), 5000);
    Udp.write(replyPacket);
    Udp.endPacket();
  }
}

It's possible we have some bug in autoconnect when using new STA Static IP. I'll definitely have a look at the possible. issue.

khoih-prog commented 4 years ago

Hi @05prateek

Just inform you that the new ESP_WiFiManager v1.0.11 has been released, with your contribution noted in Contributions-and-Thanks.

The autoConnect() bug has been fixed and autoConnect() function has been pulled out of the deprecated list. Now you can use your original sketch with STA static IP working as expected.

Releases 1.0.11

  1. Add optional CORS (Cross-Origin Resource Sharing) feature. Thanks to AlesSt. See more in Issue #27: CORS protection fires up with AJAX and Cross Origin Resource Sharing. To use, you must explicitly use #define USING_CORS_FEATURE true
  2. Solve issue softAP with custom IP sometimes not working. Thanks to AlesSt. See Issue #26: softAP with custom IP not working and Wifi.softAPConfig() sometimes set the wrong IP address.
  3. Temporary fix for issue of not clearing WiFi SSID/PW from flash of ESP32. Thanks to AlesSt. See more in Issue #25: API call /r doesnt clear credentials and WiFi.disconnect(true) problem.
  4. Fix autoConnect() feature to permit autoConnect() to use STA static IP or DHCP IP. Remove from deprecated functi0n list.
  5. Enhance README.md with more instructions and illustrations.