问题
I am facing a peculiar problem. The below code snippet connects to new WiFi network. No hard-coded ssid or password in the program. I am using AsyncWifiManager and AsyncWebServer modules. When I am connecting to my home WiFi router providing ssid and password in autoconnect portal, NodeMCU is getting connected and the server is working fine. But whenever I am changing the WiFi, connecting to my mobile phone hotspot, then server is not running, though I am getting local IP address in Serial Monitor.
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncWiFiManager.h>
#include <FS.h>
#include <Wire.h>
AsyncWiFiManager wifiManager(&server,&dns);
// To clean previous settings. Use one time, then comment
// wifiManager.resetSettings();
// set custom static ip for portal
IPAddress staticIP(192,168,0,20); //ESP static ip
IPAddress gateway(192,168,0,1); //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255,255,255,0); //Subnet mask
wifiManager.setSTAStaticIPConfig(staticIP, gateway, subnet);
// Open WiFi Setup portal
wifiManager.autoConnect();
Serial.println("Connecting to WiFi..");
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
WiFi.begin();
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
I am programming the NodeMCU board via Arduino IDE.
回答1:
As your code uses fix parameters for IP/subnet/gateway you have to setup your different hotspots accordingly or you have the following options to choose from as you connect your ESP8266 server to different hotspots:
- always being in the same network/subnetwork (all hotspots are part of a local network) you can use fix IP-addresses for all devices irrelevant of the hotspot you connect to
- If you do not want to use above (=fix IP for all devices): Set the DHCP server to always give the same IP addresses to the NodeMCUs based on their MAC addresses.
- You use mDNS and give the ESP8266 a fixed name and call via http://nyPreferredESP.local (allthough the IP varies) and use on your Android phone something like this APP
- If you want to work with changing gateways (Devices not on the same net/subnet, access over the internet): This would require something a little more robust. Use a Dynamic DNS service along with a domain name. The Dynamic DNS will update your DNS records in almost real time if your gateway address changes. Example here
The complexity of the solution results from the factor always in the same network/subnet and a fixed gateway or everything (except MAC-address and name of the device are fix) and the rest may be variable. Read some basics about setting up a local network here
来源:https://stackoverflow.com/questions/61665434/inconsistent-connectivity-via-wifi-manager-in-esp8266