tzapu / WiFiManager

ESP8266 WiFi Connection manager with web captive portal
http://tzapu.com/esp8266-wifi-connection-manager-library-arduino-ide/
MIT License
6.6k stars 1.98k forks source link

Cannot ping or connect to the ESP32 (via socket) using the hostname #1400

Open MythicalForce opened 2 years ago

MythicalForce commented 2 years ago

Basic Infos

Hardware

WiFimanager Branch/Release: v2.0.10-beta+sha.b7ca079

Esp8266/Esp32:

Hardware: ESP32-WROOM-32UE

Description

I cant get the hostname to work with the wifimanager it reports back the right hostname in the output but i cannot ping my ESP32 nor connect to it via socket using the hostname (this works fine using default WiFi.h lib for ESP32)

Settings in IDE

platformio.ini

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
upload_speed = 921600
build_type = debug
monitor_filters = esp32_exception_decoder
build_flags = 
    -D VERSION=1.0.0
    -std=gnu++17
    -Ofast
lib_deps = 
    fastled/FastLED
    links2004/WebSockets
    bblanchon/ArduinoJson
    https://github.com/tzapu/WiFiManager
    khoih-prog/ESP_DoubleResetDetector
lib_compat_mode = strict

Sketch

#BEGIN
#pragma once

#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <globals.h>
#include <secrets.h>
#include "BluetoothSerial.h"

#define ESP_DRD_USE_SPIFFS true

#define DOUBLERESETDETECTOR_DEBUG       true

//#include <FS.h>
#include <SPIFFS.h>

#include <WiFiManager.h>

#include <ESP_DoubleResetDetector.h>

#include <ArduinoJson.h>

#define JSON_CONFIG_FILE "/sample_config.json"

// Number of seconds after reset during which a
// subseqent reset will be considered a double reset.
#define DRD_TIMEOUT 10

// RTC Memory Address for the DoubleResetDetector to use
#define DRD_ADDRESS 0

DoubleResetDetector *drd;

bool shouldSaveConfig = false;

char HostNameString[50];

void saveConfigFile()
{
  debug.info("[NETWORK]", "[JSON]", "Saving config");
  StaticJsonDocument<512> json;
  json["HostNameString"] = HostNameString;

  File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w");
  if (!configFile)
  {
    debug.error("[NETWORK]", "[JSON]", "Failed to open config file for writing");
  }

  serializeJsonPretty(json, Serial);
  if (serializeJson(json, configFile) == 0)
  {
    debug.error("[NETWORK]", "[JSON]", "Failed to write to file");
  }
  configFile.close();
}

bool loadConfigFile()
{
  //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  debug.info("[NETWORK]", "[JSON]", "Mounting FS...");

  // May need to make it begin(true) first time you are using SPIFFS
  // NOTE: This might not be a good way to do this! begin(true) reformats the spiffs
  // it will only get called if it fails to mount, which probably means it needs to be
  // formatted, but maybe dont use this if you have something important saved on spiffs
  // that can't be replaced.
  if (SPIFFS.begin(false) || SPIFFS.begin(true))
  {
    debug.success("[NETWORK]", "[JSON]", "Mounted file system");
    if (SPIFFS.exists(JSON_CONFIG_FILE))
    {
      //file exists, reading and loading
      debug.info("[NETWORK]", "[JSON]", "Reading config file");
      File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r");
      if (configFile)
      {
        debug.success("[NETWORK]", "[JSON]", "Opened config file");
        StaticJsonDocument<512> json;
        DeserializationError error = deserializeJson(json, configFile);
        serializeJsonPretty(json, Serial);
        if (!error)
        {
          debug.info("[NETWORK]", "[JSON]", "Parsed json");

          strcpy(HostNameString, json["HostNameString"]);

          return true;
        }
        else
        {
            debug.error("[NETWORK]", "[JSON]", "Failed to load json config");
        }
      }
    }
  }
  else
  {
    debug.error("[NETWORK]", "[JSON]", "Failed to mount FS");
  }
  //end read
  return false;
}

void saveConfigCallback()
{
    debug.warning("[NETWORK]", "[JSON]", "Should save config");
    shouldSaveConfig = true;
}

