frankcohen / EleksTubeIPSHack

Hacking the Elekstube IPS ESP32 TFT based clock
GNU General Public License v3.0
69 stars 22 forks source link

Bug: Save settings correctly #5

Open koshisan opened 3 years ago

koshisan commented 3 years ago

Right now the settings are not saved correctly - which is especially annoying for the Wifi-stuff

koshisan commented 3 years ago

I took a look at it to get familiar with your code and it didn't seem like a huge issue at first.

Like you said the original code is still there, it just isn't used currently. SmittyHalibut even included a struct for wifi credentials in his storedconfig class.

So basically there are just two things that need to happen:

On startup we should load the configuration, check for existing Wifi details and join the network. If the join fails, we should start our own AP after a few retries (note that the ESP32 is known to sometimes fail to join a wifi network on the first attempt without reason...)

So we basically have something like this on startup (retries are not implemented yet):

 if (stored_config.config.wifi.is_valid) {

  Serial.print( "Valid configuration found, connecting to: " );
  Serial.print( ssid );
  Serial.print( ", using password: " );
  Serial.println( password );

  ssid = stored_config.config.wifi.ssid;
  password = stored_config.config.wifi.password;

  WiFi.begin( ssid, password );

  } else {
  Serial.print( "Starting Wifi Access Point, connect to: " );
  Serial.print( APssid );
  Serial.print( ", using password: " );
  Serial.println( APpassword );
  Serial.print( "Upon connection point your browser to:" );
  Serial.print( "192.168.1.1" );
  Serial.print( " to view the main menu." );
  Serial.println( "The gateway is at 192.168.1.1 and subnet mask is 255.255.255.0" );

  WiFi.mode(WIFI_MODE_APSTA);
  WiFi.disconnect();

  smartDelay(500);

  WiFi.softAP(APssid, APpassword);
  WiFi.softAPConfig(local_ip, gateway, subnet);

  smartDelay(1000);

  }

Of course, the config needs to be loaded before that and the variables for our own AP have to be renamed in the initial declaration (APssid/APpassword)

Next we need to add code to the wifi connection handler of the webserver, so it can save our settings once connected successfully:

  if ( WiFi.status() == WL_CONNECTED )
  {
    resp += "Connected<br>";
     strncpy(stored_config.config.wifi.ssid, ssid, 32);
     strncpy(stored_config.config.wifi.password, password, 32);
     stored_config.config.wifi.is_valid = StoredConfig::valid;
     Serial.print("Saving config.");   
     stored_config.save();

  }

Which is were I failed yesterday ;) I have to admit that I am not too familiar with c/c++. I am normally used to something a bit more modern/highlevel, so I regular stumble over type conversions... I thought the code above should work and it does compile - however, it crashes the ESP when saving sending it into a reboot loop...