note: this is part of a larger program which offers a "configuration" and a "deep sleep" mode the first being in softAP mode the second uses this function which is called in the setup() function portion in arduino ide when the device is configured and when it comes back from deepsleep.
(see commented lines for hardcode version)
void start_wifi_client() {
//const char* client_ssid = "test_iot_2g";
//const char* client_password = "Test1234";
//IPAddress wifi_ip(10,0,0,144);
//IPAddress wifi_dns(10,0,0,4);
//IPAddress wifi_gateway(10,0,0,129);
//IPAddress wifi_subnet(255,255,255,224);
// **** loading from SPIFFS ****
String s,wifi_ssid="",wifi_password;
IPAddress wifi_ip,wifi_subnet,wifi_gateway;
File file = SPIFFS.open("/wifi.cfg","r");
if(!file) {
Serial.println("Could not open config file");
} else {
Serial.println("Reading Config...");
do {
s = file.readStringUntil('\n');
if(s.startsWith("ssid")) { wifi_ssid=s.substring(s.indexOf('=')+1,s.length()); Serial.print(wifi_ssid); }
else if(s.startsWith("passkey")) { wifi_password=s.substring(s.indexOf('=')+1,s.length()); } //Serial.print(wifi_password); }
else if(s.startsWith("ip")) { wifi_ip.fromString(s.substring(s.indexOf('=')+1,s.length())); Serial.print(wifi_ip.toString()); }
else if(s.startsWith("subnet")) { wifi_subnet.fromString(s.substring(s.indexOf('=')+1,s.length())); Serial.print(wifi_subnet.toString()); }
else if(s.startsWith("gateway")) { wifi_gateway.fromString(s.substring(s.indexOf('=')+1,s.length())); Serial.print(wifi_gateway.toString()); }
Serial.print("\n");
} while(file.available());
delay(10);
file.close();
// *** end loading config ***
Serial.println("");
Serial.print("Connecting to: ");
Serial.print(wifi_ssid);
Serial.print("\n");
//WiFi.forceSleepWake();
//WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.config(wifi_ip,wifi_gateway,wifi_subnet);
float time_count=0;
Serial.println("connected to wifi");
WiFi.begin(wifi_ssid, wifi_password);
do {
delay(100);
// led_blink();
Serial.print(".");
time_count+=100;
} while(WiFi.status() != WL_CONNECTED);
Serial.print("\ntook ");
Serial.print((time_count/1000));
Serial.print(" sec to connect\n");
Serial.print("Our ip is: ");
Serial.print(WiFi.localIP());
Serial.print("\n");
}
}