tzapu / WiFiManager

ESP8266 WiFi Connection manager with web captive portal
http://tzapu.com/esp8266-wifi-connection-manager-library-arduino-ide/
MIT License
6.53k stars 1.96k forks source link

Add Parameters other than SSID and Password #463

Open MehtaTJ opened 6 years ago

MehtaTJ commented 6 years ago

I am thankful to @tzapu for giving this tremendous work. I want take some more parameters other than SSID and password from AutoConnectAP captive page. After selecting Configure Wifi if I want to add some more parameters, can anybody help me out there? I am novice programmer in HTML and C++. So requesting you to give detailed explanation

alx-1 commented 6 years ago

I did that with this project : https://github.com/reseauducommun/cociclo/tree/master/cociclo_transpiksel_eastern_bloc/software/cociclo_transpiksel_eastern_bloc

The first file in that directory has an example of latitude, longitude and userid added to the ssid + password.

Good luck ++

tablatronix commented 6 years ago

This is built in, see the parameters example.

JhonControl commented 6 years ago

Hello, perform some tests adding parameters, maybe serve as a guide, greetings

JhonControl commented 6 years ago

http://pdacontrolen.com/wifimanager-emoncms-oem-with-esp8266-temperature-1/

jgarridc commented 6 years ago

Hi, sorry about my english... I have a problem, I added a new field in addition to pass and ssid. I am woriking with thinspeak to monitoring temperature and humity.

With de APIkey I dont have any problem, but if I want to put the channel number too, its not possible because de compilator says "*invalid conversion from 'char' to 'long unsigned int' [-fpermissive**]"

This is te code I am using:

