Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By sleberboti
#68957 Dear All,

I am working on websocket powered webpage running on a NodeMCU. There is a main issue which bothers me. Whenever I connected to a network it works fine, if i disconnect from it and then re-connect it still okay. But if the network becomes unavailable and gone missing I can't connect to the ESP anymore.
Are there any ideas, how I can handle this situation? I attached my code

Also, I have another issue, which is when I connect to a network or reconnect to it or disconnect from it, I always need to refresh my webpage. Is it possible to refresh automaticly when it happens?

Thanks a lot



Code: Select all#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <DNSServer.h>
#include <Wire.h>       //I2C library
#include <RtcDS3231.h>  //RTC library

WebSocketsServer webSocket = WebSocketsServer(81);
ESP8266WebServer server(80);
WiFiManager wifiManager;
DNSServer dnsServer;
RtcDS3231<TwoWire> rtcObject(Wire);

IPAddress apIP(192, 168, 1, 1);


String serialText;

byte ledPin = D0;
byte secPin=D3;                               // second counter interrupt pin
byte sensorPin = A0;                          // IR sensor pin

int sensorValue=0;

int secCount=0;
int startTime;
int loopTime;
double moveTime;

const byte DNS_PORT = 53;
const char* ssidESP = "ESP";
const char* passwordESP = "szipusalfonz";
String webSite, javaScript, JSONtxt;
boolean LEDonoff = true;
int counter = 0;
char* ssidNET="ssidNET";
char* passwordNET="passwordNET";
String randszoveg="ESP homepage";

int ntpYear, ntpMonth, ntpDay, ntpHour, ntpMinute, ntpSecond;
int rtcYear, rtcMonth, rtcDay, rtcHour, rtcMinute, rtcSecond;
int clockEnabled=0;

void ICACHE_RAM_ATTR secondReceive() {
  secCount=1;
}

void buildWebsite() {
  buildJavascript();
  webSite = "<!DOCTYPE HTML><HTML>\n";
  webSite += "<META name='viewport' content='width=device-width, initial-scale=1'>\n";
   
  webSite += javaScript; 
 
  webSite += "<BODY>\n";
  webSite += "<BR><BR>Randomszoveg = <A ID='randszoveg'></A><BR><BR>\n";
 
  webSite += "<BUTTON ID='button' ONCLICK='button()' STYLE='width:200px;height:150px'></BUTTON>";
  webSite += "<BUTTON ID='wifiManager' ONCLICK='wifiManager()' STYLE='width:200px;height:150px'></BUTTON>";
  webSite += "<BUTTON ID='discWifi' ONCLICK='discWifi()' STYLE='width:200px;height:150px'></BUTTON>";
  webSite += "<INPUT ID='searchTxt' type='text' ONCHANGE='textbox()'/><BR><BR><BR>";
  webSite += "<INPUT ID='networkName' type='text' placeholder='Input the network name' ONCHANGE='network()'/><BR>";
  webSite += "<INPUT ID='networkPw' type='password' placeholder='Input the network password' ONCHANGE='pw()'/><BR><BR><BR>"; 
 
  webSite += javaScript;
  webSite += "</BODY>\n";
  webSite += "</HTML>\n";
}

