How to keep active with web browser ?

hello friends,
my english is not so good hope you guys undersatnd me, i,m working with esp8266 board. this is my simple learning base led blinking speed controlling code from android phone . code is working fine but problem is whenever mobile phone display goes Off after 30 seconds. and after 45 or 50 seconds i turn mobile screen back On. the web page stop sending commands . and wont work unitil i reload or refresh browser page. is there any way to stay connected or active even if android phone display went off and after phone display on, it work without refreshing or reloading web page ? here is the code, and thanks in advance.

#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
const char* ssid = "ledbink";
const char* password = "";
int LED = 16;
int websockMillis = 50;
int sliderVal = 60;
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(88);
String webSite, JSONtxt;
unsigned long wait001 = 0UL, wait000 = 0UL;
int LEDmillis = 9 * (100 - sliderVal) + 100;
boolean LEDonoff = true;
void buildWebsite() {
  webSite = "<!DOCTYPE HTML><HTML>\n";
  webSite += "<META name='viewport' content='width=device-width, initial-scale=1'>\n";
  webSite += "<BODY>\n";
  webSite += "<BR><B>This is the ESP website ...</B><BR><BR>\n";
  webSite += "<TABLE BORDER=1 WIDTH=200px BGCOLOR='cornsilk' STYLE='border-collapse:collapse;text-align:center'>\n";
  webSite += "<TR><TD>Slidervalue = <A ID='Sliderval'></A><BR>\n";
  webSite += "<TR><TD><INPUT ID='slider' TYPE='range' ONCHANGE='Slider()' STYLE='writing-mode:bt-lr;-webkit-appearance:slider-vertical;' orient='vertical'></TD></TR>\n";
  webSite += "<TR><TD><BUTTON ID='button' ONCLICK='button()' STYLE='width:110px;height:40px'></BUTTON></TD></TR>\n";
  webSite += "</TABLE>\n";
  webSite += "<SCRIPT>\n";
  webSite += "InitWebSocket();\n";
  webSite += "function InitWebSocket(){\n";
  webSite += "  websock=new WebSocket('ws://'+window.location.hostname+':88/');\n";
  webSite += "  websock.onmessage=function(evt){\n";
  webSite += "    JSONobj=JSON.parse(evt.data);\n";
  webSite += "    document.getElementById('slider').value=JSONobj.sliderVal;\n";
  webSite += "    document.getElementById('Sliderval').innerHTML=JSONobj.sliderVal;\n";
  webSite += "  }\n";
  webSite += "}\n";
  webSite += "function Slider(){\n";
  webSite += "  sliderVal=document.getElementById('slider').value;\n";
  webSite += "  websock.send('sliderVal='+sliderVal);\n";
  webSite += "}\n";
  webSite += "</SCRIPT>\n";
  webSite += "</BODY>\n";
  webSite += "</HTML>\n";
}
void handleWebsite() {
  buildWebsite();
  server.send(200, "text/html", webSite);
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t wslength) {
  String payloadString = (const char *)payload;
  byte separator = payloadString.indexOf('=');
  String var = payloadString.substring(0, separator);
  String val = payloadString.substring(separator + 1);
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", num);
      break;
    case WStype_CONNECTED: {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
        webSocket.sendTXT(num, "Connected");
      }
      break;
    case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\n", num, payload);
      if (var == "sliderVal") {
        sliderVal = val.toInt();
        LEDmillis = 9 * (100 - sliderVal) + 100;
      }
      break;
  }
}
void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(
    IPAddress(192, 168, 4, 1),
    IPAddress(192, 168, 4, 1),
    IPAddress(255, 255, 255, 0));
  server.on("/", handleWebsite);
  server.begin();
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}
void loop() {
  webSocket.loop();
  server.handleClient();

  if (millis() > wait000 && LEDonoff == true) {
    digitalWrite(LED, !digitalRead(LED));
    wait000 = millis() + LEDmillis;
  }

  if (millis() > wait001) {
    JSONtxt = "{\"sliderVal\":\"" + (String)sliderVal + "\"," +
              "\"LEDmillis\":\"" + (String)LEDmillis + "\"}";
    webSocket.broadcastTXT(JSONtxt);
    wait001 = millis() + websockMillis;
  }
}



if a mobile device is locked, goes to sleep or the application is moved to the background, any active WebSocket connection may become unresponsive and not close itself properly so you need to check the status of your web socket and re-establish the link if it's dead.

I remember that there is an option to force refreshing through adding a certain detail in the url but I don't remember the syntax.

@J-M-L do you know what I mean and can you post an example how to add this detail that forces refreshing?

I'm not sure what you mean by that.

here it's a web socket that's being used and one of the party to the communication goes away...

WebSocket connections can become stale due to various reasons such as network issues, server-side problems, or inactivity.

You can implement a heartbeat mechanism (Keep-Alive Messages) where the server sends periodic "ping" messages to the client or implement a timeout mechanism on both the client and server sides (if there is no activity within a specified period, you can assume the connection is stale and close it).

Depending on your platform WebSocket connections can emit error events. You can listen for these events and take appropriate action but here I don't think the web browser does get such an event when the device goes to sleep.

web sockets are useful as you maintain this communication channel open in both directions, but it comes with complexity. Sometimes it's better to just go AJAX and let the browser ping the server back when needed. You pay the reconnection cost each time but at least you don't need to deal with the disappearing connexion.

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