namespace network
{
    #if ENABLE_WIFI
    namespace wifi
    {
        void begin()
        {
            pinMode( WIFI_LED_PIN, OUTPUT );

            bool forceConfig = false;

            drd = new DoubleResetDetector(DRD_TIMEOUT, DRD_ADDRESS);
            if (drd->detectDoubleReset())
            {
                debug.info("[DOUBLEDETECTION]", "[DRD]", "Forcing config mode as there was a Double reset detected");
                forceConfig = true;
            }

            bool spiffsSetup = loadConfigFile();
            if (!spiffsSetup)
            {
                debug.info("[DOUBLEDETECTION]", "[SPIFFS]", "Forcing config mode as there is no saved config");
                forceConfig = true;
            }

            WiFi.mode( WIFI_STA ); // explicitly set mode, esp defaults to STA+AP

            WiFiManager wm;

            //wm.resetSettings();

            wm.setHostname( HostNameString );
            WiFi.setHostname( HostNameString );

            wm.setSaveConfigCallback(saveConfigCallback);

            WiFiManagerParameter custom_host_name("hostname", "Enter a Hostname here", HostNameString, 50);

            wm.addParameter(&custom_host_name);

            if (forceConfig)
            {
                if (!wm.startConfigPortal("Mythical-Neon-Controller", "12345678"))
                {
                    debug.info("[WIFIMANAGER]", "[AP]", "failed to connect and hit timeout");
                    delay(3000);
                    //reset and try again, or maybe put it to deep sleep
                    ESP.restart();
                    delay(5000);
                }
            }
            else
            {
                if (!wm.autoConnect( HostNameString, wm.getWiFiPass().c_str()))
                {
                    debug.info("[WIFIMANAGER]", "[AUTOCONNECT]", "failed to connect");
                    delay(3000);
                    // if we still have not connected restart and try all over again
                    ESP.restart();
                    delay(5000);
                }
                else
                {
                    debug.success("[NETWORK]", "[WIFI]", "WiFi Online!");
                    debug.info("[NETWORK]", "[WIFI]", "IP : %s", WiFi.localIP().toString().c_str());
                    debug.info("[NETWORK]", "[WIFI]", "WiFi Hostname : %s", WiFi.getHostname());
                    debug.info("[NETWORK]", "[WIFI]", "WM Hostname : %s", wm.getWiFiHostname().c_str());
                    debug.info("[NETWORK]", "[WIFI]", "String Hostname : %s", HostNameString);
                    digitalWrite( WIFI_LED_PIN, HIGH );
                }
            }            

            strncpy(HostNameString, custom_host_name.getValue(), sizeof(HostNameString));

            if (shouldSaveConfig)
            {
                saveConfigFile();
            }        
        }
    }
    #endif    
}
#END

Debug Messages

------------------------------------------------------------------------------------- 
- NETWORK                                                                   Startup - 
------------------------------------------------------------------------------------- 
SPIFFS Flag read = 0xD0D04321
No doubleResetDetected
Saving config file...
Saving config file OK
[I][NETWORK][JSON] Mounting FS... 
[S][NETWORK][JSON] Mounted file system 
[I][NETWORK][JSON] Reading config file 
[S][NETWORK][JSON] Opened config file 
{
  "HostNameString": "testmachine"
}
[I][NETWORK][JSON] Parsed json 
*wm:[2] Added Parameter: hostname
*wm:[1] AutoConnect 
*wm:[2] ESP32 event handler enabled 
*wm:[2] Setting Hostnames:  testmachine
*wm:[2] Setting WiFi hostname 
*wm:[2] Connecting as wifi client... 
*wm:[2] setSTAConfig static ip not set, skipping 
*wm:[1] Connecting to SAVED AP: Le’s
*wm:[1] connectTimeout not set, ESP waitForConnectResult... 
*wm:[2] Connection result: WL_CONNECTED
*wm:[1] AutoConnect: SUCCESS 
*wm:[2] Connected in 4126 ms
*wm:[1] STA IP Address: 192.168.68.122
[S][NETWORK][WIFI] WiFi Online! 
[I][NETWORK][WIFI] IP : 192.168.68.122 
[I][NETWORK][WIFI] WiFi Hostname : testmachine 
[I][NETWORK][WIFI] WM Hostname : testmachine 
[I][NETWORK][WIFI] String Hostname : testmachine 

------------------------------------------------------------------------------------- 
- Websocket                                                                 Startup - 
------------------------------------------------------------------------------------- 
[S][SOCKET][STATUS] Websocket Online! 
tablatronix commented 2 years ago

// #define WM_MDNS // includes MDNS, also set MDNS with sethostname

It is not enabled by default

wifi hostname is different than mdns

