使用 WIFI_AP_STA 模式在 ESP8266 上配置 WiFi

Configure WiFi on ESP8266 uing WIFI_AP_STA mode

我正在尝试对我的 NodeMCU (Lolin v3) 板进行编程,以便我可以使用它来配置 WiFi 设置,而无需对凭据进行硬编码。我知道有一个 WiFiManager 库,但我不打算使用它,因为我需要自己实现,而不是使用库提供的 UI。用户提供的凭据使用 SPIFFS 存储在一个文件中,用于检查是否仅以 AP_STA 模式或 STA 模式启动开发板。

以下是我使用的逻辑:

void connectWiFi(String ssid, String password, boolean staOnly = false) {
  boolean state = true;
  int i = 0;
  if(staOnly)
    WiFi.mode(WIFI_STA);
  WiFi.begin(ssid.c_str(), password.c_str());
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if (i > 10) {
      state = false;
      break;
    }
    i++;
  }
  return state;
}

void join() {
  String ssid = setupServer.arg("ssid");
  String password = setupServer.arg("password");
  result = connectWifi(ssid, password);
  if(result) {
    Serial.println("Connected");
    // **THIS IS THE PROBLEMATIC PART**
    setupServer.send(200, "text/plain", WiFi.localIP().toString());
    // save credentials to a file
    Serial.println("Conf saved");
    delay(2000);
    ESP.restart();
  } else
    setupServer.send(200, "text/plain", "fail");
  }

void setup() {
  Serial.begin(115200);
  WiFi.disconnect(true);
  boolean fileExists = SPIFFS.exists(WIFI_CONF_FILE);
  if(!fileExists) {
    WiFi.mode(WIFI_AP_STA);
    WiFi.softAP("AP", "password");
    IPAddress myIP = WiFi.softAPIP();
    setupServer = ESP8266WebServer(myIP, 8888);
    setupServer.on("/join", join);
    setupServer.begin();
  } else {
    // read file contents for ssid and password
    connectWifi(ssid, password, true);
    // do some work here
  }
}

void loop() {
  setupServer.handleClient();
}

所以现在当我重新启动时,电路板进入 AP_STA 模式并以 SSID AP 启动。我连接到它并在浏览器中打开 http://192.169.4.1/join?ssid=mywifi&password=12345678。连接以某种方式终止,我在浏览器中看到 "Destination Unreachable"。但是串行监视器打印 'Connected' 和 'Conf saved'.

我想知道为什么它没有 return 向浏览器发送成功响应。连接到 WiFi 后,我需要 localIP。它 return 正确地处理失败的响应,以防它失败。我如何确保它总是 return 在重新启动之前将分配给它的 IP 地址返回给连接到它的客户端?

感谢任何帮助。

谢谢!

看起来这是必然发生的,因为无线电模块在两种模式之间共享。

在这里找到了这个问题的解释:https://github.com/esp8266/Arduino/issues/3282

This is related to the fact that STA will switch to the channel of the AP it is trying to connect to, and SoftAP will have to switch to the same channel. So the client (PC or smartphone connected to the SoftAP) will have to reconnect to the SoftAP on its new channel. In most cases this causes TCP connections to be reset.