mrWheel / DSMRloggerAPI

Firmware for the DSMR-logger using only API call's
MIT License
18 stars 25 forks source link

Static ip #72

Closed arjenv closed 2 months ago

arjenv commented 2 months ago

Ik ben nu al een uurtje aan het zoeken hoe ik in deze software een static ip kan instellen. De software draait, ik heb de wifimanager kunnen openen en ingesteld op mijn netwerk, maar krijg een DHCP aanwijzing. Elke keer als mijn modem reset wordt dat anders en ik wil de boel via JSON kunnen uitlezen, dus een vast IP address is een noodzaak.

Ik gebruik de ESP8266 versie. Wellicht outdated maar goed genoeg voor mijn applicatie.

Vast al ergens behandeld maar ik kan het dus niet vinden...

Bedankt voor great software!

mrWheel commented 2 months ago

@arjenv , Het is mogelijk om een vast IP adres in te stellen, maar niet via de GUI. Het moet in de firmware gebeuren, vlak voor WiFi wordt aangezet.

In networkStuff.ino in de functie startWiFi()

void startWiFi(const char *hostname, int timeOut, bool eraseCredentials)

Met google zoeken op ‘static IP esp8266’

arjenv commented 1 month ago

Het is mij gelukt een static ip in te stellen. Dit kan via de wifimanager. Zonder het dus te 'hardcoderen'. Voor hen met interesse kan ik het publiceren.

jplatier commented 1 month ago

Ik heb hetzelfde probleem. Als je de tip wil publiceren dan graag.

arjenv commented 1 month ago

In DSMRloggerapi.ino:

Ik heb het optioneel gemaakt met een #define statement net als andere opties (ADDSTATICIP)

`/**** compiler options ****/

define USE_LITTLEFS // if not #defined: use SPIFFS

define USE_UPDATE_SERVER // define if there is enough memory and updateServer to be used

define USE_MQTT // define if you want to use MQTT (configure through webinterface)

//#define USE_MINDERGAS // define if you want to update mindergas (configure through webinterface)

// #define USE_SYSLOGGER // define if you want to use the sysLog library for debugging

// #define SHOW_PASSWRDS // well .. show the PSK key and MQTT password, what else?

// #define HAS_NO_SLIMMEMETER // define for testing only!

define ADDSTATICIP

/**** don't change anything below this comment **/`

Net voor '//------ read status file for last Timestamp --------------------'

  // Added for static IP july 2024 ARV
#if defined ADDSTATICIP  
  setupStaticIP();
#endif  
  // end Added

  //------ read status file for last Timestamp --------------------

Vervang heel networkstuff.h met het volgende:

