I have created an ESP-07 based project where one can configure the unit to run in either STA mode (using SSID and password from its configuration in EEPROM) or as a SoftAP unit.
Now I have run into a problem when the device is moved from one location to another where the configured WiFi network does not exist. In this case I want it to fall back to its SoftAP mode, which it uses during initial configuration, so can change the SSID/password it shall connect to.
Is it possible to add such a mode of operation and if so is there some sample code on how to do it?
It seems like in setup() one should provide for the case that it is configured for STA but cannot connect...
One approach could be this:
InitConfig(); //Initialize handling of configuration via EEPROM
int sta_connected = 0;
if (ESPConf.mode == WIFI_STA)
{
WiFi.mode((WiFiMode)ESPConf.mode); //WIFI_AP, WIFI_STA, WIFI_AP_STA, WIFI_OFF
local_ip = IPAddress(0,0,0,0);
WiFi.config(local_ip, local_ip, local_ip); //Reset to use DHCP
WiFi.hostname(ESPConf.host); //This is the hostrname that should be supplied to the DHCP server
WiFi.begin(ESPConf.ssid, ESPConf.passwd);
if(WiFi.waitForConnectResult() == WL_CONNECTED)
{
IP2str(ipbuf, WiFi.localIP());
MsgDbg = "STA ADDR = " + String(ipbuf);
sta_connected = 1;
}
else
MsgDbg = "WiFi connection to " + String(ESPConf.ssid) + " failed! Starting SoftAP instead";
SerialDebug.println(MsgDbg);
}
if ((ESPConf.mode == WIFI_AP) || (!sta_connected)) //Mode WIFI_AP or failed to connect WIFI_STA
{
WiFi.mode(WIFI_AP); //WIFI_OFF, WIFI_STA, WIFI_AP, WIFI_AP_STA
WiFi.softAPConfig((IPAddress)ESPConf.addr, (IPAddress)ESPConf.addr, netmask);
WiFi.softAP(ESPConf.ssid, ESPConf.passwd, ESPConf.wichannel, true);
}
But is it possible to restart WiFi in AP mode after it has been initialized in STA mode but failed to connect?
Is there some master reset that has to be done first (when it fails to connect)?