ESP32 + wifi manager + winsock client + fix ip NOT WORKING

Hi to all,
have a small project reading water flow sensor and send data on one hour base to remote winsock server. I add wifi manager and elegant OTA as well as web server to ESP32. All works well until I add FIX IP to wifi manager. After that winsock client could not connect to server. Test program is herewith bellow. I appreciate any help.

/*
primjer config.json
{
  "lokacija_uredjaja": "xxxxxxxxtesica",
  "broj_uredjaja": "1",
  "server_na_koji_se_spaja": "jaxxxxxxxxs.net",
  "password_za_server": "xxxxxxxdaj1!*",
  "ip": "192.168.1.12",
  "gateway": "192.168.1.1",
  "subnet": "255.255.255.0"
}
*/

// Import required libraries
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include "SPIFFS.h"
#include <SPI.h>
#include <Wire.h>
#include <ESPmDNS.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncWiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

#include <AsyncElegantOTA.h>
//#include <WebSocketClient.h>


// Replace with your network credentials

const char* ssid = "xxxx";
const char* password = "xxxxxxxxx";

String remDev = "";
String serPsswd = "";
//String remDev = "xxxxxxxxatesica-1";
//String serPsswd = "xxxxxxxxrdaj1!*";
//const char *ssid = "kuci";     // replace with your wifi ssid and wpa2 key
//const char *pass = "kucikuci01";
//const char *server1 = "jadrand.ddns.net";
//char host[] = "jadrand.ddns.net";
#define LED_BUILTIN 16
#define SENSOR  2

long currentMillis = 0;
long previousMillis = 0;
int interval = 1000;
boolean ledState = LOW;
float calibrationFactor = 4.5;
volatile byte pulseCount;
byte pulse1Sec = 0;
float flowRate;
unsigned long flowMilliLitres;
unsigned int totalMilliLitres;
float flowLitres;
float totalLitres;
int pressCO2;


bool shouldSaveConfig = false; //manipulira se iz WiFi Mangera
char lokacija_uredjaja[20];
char broj_uredjaja[2];
char server_na_koji_se_spaja[20];
char password_za_server[20];
//default custom static IP
char static_ip[16] = "192.168.1.22";
char static_gw[16] = "192.168.1.1";
char static_sn[16] = "255.255.255.0";


// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
DNSServer dns;


// Set LED GPIO
const int ledPin = 13;// croduino ESP32 led IO
// Stores LED state
//String ledState;


void IRAM_ATTR pulseCounter()
{
  pulseCount++;
}




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


String processor(const String& var) {
  Serial.print("Processor: ");Serial.print("VAR ");Serial.println(var);
 
  if (var == "STANJE") { // umjesto %STANJE% na index.html bit ce broj litara. 
                         //za svaku varijablu koja pocinje sa % treba ovdje napisati dio program akoji ce ju promijeniti
    String ukupno_litara="10";
    return ukupno_litara;
  }
}//end processor