MDNS will only work if your network allows mdns broadcasts across network, otherwise it will only resolve on the same wifi

MythicalForce commented 2 years ago

oh i need to enable MDNS?

Do i set it befor or after #include <WiFiManager.h> ?

tablatronix commented 2 years ago

See edit caveats above,

tablatronix commented 2 years ago

you cannot set it in your sketch, you can do it in your environment or boards file or modify the wm.h file

tablatronix commented 2 years ago

if you use ota, on esp32 this is automatically handled I think

MythicalForce commented 2 years ago

if you use ota, on esp32 this is automatically handled I think

yea i plan to use OTA but yea i wanted to fix this hostname issue

MythicalForce commented 2 years ago

so i uncommented #define WM_MDNS // includes MDNS, also set MDNS with sethostname

is there anything else i would need to set or do?

MythicalForce commented 2 years ago

added this also

            if(!MDNS.begin( HostNameString ))
            {
                debug.error("[MDNS]", "[SETUP]", "Error starting mDNS");
                return;
            }
            else
            {
                debug.success("[MDNS]", "[SETUP]", "mDNS Started");
            }

but still not working

tablatronix commented 2 years ago

hmmm

MythicalForce commented 2 years ago

i realy wanna use WifiManager but if the hostname does not work :/ i need to find other if any

tablatronix commented 2 years ago

I tried testing this but my router was messed up, ill try again. Last time I checked it worked fine though.

MythicalForce commented 2 years ago

I tried testing this but my router was messed up, ill try again. Last time I checked it worked fine though.

https://cdn.discordapp.com/attachments/537365760008257569/967822241456849096/278949010_699082621339260_3346299735419732370_n.jpg

cause i can see ny ESP32 on my router with the hostname "testmachine"...

tablatronix commented 2 years ago

ok then are you on the same network when you try to find it?

testmachine.local or whatever?

MDNS is only valid on same vlan unless you have a router that has multicast forwarding on

Also you are calling autoconnect right?

MythicalForce commented 2 years ago

ok then are you on the same network when you try to find it?

Yes

Also you are calling autoconnect right?

                if (!wm.autoConnect( HostNameString, wm.getWiFiPass().c_str()))
                {
                    debug.info("[WIFIMANAGER]", "[AUTOCONNECT]", "failed to connect");
                    delay(3000);
                    // if we still have not connected restart and try all over again
                    ESP.restart();
                    delay(5000);
                }
                else
                {
                    debug.success("[NETWORK]", "[WIFI]", "WiFi Online!");
                    debug.info("[NETWORK]", "[WIFI]", "IP : %s", WiFi.localIP().toString().c_str());
                    debug.info("[NETWORK]", "[WIFI]", "WiFi Hostname : %s", WiFi.getHostname());
                    debug.info("[NETWORK]", "[WIFI]", "WM Hostname : %s", wm.getWiFiHostname().c_str());
                    debug.info("[NETWORK]", "[WIFI]", "String Hostname : %s", HostNameString);
                    digitalWrite( WIFI_LED_PIN, HIGH );
                }
tablatronix commented 2 years ago

ok not a mdns problem probably, I was confused for a second and assumed it was not DNS, Since hostname gets set in autoconnect, its possible that its broken when saving from configportal, workaround would be to restart after save.

Since we only set hostname in autoconnect, it might not be still set on save connect which used a different code

Can you confirm that it only is broken when saving? or is it never working?

cause mine does Screen Shot 2022-04-25 at 5 55 36 PM Screen Shot 2022-04-25 at 5 55 29 PM

tablatronix commented 2 years ago

ok nope mine works on save also, let me check blocking

tablatronix commented 2 years ago

Nope works fine for me.. even without MDNS enabled

tablatronix commented 2 years ago

Maybe string is broken? try harcoding char?

bool  WiFiManager::setHostname(const char * hostname){
  //@todo max length 32
  _hostname = String(hostname);
  return true;
}

bool  WiFiManager::setHostname(String hostname){
  //@todo max length 32
  _hostname = hostname;
  return true;
}
tablatronix commented 2 years ago

what esp version ? Try the SUPER/ondemand example?

MythicalForce commented 2 years ago

Can you confirm that it only is broken when saving? or is it never working?

Never working

try harcoding char?

Tried and not working

what esp version ?

Do you mean software version or hardware?

HW : ESP32-WROOM-32UE SW : v4.4-dev-3569-g6a7d83af19-dirty

tablatronix commented 2 years ago

Ok let me try 4.4