void buildJavascript() {
  javaScript = "<SCRIPT>\n";
 
  javaScript += "InitWebSocket();\n"; 
  javaScript += "function InitWebSocket(){\n";
  javaScript += "  websock=new WebSocket('ws://'+window.location.hostname+':81/');\n";
  javaScript += "  websock.onmessage=function(evt){\n";
  javaScript += "    JSONobj=JSON.parse(evt.data);\n";
   
  javaScript += "    document.getElementById('randszoveg').innerHTML=JSONobj.randszoveg;\n";
  javaScript += "    document.getElementById('button').innerHTML=JSONobj.LEDonoff;\n";
  javaScript += "    document.getElementById('wifiManager').innerHTML=JSONobj.wifiManager;\n";
  javaScript += "    document.getElementById('discWifi').innerHTML=JSONobj.diskWifi;\n";
  javaScript += "    document.getElementById('searchTxt').innerHTML=JSONobj.searchTxt;\n";
  javaScript += "    document.getElementById('networkName').innerHTML=JSONobj.networkName;\n";
  javaScript += "    document.getElementById('networkPw').innerHTML=JSONobj.networkPw;\n";
 
  javaScript += "  }\n";
  javaScript += "}\n";
 

  javaScript += "function button(){\n";
  javaScript += "  btn='LEDonoff=LED = ON';\n";
  javaScript += "  if(document.getElementById('button').innerHTML==='LED = ON')btn='LEDonoff=LED = OFF';\n";
  javaScript += "  websock.send(btn);\n";
  javaScript += "}\n";

  javaScript += "function wifiManager(){\n";
  javaScript += "  btnWifi='wifiManager';\n";
  javaScript += "  websock.send(btnWifi);\n";
  javaScript += "}\n";
 
  javaScript += "function discWifi(){\n";
  javaScript += "  btndiscWifi='discWifi';\n";
  javaScript += "  websock.send(btndiscWifi);\n";
  javaScript += "}\n";


  javaScript += "function textbox(){\n";
  javaScript += "  txt=document.getElementById('searchTxt').value;\n";
  javaScript += "  websock.send('searchTxt='+txt);\n";
  javaScript += "}\n";

  javaScript += "function network(){\n";
  javaScript += "  name=document.getElementById('networkName').value;\n";
  javaScript += "  websock.send('networkName='+name);\n";
  javaScript += "}\n";

  javaScript += "function pw(){\n";
  javaScript += "  pass=document.getElementById('networkPw').value;\n";
  javaScript += "  websock.send('networkPw='+pass);\n";
  javaScript += "}\n";
 
 
  javaScript += "</SCRIPT>\n";
}

void handleWebsite() {
  buildWebsite();
  server.send(200, "text/html", webSite);
}

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

  String payloadString = (const char *)payload;
  if (type == WStype_TEXT) {
    byte separator = payloadString.indexOf('=');
    String var = payloadString.substring(0, separator);
    String val = payloadString.substring(separator + 1);

    if (var == "LEDonoff") {
      LEDonoff = false;
      if (val == "LED = ON")LEDonoff = true;
      digitalWrite(ledPin, HIGH);     
      delay(500);
      digitalWrite(ledPin, LOW);
      Serial.println("LEDSWITCH");
    }

    if (var == "discWifi") {

      WiFi.disconnect();
      WiFi.mode(WIFI_OFF);
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
      WiFi.softAP(ssidESP, passwordESP);
      Serial.print("Connected to ");
      Serial.println(ssidESP);
      Serial.print("Access Point IP address = ");
      Serial.println(WiFi.softAPIP());
      dnsServer.start(DNS_PORT, "*", apIP);
      delay(1000);
    }


    if (var == "wifiManager") {

      WiFi.disconnect();
     
      WiFi.mode(WIFI_AP_STA);     

      int loopstartTime=millis();
      int loopcurrentTime;
     
      Serial.println("");
      Serial.print("Connencting to network: ");
      Serial.print(ssidNET);
      WiFi.begin(ssidNET, passwordNET);
      wifi_station_set_auto_connect(true);
      while ((!(WiFi.status() == WL_CONNECTED))) {
      loopcurrentTime=millis();
      if((loopcurrentTime-loopstartTime)>15000)break;
      delay(500);
      Serial.print(".");
      }

      if((WiFi.status() == WL_CONNECTED)){
        Serial.println("Connected");
        Serial.print("Station IP address = ");
        Serial.println((WiFi.localIP()));         
      }     
      else{
        Serial.println("Failed attempt to connect! :(");
        WiFi.disconnect();
        WiFi.mode(WIFI_OFF);   
        WiFi.mode(WIFI_AP);       
      } 

      WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
      WiFi.softAP(ssidESP, passwordESP);
      Serial.print("Connected to ");
      Serial.println(ssidESP);
      Serial.print("Access Point IP address = ");
      Serial.println(WiFi.softAPIP());
      dnsServer.start(DNS_PORT, "*", apIP);
   
      configRTC(ntpYear, ntpMonth, ntpDay, ntpHour,ntpMinute, ntpSecond);
      delay(1000);   
    }
   
   

    if (var == "networkName") {
      Serial.print("Typed network name: ");
      val.toCharArray(ssidNET, val.length()+1);
      Serial.println(ssidNET);
    }
   
    if (var == "networkPw") {
      Serial.print("Typed password: ");
      val.toCharArray(passwordNET, val.length()+1);
      Serial.println(passwordNET);
    }
   
   
  }
}
void setup() {

 
  delay(500);
  Serial.begin(9600);
  delay(500);
  ESP.eraseConfig();
 
  //Init pins
  pinMode(sensorPin, INPUT);
  pinMode(secPin, INPUT);
  pinMode(ledPin, OUTPUT);
     
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssidESP, passwordESP);
  Serial.print("Connected to ");
  Serial.println(ssidESP);
  Serial.print("Access Point IP address = ");
  Serial.println(WiFi.softAPIP());
  Serial.println("");

  // Init RTC second and voltage drop interrupts
  rtcObject.Begin(); 
  attachInterrupt(digitalPinToInterrupt(secPin), secondReceive, FALLING);
  rtcObject.SetSquareWavePin(DS3231SquareWavePin_ModeClock);
  rtcObject.SetSquareWavePinClockFrequency(DS3231SquareWaveClock_1Hz); //SQW set to 1Hz
  configRTC(ntpYear, ntpMonth, ntpDay,ntpHour, ntpMinute, ntpSecond);
  RtcDateTime currentTime = RtcDateTime(ntpYear, ntpMonth, ntpDay, ntpHour, ntpMinute, ntpSecond);
  rtcObject.SetDateTime(currentTime);
 
 

  // init website, dnsserver, websocket
  handleWebsite();
  dnsServer.start(DNS_PORT, "*", apIP);
  server.on("/", handleWebsite);
  server.on("/generate_204", handleWebsite);
  server.on("/fwlink", handleWebsite);
  server.begin();
  server.onNotFound([]() {
    server.send(200, "text/html", webSite);
  });
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}