bool loadConfig() {
  Serial.println("loadconfig:");
  Serial.println(SPIFFS.exists("/index.html"));// ispisuje 1 ako file postoji ili 0 ako ne postoji
  Serial.println(SPIFFS.exists("/style.css"));// ispisuje 1 ako file postoji ili 0 ako ne postoji
  
  
  
  File configFile = SPIFFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }
  Serial.println("loadconfig: config file exist");
  
  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);

  // We don't use String here because ArduinoJson library requires the input
  // buffer to be mutable. If you don't use ArduinoJson, you may as well
  // use configFile.readString instead.
  configFile.readBytes(buf.get(), size);
  DynamicJsonBuffer jsonBuffer;
  //StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());

  if (!json.success()) {
    Serial.println("Failed to parse config file");
    return false;
  }
  else {
  
    strcpy(lokacija_uredjaja, json["lokacija_uredjaja"]);
    strcpy(broj_uredjaja, json["broj_uredjaja"]);
    strcpy(server_na_koji_se_spaja, json["server_na_koji_se_spaja"]);
    strcpy(password_za_server, json["password_za_server"]);

    Serial.println("procitao sam config file");
    Serial.print("lokacija_uredjaja= "); Serial.println(lokacija_uredjaja);
    Serial.print("broj_uredjaja= "); Serial.println(broj_uredjaja);
    Serial.print("server_na_koji_se_spaja= "); Serial.println(server_na_koji_se_spaja);
    Serial.print("password_za_server= "); Serial.println(password_za_server);
    
    
    if(json["ip"]) {
            Serial.println("setting custom ip from config");
            strcpy(static_ip, json["ip"]);
            strcpy(static_gw, json["gateway"]);
            strcpy(static_sn, json["subnet"]);
            Serial.print("static_ip= ");Serial.println(static_ip);
            Serial.print("static_gw= ");Serial.println(static_gw);
            Serial.print("static_sn= ");Serial.println(static_sn);
   }
  }
}//end loadconfiguration


bool saveConfiguration() {
  //*************************************************************************
  //save the custom parameters to FS

  Serial.println("saveConfiguration:");
  //********************************************
  DynamicJsonBuffer jsonBuffer;
  //********************************************
  //StaticJsonBuffer<200> jsonBuffer;

  JsonObject& json = jsonBuffer.createObject();

  Serial.print("lokacija_uredjaja= "); Serial.println(lokacija_uredjaja);
  Serial.print("broj_uredjaja= "); Serial.println(broj_uredjaja);
  Serial.print("server_na_koji_se_spaja= "); Serial.println(server_na_koji_se_spaja);
  Serial.print("password_za_server= "); Serial.println(password_za_server);

  json["lokacija_uredjaja"] = lokacija_uredjaja;
  json["broj_uredjaja"] = broj_uredjaja;
  json["server_na_koji_se_spaja"] = server_na_koji_se_spaja;
  json["password_za_server"] = password_za_server;
  json["ip"] = WiFi.localIP().toString();
  json["gateway"] = WiFi.gatewayIP().toString();
  json["subnet"] = WiFi.subnetMask().toString();

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

  Serial.println("saveconfig: upisujem u config.json");
  json.prettyPrintTo(Serial);
  json.printTo(configFile);
  configFile.close();
  Serial.println("");
  Serial.println("saveconfig: zatvorio config.json");
  return true;

}//end save