MythicalForce commented 2 years ago

Ok let me try 4.4

did you get any results?

tablatronix commented 2 years ago

not tested yet

tablatronix commented 2 years ago

Yeah just tested works fine also, must be something else going on

*wm:[1] ESP SDK version: v4.4-beta1-308-gf3e0c8bc41

Screen Shot 2022-04-27 at 9 45 19 PM

#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager

void setup() {
    WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
    Serial.begin(115200);
    WiFiManager wm;

    wm.setHostname("WM_TESTDNS");    

    bool res;
    res = wm.autoConnect("AutoConnectAP","password"); // password protected ap

    if(!res) {
        Serial.println("Failed to connect");
        // ESP.restart();
    } 
    else {
        //if you get here you have connected to the WiFi    
        Serial.println("connected...yeey :)");
    }

}

void loop() {
    // put your main code here, to run repeatedly:   
}
MythicalForce commented 2 years ago

@tablatronix hmmm weeeeird!

My Entire code as of now using wm.setHostname( "testmachine" );

#pragma once

#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <globals.h>
#include <secrets.h>
#include "BluetoothSerial.h"

#define ESP_DRD_USE_SPIFFS true

//#define WM_MDNS true

#define DOUBLERESETDETECTOR_DEBUG       true

//#include <FS.h>
#include <SPIFFS.h>

#include <WiFiManager.h>

#include <ESP_DoubleResetDetector.h>

#include <ArduinoJson.h>

#define JSON_CONFIG_FILE "/sample_config.json"

// Number of seconds after reset during which a
// subseqent reset will be considered a double reset.
#define DRD_TIMEOUT 10

// RTC Memory Address for the DoubleResetDetector to use
#define DRD_ADDRESS 0

DoubleResetDetector *drd;

bool shouldSaveConfig = false;

char HostNameString[50];

const char * hostname = "testmachine2";

void saveConfigFile()
{
  debug.info("[NETWORK]", "[JSON]", "Saving config");
  StaticJsonDocument<512> json;
  json["HostNameString"] = HostNameString;

  File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w");
  if (!configFile)
  {
    debug.error("[NETWORK]", "[JSON]", "Failed to open config file for writing");
  }

  serializeJsonPretty(json, Serial);
  if (serializeJson(json, configFile) == 0)
  {
    debug.error("[NETWORK]", "[JSON]", "Failed to write to file");
  }
  configFile.close();
}

bool loadConfigFile()
{
  //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  debug.info("[NETWORK]", "[JSON]", "Mounting FS...");

  // May need to make it begin(true) first time you are using SPIFFS
  // NOTE: This might not be a good way to do this! begin(true) reformats the spiffs
  // it will only get called if it fails to mount, which probably means it needs to be
  // formatted, but maybe dont use this if you have something important saved on spiffs
  // that can't be replaced.
  if (SPIFFS.begin(false) || SPIFFS.begin(true))
  {
    debug.success("[NETWORK]", "[JSON]", "Mounted file system");
    if (SPIFFS.exists(JSON_CONFIG_FILE))
    {
      //file exists, reading and loading
      debug.info("[NETWORK]", "[JSON]", "Reading config file");
      File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r");
      if (configFile)
      {
        debug.success("[NETWORK]", "[JSON]", "Opened config file");
        StaticJsonDocument<512> json;
        DeserializationError error = deserializeJson(json, configFile);
        serializeJsonPretty(json, Serial);
        if (!error)
        {
          debug.info("[NETWORK]", "[JSON]", "Parsed json");

          strcpy(HostNameString, json["HostNameString"]);

          return true;
        }
        else
        {
            debug.error("[NETWORK]", "[JSON]", "Failed to load json config");
        }
      }
    }
  }
  else
  {
    debug.error("[NETWORK]", "[JSON]", "Failed to mount FS");
  }
  //end read
  return false;
}

void saveConfigCallback()
{
    debug.warning("[NETWORK]", "[JSON]", "Should save config");
    shouldSaveConfig = true;
}

