用 WiFiManager 库 + EEPROM库
#include <WiFiManager.h>
#include <EEPROM.h>
struct Settings {
char auth_key[13];
} sett;
// 功能描述:设置点击保存的回调
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
bool chkAuthkey(char* key, int len){
if (len != 12) return false;
for (int i=0;key[i]!=0;i++){
if (!isxdigit(key[i])) return false;
}
return true;
}
//----------------------------------------------------------------------------------
EEPROM.begin(1408);
EEPROM.get<Settings>(1280, sett);
WiFiManager wifiManager;
WiFi.mode(WIFI_STA);
//wifiManager.setDebugOutput(true);
// 重置保存的修改
if (digitalRead(GPIO_RESET) == LOW){
Serial.println(F("WiFi resetSettings."));
wifiManager.resetSettings();
}
//wifiManager.resetSettings(); //调试时打开
wifiManager.setAPStaticIPConfig(IPAddress(192,168,10,1), IPAddress(192,168,10,1), IPAddress(255, 255, 255, 0));
// 3分钟配网时间,如没有完成则退出配网.
// 例如原正常连接的WIFI路由掉线死机或不通电等情况, 通过配网超时后, 会重新进行连接原WIFI信号。 避免停在配网模式下等待
wifiManager.setConfigPortalTimeout(180);
//wifiManager.setConnectTimeout(240);
// 设置点击保存的回调
wifiManager.setSaveConfigCallback(saveConfigCallback);
WiFiManagerParameter custom_authkey("auth_key", "Authkey", sett.auth_key, 12);
wifiManager.addParameter(&custom_authkey);
//AP名称:ESP_AP 密码:12345678
if(!wifiManager.autoConnect("ESP_AP","12345678")) {
Serial.println(F("Failed to connect. Reset and try again. . ."));
Blinker.delay(3000);
ESP.restart();
Blinker.delay(5000);
}
Serial.println(F("Connected to Wifi."));
Serial.print(F("My IP:"));
Serial.println(WiFi.localIP());
// 保存自定义信息
if (shouldSaveConfig) {
Serial.println(F("saving config..."));
//Serial.println(custom_authkey.getValue());
strncpy(sett.auth_key, custom_authkey.getValue(), 12);
sett.auth_key[12] = '\0';
if (!chkAuthkey(sett.auth_key, strlen(sett.auth_key))){
Serial.println(F("Authkey is wrong."));
wifiManager.resetSettings();
ESP.restart();
Blinker.delay(5000);
}
EEPROM.put<Settings>(1280, sett);
if (EEPROM.commit()) {
Serial.println(F("EEPROM successfully committed"));
} else {
Serial.println(F("ERROR! EEPROM commit failed"));
}
}
EEPROM.end();
sett.auth_key[12] = '\0';
Blinker.begin(sett.auth_key,........................略........................);
|