void setup(){
  // Serial port for debugging purposes

 Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(SENSOR, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin,LOW);
 
  pulseCount = 0;
  flowRate = 0.0;
  pressCO2 = 0;
  flowMilliLitres = 0;
  totalMilliLitres = 0;
  previousMillis = 0;

  attachInterrupt(digitalPinToInterrupt(SENSOR), pulseCounter, FALLING);

  // Initialize SPIFFS
  
  if (SPIFFS.begin(true)) {
    Serial.println("mounted file system");


    loadConfig(); // procitaj config.json

  } else {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
  //end read  
  

  // 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

  //**********************************************************************************************************************
  //                                                       id,     name,                     placeholder,    length
  AsyncWiFiManagerParameter custom_server_na_koji_se_spaja("server_na_koji_se_spaja", "server na koji se spaja", server_na_koji_se_spaja, 20);
  AsyncWiFiManagerParameter custom_password_za_server("password_za_server", "password za server", password_za_server, 16);
  AsyncWiFiManagerParameter custom_lokacija_uredjaja("lokacija_uredjaja", "adresa uredjaja", lokacija_uredjaja, 20);
  AsyncWiFiManagerParameter custom_broj_uredjaja("broj_uredjaja", "broj uredjaja", broj_uredjaja, 2);
  //**********************************************************************************************************************

   //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  AsyncWiFiManager wifiManager(&server, &dns);

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

//--------------------kad ovoga nema onda se spaja na remote server ali nema fixIP-------------------------------------------
/* //when this is included in program program stop to connect to client
 //set static ip
  IPAddress _ip,_gw,_sn;
  _ip.fromString(static_ip);
  _gw.fromString(static_gw);
  _sn.fromString(static_sn);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);

*/
//---------------------------------------------------------------------------------------------------------------------------  
   //************************************************************
  wifiManager.addParameter(&custom_server_na_koji_se_spaja);
  wifiManager.addParameter(&custom_password_za_server);
  wifiManager.addParameter(&custom_lokacija_uredjaja);
  wifiManager.addParameter(&custom_broj_uredjaja);
  //************************************************************
  
  
  //u slucaju da treba brisati podatke o wifi mrezi i passwordu upisanim u flash ESP32 
  //treba startati resetSettings jednom i opet maskirati 
  //tada se starta WiFi Manager
  //reset settings - for testing
   //wifiManager.resetSettings();

 //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

 //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("VODA","password")) {              // (!wifiManager.autoConnect("AutoConnectAP", "password")) {
                               Serial.println("failed to connect and hit timeout");
                               delay(3000);
                               //reset and try again, or maybe put it to deep sleep
                               //ESP.reset(); - work on ESP8266
                               ESP.restart();
                               delay(5000);
 }


//***************************************************************ODAVDE POCINJE MOJ WEB AKO JE SPOJEN*******************************
      //if you get here you have connected to the WiFi
       Serial.println("connected to choosed WiFi ;)");

       //kao znak da WiFi radi na mrezi na koju je odabran svijetli LED na IO13
       digitalWrite(ledPin,HIGH);

//**********************************************************************************************************************************
      Serial.print("WiFi Connected to: ");
      Serial.println(WiFi.SSID());

      Serial.print("WiFi Signal strength: ");
      Serial.println(WiFi.RSSI());

      Serial.print("WiFi connected with IP: ");
      Serial.println(WiFi.localIP());
      //***********************************************************************************************************************************************

//read updated parameters
      
      //*****************************************************************
      Serial.println("SETUP: uzimanje vrijednosti iz upisanog podatka sa wifi manager stranice ");
      strcpy(lokacija_uredjaja,custom_lokacija_uredjaja.getValue());
      strcpy(broj_uredjaja,custom_broj_uredjaja.getValue());
      strcpy(server_na_koji_se_spaja,custom_server_na_koji_se_spaja.getValue());
      strcpy(password_za_server,custom_password_za_server.getValue());
      
      Serial.println("SETUP: kopirani podaci sa web portala u varijable: ");
      Serial.print("lokacija_uredjaja = ");Serial.println(lokacija_uredjaja);
      Serial.print("broj_uredjaja = ");Serial.println(broj_uredjaja);
      Serial.print("server_na_koji_se_spaja = ");Serial.println(server_na_koji_se_spaja);
      Serial.print("password_za_server = ");Serial.println(password_za_server);

   //save the custom parameters to FS
   if (shouldSaveConfig) {

   //*******************************************************************
   saveConfiguration();
   //*******************************************************************

   }

   // Print ESP32 Local IP Address
   Serial.println("local ip");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.gatewayIP());
  Serial.println(WiFi.subnetMask());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", String(), false, processor);
  });
  
  // Route to load style.css file
  server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send(SPIFFS, "/style.css", "text/css");
  });

 char DNS[10];
        
       DNS[0]='\0';
       strcat(DNS,"VODA-");
       strcat(DNS,broj_uredjaja);
       Serial.print("DNS= ");Serial.println(DNS);
        
 if (!MDNS.begin (DNS)){                        //("VODA")) {             // Start the mDNS responder for esp8266.local
    Serial.println("Error setting up MDNS responder!");
  }
    Serial.println("mDNS responder started");
 

    AsyncElegantOTA.begin(&server);    // Start ElegantOTA

  // Start server
  server.begin();
 
}
 