void loop() {

  dnsServer.processNextRequest();
  server.handleClient();
  webSocket.loop();

  // communicating w/ webpage through JSON
  JSONtxt = "{\"randszoveg\":\"" + serialText + "\"," +
            "\"requestNTP\":\"" + "Get NTP data." +"<br /><br />"+"Current RT data: "+getRTC() + "\"," +
            "\"wifiManager\":\"" +"Wifi Manager "+"<br /><br />"+ "\"}";;
  webSocket.broadcastTXT(JSONtxt);
 
  if(secCount==1 ){
   
   startTime=millis();
   getRtcTime();
   sensorValue=analogRead(sensorPin);
/// everything else
   loopTime=millis();

   moveTime=(loopTime-startTime);
   dataWrite();
   
  } 
  secCount=0;
}

void configRTC (int year, int month, int day, int hour, int minute, int second){
  rtcObject.Begin();
  RtcDateTime currentTime = RtcDateTime(year, month, day, hour, minute, second); //define date and time object
  rtcObject.SetDateTime(currentTime); //configure the RTC with object
  Serial.println("Configured RTC");
}


String getRTC(){
 
    RtcDateTime currentTime = rtcObject.GetDateTime();
    rtcYear=currentTime.Year();
    rtcMonth=currentTime.Month();
    rtcDay=currentTime.Day();
    rtcHour=currentTime.Hour();
    rtcMinute=currentTime.Minute();
    rtcSecond=currentTime.Second(); 
    return String(rtcYear)+"/"+String(rtcMonth)+"/"+String(rtcDay)+" "+String(rtcHour)+":"+String(rtcMinute)+":"+String(rtcSecond);

}

void dataWrite(){
  Serial.print("rtc Min:Sec: ");
  Serial.print(rtcMinute);
  Serial.print(":"); 
  Serial.print(rtcSecond); 
  Serial.print("  SensorValue: ");
  Serial.print(sensorValue); 
  Serial.print("   LoopTime: ");
  Serial.println(moveTime);

  serialText=" rtc Min:Sec: "+String(rtcMinute)+":"+String(rtcSecond)+"  SensorValue: "+String(sensorValue)+"   LoopTime: "+String(moveTime);
}


void getRtcTime(){
 
    RtcDateTime currentTime = rtcObject.GetDateTime();
    rtcHour=currentTime.Hour();
    rtcMinute=currentTime.Minute();
    rtcSecond=currentTime.Second();   
}