tzapu / WiFiManager

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

AP mode still active after setup as client. #1077

Closed VladoPortos closed 4 years ago

VladoPortos commented 4 years ago

Basic Infos

ESP-01 ( 8266 ) Module still create AP after setup and successful log in as client. I think that should not be happening. It connects as client ok, gets IP where can I access the value. but when I do scan on phone for wifi I see ESP_C59C60 ( which is not the one I named for configuration) but I can connect to it and on the ip 192.168.4.1 I get same value as on its client IP...

Hardware

WiFimanager Branch/Release:

Esp8266/Esp32:

Hardware: ESP-12e, esp01, esp25

ESP Core Version: 2.4.0, staging

Description

ESP-01 ( 8266 ) Module still create AP after setup and successful log in as client. I think that should not be happening.

Settings in IDE

Module: Generic ESP8266 Module

Additional libraries:

include // Include the SPIFFS library include //https://github.com/esp8266/Arduino include include include //https://github.com/tzapu/WiFiManager include //https://github.com/jenscski/DoubleResetDetect include include // https://github.com/bblanchon/ArduinoJson

Sketch

#include <FS.h>   // Include the SPIFFS library
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <DoubleResetDetect.h>  //https://github.com/jenscski/DoubleResetDetect
#include <OneWire.h>
#include <ArduinoJson.h>          // https://github.com/bblanchon/ArduinoJson

OneWire  ds(2);  // on pin 2 
ESP8266WebServer server(80);

char hostName[40]="TempMonitor";

// Number of seconds after reset during which a
// subseqent reset will be considered a double reset.
#define DRD_TIMEOUT 10

// RTC Memory Address for the DoubleResetDetector to use
#define DRD_ADDRESS 0x00

DoubleResetDetect drd(DRD_TIMEOUT, DRD_ADDRESS);

//flag for saving data
bool shouldSaveConfig = false;

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

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    delay(5000);

    //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(hostName, json["hostName"]);
         } else {
           Serial.println("failed to load json config");
         }
        }
     }
   } else {
     Serial.println("failed to mount FS");
   }
   //end read

    WiFiManagerParameter custom_hostname("hostName", "Hostname", hostName, 40);
    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;

     //set config save notify callback
    wifiManager.setSaveConfigCallback(saveConfigCallback);

    //add all your parameters here
    wifiManager.addParameter(&custom_hostname);

    //Set hostname
    WiFi.hostname(hostName);

    //reset saved settings if double reset

    if (drd.detect()) {
      Serial.println("Double Reset Detected");
      wifiManager.resetSettings();
    }

    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //fetches ssid and pass from eeprom 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
    wifiManager.autoConnect("TMPSensorSetup");
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();

    //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("TMPSensorSetup")) {
     Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
       ESP.reset();
      delay(5000);
    } 

    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");

    //read updated parameters
    strcpy(hostName, custom_hostname.getValue()); 

    //save the custom parameters to FS
    if (shouldSaveConfig) {
      Serial.println("saving config");
      DynamicJsonBuffer jsonBuffer;
      JsonObject& json = jsonBuffer.createObject();
      json["hostName"] = hostName;

      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

    server.on("/", handle_OnConnect);
    server.onNotFound(handle_NotFound);
    server.begin();
    Serial.println("Server started");

    // Print the IP address
    Serial.println(WiFi.localIP());
}

void loop() {

    server.handleClient();

}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

void handle_OnConnect() {

    byte i;
    byte present = 0;
    byte type_s;
    byte data[12];
    byte addr[8];
    float celsius;

    if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
    }

    Serial.print("ROM =");
    for ( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
    }

    if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
    }
    Serial.println();

    // the first ROM byte indicates which chip
    switch (addr[0]) {
    case 0x10:
    Serial.println("  Chip = DS18S20");  // or old DS1820
    type_s = 1;
    break;
    case 0x28:
    Serial.println("  Chip = DS18B20");
    type_s = 0;
    break;
    case 0x22:
    Serial.println("  Chip = DS1822");
    type_s = 0;
    break;
    default:
    Serial.println("Device is not a DS18x20 family device.");
    return;
    }

    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end

    delay(1000);     // maybe 750ms is enough, maybe not
    // we might do a ds.depower() here, but the reset will take care of it.

    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad

    Serial.print("  Data = ");
    Serial.print(present, HEX);
    Serial.print(" ");
    for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
    }
    Serial.print(" CRC=");
    Serial.print(OneWire::crc8(data, 8), HEX);
    Serial.println();

    int16_t raw = (data[1] << 8) | data[0];
    if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
    // "count remain" gives full 12 bit resolution
    raw = (raw & 0xFFF0) + 12 - data[6];
    }
    } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
    }
    celsius = (float)raw / 16.0;

    server.send(200, "text/html", SendHTML(celsius)); 
}

String SendHTML(float TemperatureWeb){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head>\n";
  // ptr +="<title>ESP8266 Global Server</title>\n";

  ptr +="</head>\n";
  ptr +="<body>\n";
  ptr +=(int)TemperatureWeb;
  ptr +="\n";
  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

Debug Messages

11:31:12.317 -> mounting FS...
11:31:12.317 -> mounted file system
11:31:12.317 -> reading config file
11:31:12.317 -> opened config file
11:31:12.317 -> {"hostName":"SenzorVlado"}
11:31:12.317 -> parsed json
11:31:12.317 -> *WM: [3] allocating params bytes: 20
11:31:12.317 -> *WM: [2] Added Parameter: hostName
11:31:12.317 -> *WM: [1] AutoConnect 
11:31:12.317 -> *WM: [1] AutoConnect: ESP Already Connected 
11:31:12.317 -> *WM: [3] STA static IP:
11:31:12.317 -> *WM: [2] setSTAConfig static ip not set, skipping 
11:31:12.317 -> *WM: [1] AutoConnect: SUCCESS 
11:31:12.350 -> *WM: [1] STA IP Address: 10.0.0.166
11:31:12.350 -> *WM: [1] AutoConnect 
11:31:12.350 -> *WM: [1] AutoConnect: ESP Already Connected 
11:31:12.350 -> *WM: [3] STA static IP:
11:31:12.350 -> *WM: [2] setSTAConfig static ip not set, skipping 
11:31:12.350 -> *WM: [1] AutoConnect: SUCCESS 
11:31:12.350 -> *WM: [1] STA IP Address: 10.0.0.166
11:31:12.350 -> connected...yeey :)
11:31:12.350 -> Server started
11:31:12.350 -> 10.0.0.166
11:31:12.350 -> *WM: [3] freeing allocated params! 
11:31:12.350 -> *WM: [3] unloading 
11:31:12.520 -> No more addresses.
11:31:12.520 -> 
11:31:54.197 -> No more addresses.
11:31:54.197 -> 
tablatronix commented 4 years ago

WiFi.mode(WIFI_STA); in your sketch the esp auto starts ap if its saved

VladoPortos commented 4 years ago

WiFi.mode(WIFI_STA); in your sketch the esp auto starts ap if its saved

Thanks @tablatronix seems like this is the answer, but where in setup exactly to put it ?

tablatronix commented 4 years ago

In setup right after your start serial probably. You also only have to do it once, so if you have code that runs once you can do it there, it is saved by esp

alirezaimi commented 4 years ago

hi, I can't understand what the answer is ?! I have this problem with esp-8266 12e/f , is this is an option ?

tablatronix commented 4 years ago

Yes , the esp by default start an ap with the esp id name, you need to turn off WIFI_AP mode

cacs200281 commented 4 years ago

I had the same issue and just solved, in my case, following that instructions from @tablatronix . Thanks a lot!