Site icon Renzo Mischianti

Come gestire dinamicamente la configurazione WIFI su esp8266 o esp32

WiFiManager seleziona un AP e parametri main

Spread the love

Una delle esigenze più comuni quando si utilizza un dispositivo IOT con WIFI è la configurazione del WiFi stesso, non è bello mettere a codice i parametri, ma una libreria consente di collegare il tuo esp8266/esp32 ai diversi punti di accesso (AP) senza doverli mettere a codice. Inoltre, puoi anche aggiungere parametri personalizzati (variabili) e gestire più connessioni SSID, il tutto grazie alla libreria WiFiManager.

Di seguito il ciclo di vita della libreria:

Libreria

Puoi trovare la libreria qui here, ma la puoi scaricare direttamente dall’ArduinoIDE Tools --> Manage library...

WifiManager library

How to

Per prima cosa imposta il tuo IDE per sovrascrivere anche le impostazioni WiFi:

ArduinoIDE override all WIFI parameters

Uso standard

Quindi aggiungi questo sketch modificato dall’esempio originale

/*
 * Simple WiFiManager usage
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 * written by Renzo Mischianti <www.mischianti.org>
 */

#include <ESP8266WiFi.h>        

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect("esp8266 mischiantis test")) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  } 

  //if you get here you have connected to the WiFi
  Serial.println(F("WIFIManager connected!"));

  Serial.print(F("IP --> "));
  Serial.println(WiFi.localIP());
  Serial.print(F("GW --> "));
  Serial.println(WiFi.gatewayIP());
  Serial.print(F("SM --> "));
  Serial.println(WiFi.subnetMask());

  Serial.print(F("DNS 1 --> "));
  Serial.println(WiFi.dnsIP(0));

  Serial.print(F("DNS 2 --> "));
  Serial.println(WiFi.dnsIP(1));
 
}

void loop() {
  // put your main code here, to run repeatedly:

}

Ed ora segui questi step

Seleziona la rete “esp8266 mischiantis test”

WiFiManager AP list

Quando ti connetti, verrai reindirizzato automaticamente alla pagina 192.168.4.1:

WiFiManager menu

Qui puoi selezionare “Configura WiFi”, e nella pagina successiva puoi selezionare il punto di accesso desiderato.

WiFiManager select AP

Quindi inserisci la password e attendi la pagina di risposta.

WiFiManager result

Ora che sei connesso, puoi vedere i dati risultanti sulla console:

*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result: 
*WM: 3
*WM: IP Address:
*WM: 192.168.1.101
WIFIManager connected!
IP --> 192.168.1.101
GW --> 192.168.1.1
SM --> 255.255.255.0
DNS 1 --> 85.37.17.12
DNS 2 --> 8.8.8.8
*WM: freeing allocated params!

Parametri aggiuntivi

Puoi usare l’interfaccia dinamica del WiFiManager per aggiungere parametri, qui un esempio:

/*
 * Simple WiFiManager usage with additional parameter
 * https://mischianti.org/
 *
 * The MIT License (MIT)
 * written by Renzo Mischianti <www.mischianti.org>
 */

#include <ESP8266WiFi.h>

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

//define your default values here, if there are different values in config.json, they are overwritten.
char mqtt_server[40];
char mqtt_port[6] = "8080";
char blynk_token[34] = "YOUR_BLYNK_TOKEN";

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_mqtt_server("server", "Here a server IP", mqtt_server, 40);
  WiFiManagerParameter custom_mqtt_port("port", "Here a server port", mqtt_port, 6);
  WiFiManagerParameter custom_blynk_token("blynk", "Here a blynk token", blynk_token, 32);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_blynk_token);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect("esp8266 mischiantis test")) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  } 

  //if you get here you have connected to the WiFi
  Serial.println(F("WIFIManager connected!"));

  Serial.print(F("IP --> "));
  Serial.println(WiFi.localIP());
  Serial.print(F("GW --> "));
  Serial.println(WiFi.gatewayIP());
  Serial.print(F("SM --> "));
  Serial.println(WiFi.subnetMask());

  Serial.print(F("DNS 1 --> "));
  Serial.println(WiFi.dnsIP(0));

  Serial.print(F("DNS 2 --> "));
  Serial.println(WiFi.dnsIP(1));
 
  //read updated parameters
  strcpy(mqtt_server, custom_mqtt_server.getValue());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(blynk_token, custom_blynk_token.getValue());

  Serial.print(F("server --> "));
  Serial.println(mqtt_server);
  Serial.print(F("port --> "));
  Serial.println(mqtt_port);
  Serial.print(F("blynk --> "));
  Serial.println(blynk_token);

}

void loop() {
  // put your main code here, to run repeatedly:

}

lo schermo ora mostra i parametri

WiFiManager select AP and parameter

Il risultato della console mostra il valore inserito

*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result: 
*WM: 4
Entered config mode
192.168.4.1
esp8266 mischiantis test
*WM: 
*WM: Configuring access point... 
*WM: esp8266 mischiantis test
*WM: AP IP address: 
*WM: 192.168.4.1
*WM: HTTP server started
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Handle root
*WM: Request redirected to captive portal
*WM: Scan done
*WM: reef-casa-sopra
*WM: -61
*WM: reef-casa-centro
*WM: -82
*WM: Sent config page
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: WiFi save
*WM: Parameter
*WM: server
*WM: server.mischianti.org
*WM: Parameter
*WM: port
*WM: 8080
*WM: Parameter
*WM: blynk
*WM: YOUR_BLYNK_TOKEN

IP statico

È possibile definire un IP statico anche aggiungendo questo codice prima della connessione automatica.

  IPAddress _ip = IPAddress(192, 168, 1, 10);
  IPAddress _gw = IPAddress(192, 168, 1, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);
  
  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);

Grazie

Questa è una libreria molto utile, ma a volte è necessario modificare alcune parti del codice per adattarle al progetto.

Per gestire il server DNS per permettere al dispositivo di connettersi su server remoto ho dovuto cambiare del codice, puoi trovare la mia versione qui .

wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn, _dns1, _dns2);

Spread the love
Exit mobile version