`/*


Program : networkStuff.h, part of DSMRloggerAPI Version : v3.0 Copyright (c) 2020 .. 2022 Willem Aandewiel TERMS OF USE: MIT License. See bottom of file.


*/

include //ESP8266 Core WiFi Library

include // Version 1.0.0 - part of ESP8266 Core https://github.com/esp8266/Arduino

include // part of ESP8266 Core https://github.com/esp8266/Arduino

include // part of ESP8266 Core https://github.com/esp8266/Arduino

ifdef USE_UPDATE_SERVER

//#include "ESP8266HTTPUpdateServer.h"

include "ModUpdateServer.h" // https://github.com/mrWheel/ModUpdateServer

include "UpdateServerHtml.h"

endif

include // version 0.15.0 - https://github.com/tzapu/WiFiManager

// included in main program: #include // Version 0.0.1 - https://github.com/jandrassy/TelnetStream

include // part of ESP8266 Core https://github.com/esp8266/Arduino

ESP8266WebServer httpServer (80);

ifdef USE_UPDATE_SERVER

ESP8266HTTPUpdateServer httpUpdater(true);

endif

static FSInfo SPIFFSinfo; bool FSYSmounted; bool isConnected = false;

// ADDED july 2024 for static IP ARV

if defined ADDSTATICIP

include //https://github.com/bblanchon/ArduinoJson

//default custom static IP char static_ip[16] = "192.168.1.50"; char static_gw[16] = "192.168.1.254"; char static_sn[16] = "255.255.255.0";

//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 setupStaticIP(void) { if (LittleFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = LittleFS.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); JsonDocument json; auto deserializeError = deserializeJson(json, buf.get()); serializeJson(json, Serial); if ( ! deserializeError ) { Serial.println("\nparsed json");

    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.println(static_ip);
    } else {
      Serial.println("no custom ip in config");
    }
  } else {
    Serial.println("failed to load json config");
  }
}

} Serial.println(static_ip); }

endif

// End Added

//gets called when WiFiManager enters configuration mode //=========================================================================================== void configModeCallback (WiFiManager *myWiFiManager) { DebugTln(F("Entered config mode\r")); DebugTln(WiFi.softAPIP().toString()); //if you used auto generated SSID, print it DebugTln(myWiFiManager->getConfigPortalSSID()); if (settingOledType > 0) { oled_Clear(); oled_Print_Msg(0, "", 0); oled_Print_Msg(1, "AP mode active", 0); oled_Print_Msg(2, "Connect to:", 0); oled_Print_Msg(3, myWiFiManager->getConfigPortalSSID(), 0); }

} // configModeCallback()

//=========================================================================================== void startWiFi(const char *hostname, int timeOut) { WiFiManager manageWiFi;

// Added July 2024 static IP ARV

if defined ADDSTATICIP

//set config save notify callback

manageWiFi.setSaveConfigCallback(saveConfigCallback); //set static ip IPAddress _ip, _gw, _sn; _ip.fromString(static_ip); _gw.fromString(static_gw); _sn.fromString(static_sn);

manageWiFi.setSTAStaticIPConfig(_ip, _gw, _sn, _gw); // added 4th argument as DNS

endif

// end Added uint32_t lTime = millis(); String thisAP = String(hostname) + "-" + WiFi.macAddress();

DebugTln("start ...");

WiFi.mode(WIFI_STA);

manageWiFi.setDebugOutput(true);

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

//--- sets timeout until configuration portal gets turned off //--- useful to make it all retry or go to sleep in seconds //manageWiFi.setTimeout(240); // 4 minuten manageWiFi.setTimeout(timeOut); // in seconden ...

//--- fetches ssid and pass and tries to connect //--- if it does not connect it starts an access point with the specified name //--- here "DSMR-WS-" //--- and goes into a blocking loop awaiting configuration if (!manageWiFi.autoConnect(thisAP.c_str())) { DebugTln(F("failed to connect and hit timeout")); if (settingOledType > 0) { oled_Clear(); oled_Print_Msg(0, "", 0); oled_Print_Msg(1, "Failed to connect", 0); oled_Print_Msg(2, "and hit TimeOut", 0); oled_Print_Msg(3, " NO WIFI ", 0); }

DebugTf(" took [%d] milli-seconds ==> ERROR!\r\n", (millis() - lTime));
//return;

} else { DebugTf("Connected with IP-address [%s]\r\n\r\n", WiFi.localIP().toString().c_str());

// Added ARV

if defined ADDSTATICIP

//save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); JsonDocument json;

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

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

serializeJson(json, Serial);
serializeJson(json, configFile);
configFile.close();
//end save

} Serial.println("local ip"); Serial.println(WiFi.localIP()); Serial.println(WiFi.gatewayIP()); Serial.println(WiFi.subnetMask());

endif

// end Added

} if (settingOledType > 0) { oled_Clear(); }

if (WiFi.softAPdisconnect(true)) Serial.println("WiFi Access Point disconnected and closed"); else Serial.println("Hm.. could not disconnect WiFi Access Point! (maybe there was none?)");

ifdef USE_UPDATE_SERVER

httpUpdater.setup(&httpServer); httpUpdater.setIndexPage(UpdateServerIndex); httpUpdater.setSuccessPage(UpdateServerSuccess);

endif

DebugTf(" took [%d] milli-seconds => OK!\r\n", (millis() - lTime));

} // startWiFi()

//=========================================================================================== void startTelnet() { TelnetStream.begin(); DebugTln(F("\nTelnet server started ..")); TelnetStream.flush();

} // startTelnet()

//======================================================================= void startMDNS(const char *Hostname) { DebugTf("[1] mDNS setup as [%s.local]\r\n", Hostname); if (MDNS.begin(Hostname)) // Start the mDNS responder for Hostname.local { DebugTf("[2] mDNS responder started as [%s.local]\r\n", Hostname); } else { DebugTln(F("[3] Error setting up MDNS responder!\r\n")); } MDNS.addService("http", "tcp", 80);

} // startMDNS()

/*** *

De opmaak laat wat te wensen over in dit antwoord, ik heb alle code in "code" gezet, maar dat werkt niet altijd even goed...

Compileren en opladen naar de ESP8266. Vergeet niet de optie aan te zetten 'alles wissen' (eenmalig). Dan inloggen via Wifimanager en als het goed is krijg je nu de optie IP nummers aan te maken. Deze worden opgeslagen op de ESP.

Laat weten of het werkt...