Solved: ESP32 NodeMCU informing the user which IP is connected!

This topic below has English and Portuguese-Br version.
English:
For those who want to create IOT (Internet Of Things) programs using WiFI and ESP 32 (https://i.ebayimg.com/images/g/jEYAAOSwE~xjc87W/s-l1600.jpg), you will find the problem of knowing which IP was connected to, in cases where the internet router works in DHCP (assigns an automatic IP for each connection made). This is a problem when we offer our solution to a customer because we cannot program the ESP32 in advance, and when the customer register it on their network, they do not know which IP was connected and therefore cannot open the webPage that was embedded on the ESP32 to be able to use it, whether for activate buttons and resources assigned to them or other previously configured applications.
After several consultations and studying the "wifiManager" library, I found a way to get the ESP32 to inform the user which IP of the user's WiFi network (DHCP) was obtained when connecting.
Below is a step-by-step guide for the user to see the IP and the program to record on the ESP32.
I hope it helps anyone who has this need.

Portugues:
Para quem quer criar programas de IOT (Internet das coisas) usando o WiFI e o ESP 32 (exemplo -> https://i.ebayimg.com/images/g/jEYAAOSwE~xjc87W/s-l1600.jpg), vai encontrar o problema de saber qual o IP ao qual ele se conectou, nos casos em que o roteador de internet trabalha em DHCP (atribui um IP automático para cada conexão feita). Isso é um problema quando oferecemos nossa solução para algum cliente pois não podemos programar previamento o ESP32, e quando o cliente consegue cadastra-lo na sua rede, ele não sabe qual foi o IP conectado e portanto, não consegue abrir a webPage que foi embutida no ESP32 para poder usa-la, seja para acionar botoes e recursos atribuidos a eles ou outras aplicações previamente configuradas.
Após várias consultas e estudando a library "wifiManager", consegui que o ESP32 informasse ao usuario qual o IP da rede WiFi (DHCP) do usuário foi obtido ao se conectar.
Segue abaixo o passo a passo para que o usuario veja o IP, e o programa para gravar no ESP32.
Espero que ajude quem tem essa necessidade.

/**
 * Basic example using LittleFS to store data
 English: step by step for connection:
   1) Search your cell phone for the list of available WiFi, locate the network "AP:192.168.4.1" and connect to it
   2) use the password: "password" (without the quotes) to connect to this new network to configure your connection
   3) In your browser type 192.168.4.1 to open the configuration page for your Wifi
   4) click on the "Configure WiFi" button
   5) All available WiFi will be listed, choose your WiFi network and password and save, this connection 192.168.4.1 will be disconnected.
   6) Now the NodeMCU will be connected but we still don't know which IP the Node MCU got from your router
   7) On NodeMCU, click the "flash" button to open a new WiFi network.
   8) Search your cell phone for the list of available WiFi, locate the network "Which_IP-192.168.4.1" and connect to it.
   9) In your browser, type 192.168.4.1 to open the configuration page and it will show which IP your NodeMCU is using.
   10) close your browser and reconnect to your WiFi network normally
   
 Pt-Br: passo a passo para conexão:
  1) Procure no seu celular a lista de wifi disoniveis, localize a rede "AP:192.168.4.1" e conecte-se a ela
  2) use a senha: "password" (sem as aspas) para se conectar nessa nova rede para configurar sua conexão
  3) No seu navegador digite 192.168.4.1 para abrir a pagina de configuração para seu Wifi
  4) clique no botão "Configure WiFi"
  5) Será listado todas as WiFi disponiveis, escolha a sua rede WiFi e sua senha e salve, essa conexão 192.168.4.1 será desfeita.
  6) Agora o NodeMCU estará conectado mas ainda não sabemos qual o IP que o Node MCU pegou do seu roteador
  7) No NodeMCU, clique no botão "flash", para abrir uma nova rede WiFi.
  8) Procure no seu celular a lista de wifi disoniveis, localize a rede "Which_IP-192.168.4.1" e conecte-se a ela.
  9) No seu navegador digite 192.168.4.1 para abrir a pagina de configuração e lá estará mostrado qual o IP que seu NodeMCU está usando.
  10) feche seu navegador e volte a se conectar na sua rede WiFi normalmente
*/

#include <Arduino.h>
#include <LittleFS.h>
#include <FS.h>

String readFile(fs::FS &fs, const char *path) {
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path, "r");
  if (!file || file.isDirectory()) {
    Serial.println("- empty file or failed to open file");
    return String();
  }
  Serial.println("- read from file:");
  String fileContent;
  while (file.available()) {
    fileContent += String((char)file.read());
  }
  file.close();
  Serial.println(fileContent);
  return fileContent;
}
void writeFile(fs::FS &fs, const char *path, const char *message) {
  Serial.printf("Writing file: %s\r\n", path);
  File file = fs.open(path, "w");
  if (!file) {
    Serial.println("- failed to open file for writing");
    return;
  }
  if (file.print(message)) {
    Serial.println("- file written");
  } else {
    Serial.println("- write failed");
  }
  file.close();
}

int data = 4;

#include <WiFiManager.h>
#define TRIGGER_PIN 0     // when pressing the NodeMCU Flash button after connected, it shows the connected IP when accessing port 192.168.4.1
int timeout = 120;  	  // seconds to run for

//------------------------------------------------------------------------------------------------------------------------------------------
void setup() {
  Serial.begin(115200);
  if (!LittleFS.begin()) {  //to start littlefs
    Serial.println("LittleFS mount failed");
    return;
  }
  data = readFile(LittleFS, "/data.txt").toInt();
  WiFi.mode(WIFI_STA);  // explicitly set mode, esp defaults to STA+AP
  // put your setup code here, to run once:
  pinMode(TRIGGER_PIN, INPUT_PULLUP);
  WiFiManager wm;
  //wm.resetSettings();
  bool res;
  res = wm.autoConnect("AP:192.168.4.1","password");  //password to connect is -->  password
  if (!res) {
    Serial.println("Failed to connect");
    // ESP.restart();
  }
}

//------------------------------------------------------------------------------------------------------------------------------------------
void loop() {
  if (digitalRead(TRIGGER_PIN) == LOW) {
    WiFiManager wm;
    //wm.resetSettings();
    wm.setConfigPortalTimeout(timeout);
    if (!wm.startConfigPortal("Wich_IP-192.168.4.1")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      ESP.restart();
      delay(5000);
    }
    Serial.println("connected...OK :)");
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.