namespace network
{
    #if ENABLE_WIFI
    namespace wifi
    {
        void begin()
        {
            pinMode( WIFI_LED_PIN, OUTPUT );

            bool forceConfig = false;

            drd = new DoubleResetDetector(DRD_TIMEOUT, DRD_ADDRESS);
            if (drd->detectDoubleReset())
            {
                debug.info("[DOUBLEDETECTION]", "[DRD]", "Forcing config mode as there was a Double reset detected");
                forceConfig = true;
            }

            bool spiffsSetup = loadConfigFile();
            if (!spiffsSetup)
            {
                debug.info("[DOUBLEDETECTION]", "[SPIFFS]", "Forcing config mode as there is no saved config");
                forceConfig = true;
            }

            WiFi.mode( WIFI_STA ); // explicitly set mode, esp defaults to STA+AP

            WiFiManager wm;

            wm.setHostname( "testmachine" );

            //wm.resetSettings();

            /*
            if(!MDNS.begin( HostNameString ))
            {
                debug.error("[MDNS]", "[SETUP]", "Error starting mDNS");
                return;
            }
            else
            {
                debug.success("[MDNS]", "[SETUP]", "mDNS Started");
            }
            */
            //wm.setConnectTimeout(60);
            //wm.setTimeout(120);
            //wm.setConfigPortalTimeout(120);

            wm.setSaveConfigCallback(saveConfigCallback);

            WiFiManagerParameter custom_host_name("hostname", "Enter a Hostname here", HostNameString, 50);

            wm.addParameter(&custom_host_name);

            if (forceConfig)
            {
                if (!wm.startConfigPortal("Mythical-Neon-Controller", "12345678"))
                {
                    debug.info("[WIFIMANAGER]", "[AP]", "failed to connect and hit timeout");
                    delay(3000);
                    //reset and try again, or maybe put it to deep sleep
                    ESP.restart();
                    delay(5000);
                }
            }

            bool res;
            res = wm.autoConnect();
            if (!res)
            {
                debug.info("[WIFIMANAGER]", "[AUTOCONNECT]", "failed to connect");
                delay(3000);
                // if we still have not connected restart and try all over again
                ESP.restart();
                delay(5000);
            }
            else
            {
                debug.success("[NETWORK]", "[WIFI]", "WiFi Online!");
                debug.info("[NETWORK]", "[WIFI]", "IP : %s", WiFi.localIP().toString().c_str());
                debug.info("[NETWORK]", "[WIFI]", "WiFi Hostname : %s", WiFi.getHostname());
                debug.info("[NETWORK]", "[WIFI]", "WM Hostname : %s", wm.getWiFiHostname().c_str());
                debug.info("[NETWORK]", "[WIFI]", "String Hostname : %s", HostNameString);
                digitalWrite( WIFI_LED_PIN, HIGH );
            }         

            strncpy(HostNameString, custom_host_name.getValue(), sizeof(HostNameString));

            if (shouldSaveConfig)
            {
                saveConfigFile();
            }

            /*
            WiFi.mode( WIFI_STA );
            WiFi.setSleep ( false );

            WiFi.setHostname( "testmachine" ); // Config[DEVICE].Wifi_DNS

            WiFi.begin( WIFI_SSID, WIFI_PASS );

            for (uint iPass = 0; iPass < 10; iPass++)
            {
                if( WiFi.status() == WL_CONNECTED )
                {
                    debug.success("[NETWORK]", "[WIFI]", "WiFi Online!");
                    debug.info("[NETWORK]", "[WIFI]", "IP : %s", WiFi.localIP().toString().c_str());
                    debug.info("[NETWORK]", "[WIFI]", "Hostname : %s", WiFi.getHostname());
                    digitalWrite( WIFI_LED_PIN, HIGH );
                    break;
                }
                else
                {
                    delay( 500 );
                    digitalWrite( WIFI_LED_PIN, HIGH );
                    delay ( 500 );
                    digitalWrite( WIFI_LED_PIN, LOW );
                }
            } 
            */           
        }
    }
    #endif

    namespace ble
    {

        #if ENABLE_BLE
        #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
        #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
        #endif

        BluetoothSerial BLE_SERIAL;
        #endif

        void begin()
        {
            #if ENABLE_BLE
            if( BLE_SERIAL.begin(BLE_HOSTNAME) )
            {
                debug.info("[NETWORK]", "[BLE]", "Online");
            }
            #endif
        }
        void loop()
        {
            #if ENABLE_BLE
            if (Serial.available())
            {
                BLE_SERIAL.write(Serial.read());
            }
            if (BLE_SERIAL.available())
            {
                Serial.write(BLE_SERIAL.read());
            }
            #endif
        }
    }

}

but yea not working :S

MythicalForce commented 2 years ago

@tablatronix i found out the problem in the end.... the router in my apartment "TP-Link Deco M5" does not support hostname resolve -.- .... annoying AF!!!