我正在开发一款物联网设备,它应该使用HTTP/REST API提供一些功能。我决定使用ESP32芯片(在“ESP32 dev board”上)。
现在,我想实现易于使用的 WLAN 配置。我不想像其他示例那样在源代码中存储凭据;因此,我决定使用 WPS。
我尝试使用以下来源实现基本的 Web 服务器: https://randomnerdtutorials.com/esp32-web-server-arduino-ide/,然后我从 ESP32 扩展库为 Arduino IDE 提供的 WiFi/WPS 示例中添加了 WPS 功能。
现在,WPS 已经可以使用了,即当开发板上电时,它处于 WPS 连接模式,并等待路由器接受 WPS 连接。它成功获取 SSID 并连接到 WLAN。
但是当我关闭 ESP32 然后再次打开时,我必须再次执行 WPS 重新连接过程。我期望进行重新连接,以存储凭据并能够在以后任何时间打开 ESP32 设备时再次连接到同一 WLAN。我想我必须存储一些凭据并使用它们重新建立连接,但我在哪里获取凭据,以及如何重新连接呢?
我在网上搜索了“ESP32 WLAN WPS reconnect”和类似的术语,但只找到了非WPS(SSID+密码)连接的重新连接策略。我还检查了WiFi库文档和esp_wps库文档,但没有找到合适的东西。
这是 WLAN WPS 连接源代码:
#include <WiFi.h>
#include "esp_wps.h"
#define ESP_WPS_MODE WPS_TYPE_PBC
esp_wps_config_t config = WPS_CONFIG_INIT_DEFAULT(ESP_WPS_MODE);
String wpspin2string(uint8_t a[]){
//...
}
void WiFiEvent(WiFiEvent_t event, system_event_info_t info){
switch(event){
case SYSTEM_EVENT_STA_START:
Serial.println("Station Mode Started");
break;
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("Connected to :" + String(WiFi.SSID()));
Serial.print("Got IP: ");
Serial.println(WiFi.localIP());
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("Disconnected from station, attempting reconnection");
WiFi.reconnect();
break;
case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
Serial.println("WPS Successfull, stopping WPS and connecting to: " + String(WiFi.SSID()));
esp_wifi_wps_disable();
delay(10);
WiFi.begin();
break;
case SYSTEM_EVENT_STA_WPS_ER_FAILED:
Serial.println("WPS Failed, retrying");
esp_wifi_wps_disable();
esp_wifi_wps_enable(&config);
esp_wifi_wps_start(0);
break;
case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
Serial.println("WPS Timedout, retrying");
esp_wifi_wps_disable();
esp_wifi_wps_enable(&config);
esp_wifi_wps_start(0);
break;
case SYSTEM_EVENT_STA_WPS_ER_PIN:
Serial.println("WPS_PIN = " + wpspin2string(info.sta_er_pin.pin_code));
break;
default:
break;
}
}
// some GPIO stuff, removed for SO question
void setup() {
// initialize some GPIO for status etc. - removed for SO
//Initialize serial and wait for port to open:
Serial.begin(115200);
while(!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// We start by connecting to a WiFi network
WiFi.onEvent(WiFiEvent);
WiFi.mode(WIFI_MODE_STA);
Serial.println("Starting WPS");
esp_wifi_wps_enable(&config);
esp_wifi_wps_start(0);
// attempt to connect to Wifi network:
while(WiFi.status() != WL_CONNECTED) {
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
delay(700);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
//irrelevant for SO question
}