`#include

include

include

include

include

include

include

include //librería conexión a thingspeak

include //librería esp8266

//#define DHTTYPE DHT22

define DHTTYPE DHT11

include

include

include

define DRD_TIMEOUT 100

define DRD_ADDRESS 0

DoubleResetDetector drd(DRD_TIMEOUT, DRD_ADDRESS);

LiquidCrystal_I2C lcd(0x27, 16, 2);

const char* serverThingspeak = "api.thingspeak.com"; char myChannelNumber[] = "myChannelNumber"; char myWriteAPIKey[] = "myWriteAPIKey"; const int releCaldera = 16; const int DHTpin = D4; float histeresis = 1; static unsigned long last_loop; unsigned long int anteriorRefreshDatos = 0; float temp= 0; float humi= 0; float tempDeseada = 00; int calderaHabilitada; int estadoRele = 0; int contconexion = 0;

DHT dht(DHTpin, DHTTYPE);

WiFiClient client; WiFiServer server(80);

      bool shouldSaveConfig = false;

      //callback notifying us of the need to save config
      void saveConfigCallback () {
      Serial.println("Should save config");
      shouldSaveConfig = true;
        }

void setup() {

      lcd.clear();
      lcd.begin(16,2);
      lcd.init();
      lcd.backlight();
      dht.begin();
      delay(10);

      pinMode(LED_BUILTIN, OUTPUT);
      Serial.begin(115200);
      Serial.println();

                    //clean FS, for testing
                    //SPIFFS.format();

                    //read configuration from FS json
                    Serial.println("mounting FS...");

                    if (SPIFFS.begin()) {
                    Serial.println("mounted file system");
                    if (SPIFFS.exists("/config.json")) {
                    //file exists, reading and loading
                    Serial.println("reading config file");
                    File configFile = SPIFFS.open("/config.json", "r");
                    if (configFile) {
                    Serial.println("opened config file");
                    size_t size = configFile.size();
                    // Allocate a buffer to store contents of the file.
                    std::unique_ptr<char[]> buf(new char[size]);

                    configFile.readBytes(buf.get(), size);
                    DynamicJsonBuffer jsonBuffer;
                    JsonObject& json = jsonBuffer.parseObject(buf.get());
                    json.printTo(Serial);
                    if (json.success()) {
                    Serial.println("\nparsed json");

                    strcpy(myWriteAPIKey, json["myWriteAPIKey"]);
                    strcpy(myChannelNumber, json["myChannelNumber"]);

                    } else {
                    Serial.println("failed to load json config");
                    }
                    }
                    }
                    } else {
                    Serial.println("failed to mount FS");
                    }

      if (drd.detectDoubleReset()) {
      Serial.println("Doble reset detectado");
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("INTRODUCIR");
      lcd.setCursor(0,1);
      lcd.print("USUARIO Y PASS");

      digitalWrite(LED_BUILTIN, LOW);
      WiFiManager wifiManager;
      wifiManager.resetSettings();

      delay(1000);

      } else {
      Serial.println("No se ha detectado doble reset");
      digitalWrite(LED_BUILTIN, HIGH);
      }

                WiFiManagerParameter custom_myWriteAPIKey("api", "api key", myWriteAPIKey, 17);
                WiFiManagerParameter custom_myChannelNumber("api", "api key", myChannelNumber, 6);

                WiFiManager wifiManager;

                wifiManager.setSaveConfigCallback(saveConfigCallback);
                wifiManager.addParameter(&custom_myWriteAPIKey);
                wifiManager.addParameter(&custom_myChannelNumber);

                pinMode(releCaldera, OUTPUT);
                digitalWrite(releCaldera, LOW);

                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);
                if (!wifiManager.autoConnect()) {
                Serial.println("failed to connect, we should reset as see if it connects");
                delay(3000);
                ESP.reset();
                delay(5000);
                }

//if you get here you have connected to the WiFi

      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("CONECTANDO...");
      delay(2000);

Serial.println("Conectado a la red WIFI :)"); Serial.println("local ip"); Serial.println(WiFi.localIP());

Serial.println(myWriteAPIKey);

              strcpy(myWriteAPIKey, custom_myWriteAPIKey.getValue());
              strcpy(myChannelNumber, custom_myChannelNumber.getValue());

              if (shouldSaveConfig) {
              Serial.println("saving config");
              DynamicJsonBuffer jsonBuffer;
              JsonObject& json = jsonBuffer.createObject();

              json["myWriteAPIKey"] = myWriteAPIKey;
              json["myChannelNumber"] = myWriteAPIKey; 
              File configFile = SPIFFS.open("/config.json", "w");
              if (!configFile) {
              Serial.println("failed to open config file for writing");
              }

              json.printTo(Serial);
              json.printTo(configFile);
              configFile.close();
              //end save  
               }

// Start the server

ThingSpeak.begin(client); Serial.println("Cliente thingspeak iniciado"); server.begin(); Serial.println("Server iniciado"); delay(10000); }

void refreshDatos(){

if (millis() > anteriorRefreshDatos + 20000){ anteriorRefreshDatos = millis();

float temp = dht.readTemperature(); float humi = dht.readHumidity();

if (isnan(temp) || isnan(humi)){ Serial.println("Fallo en lectura de temperatura y humedad");

return;}

if (calderaHabilitada = 1){
if (temp + histeresis >= tempDeseada && temp > 0)  digitalWrite(releCaldera, LOW);
else if (temp < tempDeseada && temp > 0) digitalWrite(releCaldera, HIGH);
else digitalWrite(releCaldera, LOW); 
     }              

  Serial.println();
  Serial.println("Leyendo datos....");

  Serial.print("Temperatura deseada: ");
  Serial.println(tempDeseada); 
  Serial.print("Temperatura: ");
  Serial.println(temp);
  Serial.print("Humedad: ");
  Serial.println(humi);

        lcd.setCursor(0,0);
        lcd.print("Temp: ");
        lcd.print(temp);
        lcd.print(" ");
        lcd.print((char)223);
        lcd.print("C");
        lcd.setCursor(0,1);
        lcd.print("Hum:  ");
        lcd.print(humi);
        lcd.print(" %");

  int estadoRele = digitalRead(releCaldera);
  if (estadoRele == LOW)
    {
    Serial.print("Estado relé caldera: ");  
    Serial.println("LOW");
        lcd.setCursor(15,0);
        lcd.print(" ");        
        } else {
    Serial.print("Estado relé caldera: ");  
    Serial.println("HIGH");
        lcd.setCursor(15,0);
        lcd.print("C");
        }      

          ThingSpeak.setField(1, temp);
          ThingSpeak.setField(2, humi); 
          ThingSpeak.setField(3, estadoRele);
          ThingSpeak.setField(4, tempDeseada);
          ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

          delay(15000);
          Serial.println("Enviando datos...");
          Serial.println();

            }
           }

void loop() {

drd.loop(); refreshDatos();

// Check if a client has connected WiFiClient client = server.available(); if (!client) { return;
}

// Read the first line of the request String req = client.readStringUntil('\r'); Serial.println(req); client.flush();

int val;

  if (req.indexOf("/tempDeseada21") != -1){
  tempDeseada = 21;
  val = 1;
  } else if (req.indexOf("/tempDeseada22") != -1){
  tempDeseada = 22;
  val = 1;
  } else if (req.indexOf("/tempDeseada23") != -1){
  tempDeseada = 23;
  val = 1;
  } else if (req.indexOf("/tempDeseada24") != -1){
  tempDeseada = 24;
  val = 1;
  } else if (req.indexOf("/tempDeseada25") != -1){
  tempDeseada = 25;
  val = 1;
  } else if (req.indexOf("/tempDeseada26") != -1){
  tempDeseada = 26;
  val = 1;
  } else if (req.indexOf("/tempDeseada00") != -1){
  tempDeseada = 00;
  val = 0;
  } else {
  Serial.println("peticion invalida");
  client.stop();
  return;      
  }

// Set GPIO2 according to the request calderaHabilitada = val; client.flush();

// Prepare the response String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n\r\nGPIO is now "; s += (val)?"high":"low"; s += "\n";

// Send the response to the client client.print(s); delay(1); client.stop(); Serial.println("Client disonnected"); } `