void loop(){
 //
  WiFiClient client;
  currentMillis = millis();
  L1:  if (currentMillis - previousMillis > interval)
  {

  pulse1Sec = pulseCount;
  pulseCount = 0;

  // Because this loop may not complete in exactly 1 second intervals we calculate
  // the number of milliseconds that have passed since the last execution and use
  // that to scale the output. We also apply the calibrationFactor to scale the output
  // based on the number of pulses per second per units of measure (litres/minute in
  // this case) coming from the sensor.
  flowRate = ((1000.0 / (millis() - previousMillis)) * pulse1Sec) / calibrationFactor;
  previousMillis = millis();

  // Divide the flow rate in litres/minute by 60 to determine how many litres have
  // passed through the sensor in this 1 second interval, then multiply by 1000 to
  // convert to millilitres.
  flowMilliLitres = (flowRate / 60) * 1000;
  flowLitres = (flowRate / 60);

  // Add the millilitres passed in this second to the cumulative total
  totalMilliLitres += flowMilliLitres;
  totalLitres += flowLitres;

  // Print the flow rate for this second in litres / minute
  Serial.print("Flow rate: ");
  Serial.print(float(flowRate));  // Print the integer part of the variable
  Serial.print("L / min");
  Serial.print("\t");       // Print tab space

  // Print the cumulative total of litres flowed since starting
  Serial.print("Output Liquid Quantity: ");
  Serial.print(totalMilliLitres);
  Serial.print("mL / ");
  Serial.print(totalLitres);
  Serial.println("L");

  int i = 0;
  Serial.print("server_na_koji_se_spaja= ");Serial.println(server_na_koji_se_spaja);
 //(client.connect('jadrand.ddns.net' ,27015))
  L:  if (client.connect(server_na_koji_se_spaja, 27015)){
  //lokacija i broj uredjaja u jedan string za slanje
  remDev="";
  remDev+=lokacija_uredjaja;
  remDev+="-";
  remDev+=broj_uredjaja;
  serPsswd=password_za_server;
 Serial.print("ispis remDev i serPsswd");
 Serial.print("remDev=  ");Serial.println(remDev);
 Serial.print("serPsswd= "); Serial.println(serPsswd);
  //---------------------------------
  String postStr = remDev;
  postStr += "*";
  postStr += String(flowRate);
  postStr += "*";
  postStr += String(totalLitres);
  postStr += "*";
  postStr += String(pressCO2);
  postStr += "#";
  postStr += postStr;
  postStr = serPsswd + postStr;
  postStr = postStr + "\0";
  
  Serial.print("postStr = ");Serial.println(postStr);
      char c; int j = 0;
      while ((c = postStr.charAt(j)) != '\0' ){
      if ((j/2*2) == j) postStr.setCharAt(j, c + 3);
      else postStr.setCharAt(j, c + 5);
      j++;
    }
   Serial.print("postStr_nakon_kodiranja = ");Serial.println(postStr);
      client.print(postStr);
     }
       else {
       if (i < 3){
       i++;
       Serial.print("Not connected to server !\n");
       delay(5000);
       goto L;
       }
      }
 }//L:
       else goto L1;

       client.stop();
       delay(1800000);
       //delay(3600000);
}//end loop

You must not use host names if you don't set a DNS server. If you don't use a static configuration the ESP32 will get the DNS server from the DHCP configuration. If you provide a static setup you either have to provide a DNS server IP or use only IPs in your network calls.

Very easy to fix- don't use static IP. How do you know that the DHCP server didn't assign 192.168.1.22 to another device?

The best way is to let the DHCP server in your router and in the router, set the IP subscription to permanent. This has the same effect as fixed IP addresses without all of the headaches.

I know because DHCP is set for address above 100.
I solve a problem with add config for dns1 and dns2 in IP config, so now everything is working well
this can be closed!

I see now that pylon suggest same thing, Thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.