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

Moderator: igrr

User avatar
By Th3On3Fr33man
#47942 So I'm using the ESP8266WebServer and ESP8266WiFiMulti libraries to run a webpage with websockets and I'm trying to figure out how many connections I can have, and if there's any way to increase that connection limit?

Right now it seems that I can successfully create three connections from separate IPs, and then upon initiating the fourth connection, it fails (the server doesn't crash in the serial model, but the fourth connection won't load the webpage).

I've also noticed that if I refresh my own singular connection a certain number of times (inconsistent), it will fail to load the webpage as well. I haven't been able to decipher whether this has to do with there being too many consecutive connections in general or if I'm overtaxing the server by attempting to reconnect within too quick a timeframe?

In general though, it seems rather unstable and I could really use some assistance on figuring out why.

Here's my current code:

Code: Select all#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

static const char ssid[] = "********";
static const char password[] = "********";
MDNSResponder mdns;

static void writeLED(bool);

ESP8266WiFiMulti WiFiMulti;

IPAddress ipAddressTest = (99,99,99,99);

ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);

uint8_t pageHitCounter = 0;
IPAddress ipAddressOne = (99,99,99,99);
IPAddress ipAddressTwo = (99,99,99,99);
IPAddress ipAddressThree = (99,99,99,99);
IPAddress ipAddressFour = (99,99,99,99);

uint8_t rxBuff[256];
uint8_t som = 0x11;
uint8_t eom = 0x12;
uint8_t subsys;
uint8_t receivedSubsys;
uint8_t rx_byte = 0x00;
uint8_t messageLength = 0;
uint8_t receivedMessageLength = 0;
uint8_t messageContent;
uint8_t serialCurrent;

int initialCounter = 0;
boolean messageBegun = false;
boolean messageInProgress = false;

int currNumRefresh = 0;
int currMicroC = 0;
int currMicroD = 0;
int currMicroE = 0;
int currPressureC = 0;
int currPressureD = 0;
int currPressureE = 0;
int currValveStatusNumC = 0;
int currValveStatusNumD = 0;
int currValveStatusNumE = 0;
int currFluid = 0;

char statusbuf[256];
char status[] = "";
int statusIndex = 0;

String valveStatusC = "Closed";
String valveTubePropsC = "175px solid #00ADEF";
String valveColorC = "red";

String valveStatusD = "Closed";
String valveTubePropsD = "175px solid #00ADEF";
String valveColorD = "red";

String valveStatusE = "Closed";
String valveTubePropsE = "175px solid #00ADEF";
String valveColorE = "red";

uint8_t currCountdown = 0;
long prevTimeCountdown = 0;
long countdownInterval = 1000;
long countdownPostInterval = 100;
bool countdownFlag = true;

bool teensyPOWER = false;
bool pumpPOWER = false;
bool teensyLED = false;

void switchPOWERon() {
   
    //Serial.println("TEST POWER ON");
   
    int powerStatusLength = 1;
   
    subsys = 0x10;
   
    //Account for the end of message
    messageLength = powerStatusLength + 2;
   
    messageContent = 1;
   
    Serial.write(som);
    Serial.write(messageLength);
    Serial.write(subsys);
    Serial.write(messageContent);
    Serial.write(eom);
    //Serial.println("");
    //Serial.println("TURN POWER ON|");
    //teensyLED = true;
} //end switchPOWERon

void switchPOWERoff() {
   
    //Serial.println("TEST POWER ON");
   
    int powerStatusLength = 1;
   
    subsys = 0x10;
   
    //Account for the end of message
    messageLength = powerStatusLength + 2;
   
    messageContent = 0;
   
    Serial.write(som);
    Serial.write(messageLength);
    Serial.write(subsys);
    Serial.write(messageContent);
    Serial.write(eom);
    //Serial.println("");
    //Serial.println("TURN POWER ON|");
    //teensyLED = true;
} //end switchPOWERoff

void pumpPOWERon() {
   
    //Serial.println("TEST POWER ON");
   
    int pumpPowerStatusLength = 1;
   
    subsys = 0x13;
   
    //Account for the end of message
    messageLength = pumpPowerStatusLength + 2;
   
    messageContent = 1;
   
    Serial.write(som);
    Serial.write(messageLength);
    Serial.write(subsys);
    Serial.write(messageContent);
    Serial.write(eom);
    //Serial.println("");
    //Serial.println("TURN POWER ON|");
    //teensyLED = true;
} //end switchPOWERon

void pumpPOWERoff() {
   
    //Serial.println("TEST POWER OFF");
   
    int pumpPowerStatusLength = 1;
   
    subsys = 0x13;
   
    //Account for the end of message
    messageLength = pumpPowerStatusLength + 2;
   
    messageContent = 0;
   
    Serial.write(som);
    Serial.write(messageLength);
    Serial.write(subsys);
    Serial.write(messageContent);
    Serial.write(eom);
    //Serial.println("");
    //Serial.println("TURN POWER ON|");
    //teensyLED = true;
} //end switchPOWERoff

void switchLEDon() {
   
    //Serial.println("TEST LED ON");
   
    int ledStatusLength = 1;
   
    subsys = 0x14;
   
    //Account for the end of message
    messageLength = ledStatusLength + 2;
   
    messageContent = 1;
   
    Serial.write(som);
    Serial.write(messageLength);
    Serial.write(subsys);
    Serial.write(messageContent);
    Serial.write(eom);
    //Serial.println("");
    //Serial.println("TURN LED ON|");
    //teensyLED = true;
} //end switchLEDon
 
void switchLEDoff() {
   
    //Serial.println("TEST LED OFF");
   
    int ledStatusLength = 1;
   
    subsys = 0x14;
   
    //Account for the end of message
    messageLength = ledStatusLength + 2;
   
    messageContent = 0;
   
    Serial.write(som);
    Serial.write(messageLength);
    Serial.write(subsys);
    Serial.write(messageContent);
    Serial.write(eom);
    //Serial.println("");
   
    //Serial.println("TURN LED OFF|");
    teensyLED = false;
} //end switchLEDoff

void statusUpdate(uint8_t num) {
   
   
    //Valve C
    if(currValveStatusNumC == 0)
    {
        valveColorC = "red";
        valveTubePropsC = "175px solid #00ADEF";
        valveStatusC = "Closed";
    } //end if
    else if(currValveStatusNumC == 1)
    {
        valveColorC = "green";
        valveTubePropsC = "350px solid #00ADEF";
        valveStatusC = "Open";
    } //end else if
   
    //Valve D
    if(currValveStatusNumD == 0)
    {
        valveColorD = "red";
        valveTubePropsD = "175px solid #00ADEF";
        valveStatusD = "Closed";
    } //end if
    else if(currValveStatusNumD == 1)
    {
        valveColorD = "green";
        valveTubePropsD = "350px solid #00ADEF";
        valveStatusD = "Open";
    } //end else if
   
    //Valve E
    if(currValveStatusNumE == 0)
    {
        valveColorE = "red";
        valveTubePropsE = "175px solid #00ADEF";
        valveStatusE = "Closed";
    } //end if
    else if(currValveStatusNumE == 1)
    {
        valveColorE = "green";
        valveTubePropsE = "350px solid #00ADEF";
        valveStatusE = "Open";
    } //end else if
   
    String test = "";
    test += currNumRefresh;
    test += ",";
    test += currMicroC;
    test += ",";
    test += currMicroD;
    test += ",";
    test += currMicroE;
    test += ",";
    test += currPressureC;
    test += ",";
    test += currPressureD;
    test += ",";
    test += currPressureE;
    test += ",";
    test += valveColorC;
    test += ",";
    test += valveTubePropsC;
    test += ",";
    test += valveStatusC;
    test += ",";
    test += valveColorD;
    test += ",";
    test += valveTubePropsD;
    test += ",";
    test += valveStatusD;
    test += ",";
    test += valveColorE;
    test += ",";
    test += valveTubePropsE;
    test += ",";
    test += valveStatusE;
    test += ",";
    test += currFluid;
    test += ",";
    test += pageHitCounter;
    test += ",";
    test += ipAddressTest;
   
    //Serial.print("TEST: ");
    //Serial.println(ipAddressTest);
   
    test.toCharArray(statusbuf, 256);
    webSocket.sendTXT(num, statusbuf, strlen(statusbuf));
}

static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
    <head>
        <title>Adafruit HUZZAH ESP8266</title>
       
<style type='text/css'>   
/*CSS removed to fit maximum number of allowed characters*/
</style>
<script>

var currPressureTest = 0;
var currFluidTest = 0;                                               
           
function POWERswitch(){
    var POWERswitchCheck = document.getElementById('switch1').checked;       
           
    if(POWERswitchCheck){
        websock.send("teensyPOWERon");     
    }
    else if(!POWERswitchCheck) {
        websock.send("teensyPOWERoff");
    }
}
           
function FLUSHbegin(){
    websock.send("pumpPOWERon");           
}
           
function FLUSHend(){
    websock.send("pumpPOWERoff");
}
           
function LEDswitch(){
    var LEDswitchCheck = document.getElementById('myonoffswitch').checked;       
           
    if(LEDswitchCheck){
        websock.send("teensyLEDon");     
    }
    else if(!LEDswitchCheck) {
        websock.send("teensyLEDoff");
    }
}
           
var websock;
var test = "open";
var webpageHitCounter = 20;
           
function start() {
    websock = new WebSocket('ws://' + window.location.hostname + ':81/');
    websock.onopen = function(evt) {
        console.log('websock open');
        statusUpdate();
    };
    websock.onclose = function(evt) {
        console.log('websock close');
    };
    websock.onerror = function(evt) {
        console.log(evt);
    };
    websock.onmessage = function(evt) {
        console.log(evt);
        var e = document.getElementById('ledstatus');
        var te = document.getElementById('myonoffswitch');
        var pe = document.getElementById('switch1');
                   
                   
        if(evt.data === 'teensyPOWERon')
        {
            pe.checked = 'checked';
        }
        else if(evt.data === 'teensyPOWERoff')
        {
            pe.checked = '';
        }
        else if(evt.data === 'pumpPOWERon')
        {
           
        }
        else if(evt.data === 'pumpPOWERoff')
        {
           
        }
        else if(evt.data === 'teensyLEDon')
        {
            te.checked = 'checked';
        }
        else if(evt.data === 'teensyLEDoff')
        {
            te.checked = '';
        }
        else if(evt.data === 'Update Status')
        {
           
        }
        else {
          console.log('status event');
                     
          var totalStatus = evt.data;                                             
          var splitStatus = totalStatus.split(',');                                           
          //alert("TEST: " + totalStatus);
                     
          //alert('Pressure C: ' + splitStatus[0] + ', Pressure D: ' + splitStatus[1] + ', Pressure E: ' + splitStatus[2]);                                             
                           
          //Num Refresh
          document.getElementById("demo").innerHTML = splitStatus[0];                 

          //MICROSWITCH C
          var microswitchOffC = document.getElementById('switchOffC');
          var microswitchOnC = document.getElementById('switchOnC');
                     
          if(splitStatus[1] == 0)
          {
            microswitchOnC.checked = false;
            microswitchOffC.checked = true;
          }
          else if(splitStatus[1] == 1)
          {
            microswitchOffC.checked = false;
            microswitchOnC.checked = true;
          }                 

          //MICROSWITCH D
          var microswitchOffD = document.getElementById('switchOffD');
          var microswitchOnD = document.getElementById('switchOnD');
                     
          if(splitStatus[2] == 0)
          {
            microswitchOnD.checked = false;
            microswitchOffD.checked = true;
          }
          else if(splitStatus[2] == 1)
          {
            microswitchOffD.checked = false;
                       
            microswitchOnD.checked = true;
                       
          }                 

          //MICROSWITCH E
          var microswitchOffE = document.getElementById('switchOffE');
          var microswitchOnE = document.getElementById('switchOnE');
                     
          if(splitStatus[3] == 0)
          {
            microswitchOnE.checked = false;
            microswitchOffE.checked = true;
          }
          else if(splitStatus[3] == 1)
          {
            microswitchOffE.checked = false;
            microswitchOnE.checked = true;
          }

          //PRESSURE C
          var pressureValue = document.querySelector('.gauge-c');
          pressureValue.style.transform = 'rotate('+ splitStatus[4] +'deg)';                 
         
          var pressureText = (((splitStatus[4])/180)*100).toFixed(0);
          document.getElementById("pressurePercentC").innerHTML = pressureText + '%';                 
                           
          if(pressureText > 75){
              pressureValue.style.background = 'red';   
          }                 
          else if(pressureText > 25 && pressureText < 75){
              pressureValue.style.background = 'yellow';
          }             
          else if(pressureText < 25){
              pressureValue.style.background = 'green';
          }                                                                         

          //PRESSURE D
          var pressureValue = document.querySelector('.gauge-d');
          pressureValue.style.transform = 'rotate('+ splitStatus[5] +'deg)';               
         
          var pressureText = (((splitStatus[5])/180)*100).toFixed(0);
          document.getElementById("pressurePercentD").innerHTML = pressureText + '%';       
                     
          if(pressureText > 75){
              pressureValue.style.background = 'red';   
          }                   
          else if(pressureText > 25 && pressureText < 75){
              pressureValue.style.background = 'yellow';
          }                   
          else if(pressureText < 25){
              pressureValue.style.background = 'green';
          }                 

          //PRESSURE E
          var pressureValue = document.querySelector('.gauge-e');
          pressureValue.style.transform = 'rotate('+ splitStatus[6] +'deg)';               
         
          var pressureText = (((splitStatus[6])/180)*100).toFixed(0);
          document.getElementById("pressurePercentE").innerHTML = pressureText + '%';               
                           
          if(pressureText > 75){
              pressureValue.style.background = 'red';   
          }                   
          else if(pressureText > 25 && pressureText < 75){
              pressureValue.style.background = 'yellow';
          }                   
          else if(pressureText < 25){
              pressureValue.style.background = 'green';
          }               
                     
          //VALVE STATUS C
          var valve = document.querySelector('.valve-c');
          var valveTube = document.querySelector('.valveTube-c');
          valve.style.background = splitStatus[7];
          document.getElementById("valveStatus-c").innerHTML = splitStatus[9];
                     
          if(splitStatus[9] == "Open")
          {
            valveTube.style["border-left"] = splitStatus[8];
          } //end if
          else if(splitStatus[9] == "Closed")
          {
            valveTube.style["border-left"] = splitStatus[8];
          }
                     
          //VALVE STATUS D
          var valve = document.querySelector('.valve-d');
          var valveTube = document.querySelector('.valveTube-d');
          valve.style.background = splitStatus[10];
          document.getElementById("valveStatus-d").innerHTML = splitStatus[12];
                     
          if(splitStatus[12] == "Open")
          {
            valveTube.style["border-left"] = splitStatus[10];
          } //end if
          else if(splitStatus[12] == "Closed")
          {
            valveTube.style["border-left"] = splitStatus[11];
          }
                     
          //VALVE STATUS E
          var valve = document.querySelector('.valve-e');
          var valveTube = document.querySelector('.valveTube-e');
          valve.style.background = splitStatus[13];
          document.getElementById("valveStatus-e").innerHTML = splitStatus[15];
                     
          if(splitStatus[15] == "Open")
          {
            valveTube.style["border-left"] = splitStatus[14];
          } //end if
          else if(splitStatus[15] == "Closed")
          {
            valveTube.style["border-left"] = splitStatus[14];
          }
                     
          //FLUID LEVEL
          var fluidValue = document.querySelector('.fluidMeter');
                     
          if(splitStatus[16] >= 0 && splitStatus[16] <= 100)
          {
            fluidValue.value = splitStatus[16];
          } //end if
          else
          {
            fluidValue.value = 0; 
          } //end else
                     
          var fluidText = splitStatus[16];
          document.getElementById("fluidPercent").innerHTML = fluidText + '%';
         
          webpageHitCounter = splitStatus[17];
          var ipAddress = splitStatus[18];
          document.getElementById("counterText").innerHTML = "TEST COUNTER: " + webpageHitCounter + " FROM " + ipAddress;
         
          }
      };
  }
           
  function statusUpdate() {
      websock.send("Update Status");
      setTimeout('statusUpdate()', 5000); 
  }
   
        </script>                 
    </head>

    <body style='background-color:#4a4a4c;' onload="start();">
       
        <div style='text-align:center;'>
            <h1 style='text-decoration: underline; color:white;'>Adafruit HUZZAH ESP8266</h1>
        </div>
       
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
       
        <div style="clear:both;"></div>     
       
        <div class='counterContainer'>
            <span id="counterText" style="color:white;"></span>
        </div>
       
        <div id='adminControls' class='adminControlsRow'>
           
            <h2>Administrator Controls</h2>
           
            <div id='Newbtn' class='powerSwitchContainer'>
                <h2>HHIO PTT Power</h2>
           
                <span class="switch">
                  <span class="switch-border1">
                        <span class="switch-border2">
                          <input id="switch1" type="checkbox" onclick='POWERswitch()' checked />
                          <label for="switch1"></label>
                          <span class="switch-top"></span>
                          <span class="switch-shadow"></span>
                          <span class="switch-handle"></span>
                          <span class="switch-handle-left"></span>
                          <span class="switch-handle-right"></span>
                          <span class="switch-handle-top"></span>
                          <span class="switch-handle-bottom"></span>
                          <span class="switch-handle-base"></span>
                          <span class="switch-led switch-led-green">
                            <span class="switch-led-border">
                              <span class="switch-led-light">
                                <span class="switch-led-glow"></span>
                              </span>
                            </span>
                          </span>
                          <span class="switch-led switch-led-red">
                            <span class="switch-led-border">
                             <span class="switch-led-light">
                                <span class="switch-led-glow"></span>
                              </span>
                            </span>
                          </span>
                        </span>
                  </span>
                </span>
            </div>
            <div class='flushBtnContainer'>
                <h2>Fluid Reservoir</h2>
                <button id='flushBtn' onmousedown="FLUSHbegin();" onmouseup="FLUSHend();">Flush</button>
            </div>
        </div>
       
        <div style='background-color:#1E1E20; clear:both;'>
            <h2 style='color: white;'>LED Controls</h2>                           
            <div id='LEDbtn' class='onoffswitch'>                             
                <input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' onclick='LEDswitch()'>                           
                <label class='onoffswitch-label' for='myonoffswitch'>
                    <span class='onoffswitch-inner'></span>
                    <span class='onoffswitch-switch'></span>
                </label>
            </div>
        </div>             

        <div style='background-color:#1E1E20; color: white;'>
            <h2>Num Refresh Test</h2>   
            <div id="demo"><h2>Let WEBSOCKET change this text</h2></div>
        </div>
       
        <div class='headerRow'>
            <div class="header">
                <h2>Left Shoulder</h2>
            </div>
           
            <div class="header">
                <h2>Sternum</h2>
            </div>
           
            <div class="header">
                <h2>Right Shoulder</h2>
            </div>
        </div>
       
        <div class='microswitchRow'>
            <div class="microswitchContainer">
            <div class="microswitch white">
              <input type="radio" name="switchC" class="microswitchRadio" id="switchOffC" checked>
              <input type="radio" name="switchC" class="microswitchRadio" id="switchOnC">

              <label for="switchOffC">Detached</label>
              <label for="switchOnC">Attached</label>

              <span class="toggle"></span>
            </div>
           </div>
            <div class="microswitchContainer">
            <div class="microswitch white">
              <input type="radio" name="switchD" class="microswitchRadio" id="switchOffD" checked>
              <input type="radio" name="switchD" class="microswitchRadio" id="switchOnD">

              <label for="switchOffD">Detached</label>
              <label for="switchOnD">Attached</label>

              <span class="toggle"></span>
            </div>
           </div>
            <div class="microswitchContainer">
            <div class="microswitch white">
              <input type="radio" name="switchE" class="microswitchRadio" id="switchOffE" checked>
              <input type="radio" name="switchE" class="microswitchRadio" id="switchOnE">

              <label for="switchOffE">Detached</label>
              <label for="switchOnE">Attached</label>

              <span class="toggle"></span>
            </div>
           </div>
        </div>
       
        <div class='pressureRow'>
            <div class='pressureContainer'>
                <div class='gauge-a'></div>
                <div class='gauge-b'></div>
                <div class='gauge-c'></div>
                <div class='gauge-data'><h1 id='pressurePercentC'>0%</h1></div>
            </div>
            <div class='pressureContainer'>
                <div class='gauge-a'></div>
                <div class='gauge-b'></div>
                <div class='gauge-d'></div>
                <div class='gauge-data'><h1 id='pressurePercentD'>0%</h1></div>
            </div>
            <div class='pressureContainer'>
                <div class='gauge-a'></div>
                <div class='gauge-b'></div>
                <div class='gauge-e'></div>
                <div class='gauge-data'><h1 id='pressurePercentE'>0%</h1></div>
            </div>
        </div>           
       
        <div class='valveRow'>
            <div class='valveContainer'>
                <div class="valveTube-c"></div>
                <div class="valve-c"></div>
                <div class='valve-data'><h1 id='valveStatus-c'>Closed</h1></div>
            </div>
            <div class='valveContainer'>
                <div class="valveTube-d"></div>
                <div class="valve-d"></div>
                <div class='valve-data'><h1 id='valveStatus-d'>Closed</h1></div>
            </div>
            <div class='valveContainer'>
                <div class="valveTube-e"></div>
                <div class="valve-e"></div>
                <div class='valve-data'><h1 id='valveStatus-e'>Closed</h1></div>
            </div>
        </div>
       
        <div class='fluidContainer'>
            <meter class='fluidMeter' max='100' value='50' low='25' high='75' optimum='100'></meter>
            <div class='fluid-data'><h1 id='fluidPercent'>0%</h1></div>
        </div>
       
    </body>
</html>
)rawliteral";

// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 0;

// Current POWER status
bool POWERStatus;

// Current LED status
bool LEDStatus;

// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";

const char teensyPOWERON[] = "teensyPOWERon";
const char teensyPOWEROFF[] = "teensyPOWERoff";

const char pumpPOWERON[] = "pumpPOWERon";
const char pumpPOWEROFF[] = "pumpPOWERoff";

const char teensyLEDON[] = "teensyLEDon";
const char teensyLEDOFF[] = "teensyLEDoff";

const char statusIdentifier[] = "Update Status";



void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
  //Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
  switch(type) {
    case WStype_DISCONNECTED:
      //Serial.printf("[%u] Disconnected!\r\n", num);
      break;
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(num);
        //Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
         
        // Send the current LED status
        if (LEDStatus) {
          webSocket.sendTXT(num, LEDON, strlen(LEDON));
        }
        else if(!LEDStatus) {
          webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
        }
        else if(teensyPOWER) {
          webSocket.sendTXT(num, teensyPOWERON, strlen(teensyPOWERON));
        }
        else if(!teensyPOWER) {
          webSocket.sendTXT(num, teensyPOWEROFF, strlen(teensyPOWEROFF));
        } 
        else if(pumpPOWER) {
          webSocket.sendTXT(num, teensyPOWERON, strlen(teensyPOWERON));
        }
        else if(!pumpPOWER) {
          webSocket.sendTXT(num, pumpPOWEROFF, strlen(pumpPOWEROFF));
        } 
        else if(teensyLED) {
          webSocket.sendTXT(num, teensyLEDON, strlen(teensyLEDON));
        }
        else if(!teensyLED) {
          webSocket.sendTXT(num, teensyLEDOFF, strlen(teensyLEDOFF));
        }
      }
      break;
    case WStype_TEXT:
      //Serial.printf("[%u] get Text: %s\r\n", num, payload);
         
      if (strcmp(LEDON, (const char *)payload) == 0) {
        writeLED(true);
      }
      else if (strcmp(LEDOFF, (const char *)payload) == 0) {
        writeLED(false);
      }
      else if(strcmp(teensyPOWERON,  (const char *)payload) == 0) {
          switchPOWERon();
      }
      else if(strcmp(teensyPOWEROFF,  (const char *)payload) == 0) {
          switchPOWERoff();
      }
      else if(strcmp(pumpPOWERON,  (const char *)payload) == 0) {
          pumpPOWERon();
      }
      else if(strcmp(pumpPOWEROFF,  (const char *)payload) == 0) {
          pumpPOWERoff();
      }
      else if(strcmp(teensyLEDON,  (const char *)payload) == 0) {
          switchLEDon();
      }
      else if(strcmp(teensyLEDOFF,  (const char *)payload) == 0) {
          switchLEDoff();
      }
      else if(strcmp(statusIdentifier, (const char *)payload) == 0) {
          statusUpdate(num);
      }
      else {
        //Serial.println("Unknown command");
      }
      // send data to all connected clients
      webSocket.broadcastTXT(payload, length);
      break;
    case WStype_BIN:
      //Serial.printf("[%u] get binary length: %u\r\n", num, length);
      hexdump(payload, length);

      // echo data back to browser
      webSocket.sendBIN(num, payload, length);
      break;
    default:
      //Serial.printf("Invalid WStype [%d]\r\n", type);
      break;
  }
}

void handleRoot()
{
 
  server.send(200, "text/html", INDEX_HTML);
 
  if(ipAddressTest != (0,0,0,0))
  {
      if(ipAddressOne == (99,99,99,99))
      {
          ipAddressOne = ipAddressTest;
          pageHitCounter++;
          //server.send(200, "text/html", INDEX_HTML);
     
          Serial.print("1st NEW IP: ");
          Serial.println(ipAddressTest);
      }
 
      else if(ipAddressTwo == (99,99,99,99))
      {
          if(ipAddressOne == ipAddressTest)
          {
              Serial.print("Old Connection-1 currently connected; Current Connection: ");
              Serial.println(ipAddressTest);
              //server.send(200, "text/html", INDEX_HTML);
          }
          else
          {
              ipAddressTwo = ipAddressTest;
              pageHitCounter++;
              //server.send(200, "text/html", INDEX_HTML);
     
              Serial.print("2nd NEW IP: ");
              Serial.println(ipAddressTest);
          }
      }
 
      else if(ipAddressThree == (99,99,99,99))
      {
          if(ipAddressOne == ipAddressTest || ipAddressTwo == ipAddressTest)
          {
               Serial.print("Old Connection-2 currently connected; Current Connection: ");
               Serial.println(ipAddressTest);
               //server.send(200, "text/html", INDEX_HTML);
          }
          else
          {
              ipAddressThree = ipAddressTest;
              pageHitCounter++;
              //server.send(200, "text/html", INDEX_HTML);
     
              Serial.print("3rd NEW IP: ");
              Serial.println(ipAddressTest);
          }
      }
   
      else if(ipAddressFour == (99,99,99,99))
      {
          if(ipAddressOne == ipAddressTest || ipAddressTwo == ipAddressTest || ipAddressThree == ipAddressTest)
          {
               Serial.println("Old Connection-3 currently connected; Current Connection: ");
               Serial.println(ipAddressTest);
               //server.send(200, "text/html", INDEX_HTML);
          }
          else
          {
              ipAddressFour = ipAddressTest;
              pageHitCounter++;
              //server.send(200, "text/html", INDEX_HTML);
     
              Serial.print("4th NEW IP: ");
              Serial.println(ipAddressTest);
          }
      }
     
      else
      {
          if(ipAddressOne == ipAddressTest || ipAddressTwo == ipAddressTest || ipAddressThree == ipAddressTest || ipAddressFour == ipAddressTest)
          {
               Serial.println("Old Connection-4 currently connected; Current Connection: ");
               Serial.println(ipAddressTest);
               //server.send(200, "text/html", INDEX_HTML);
          }
          else
          {
              Serial.print("Too many connections! Attempting to Connect: ");
              Serial.println(ipAddressTest);
          }
      }
  }
 
   
 
}

void handleNotFound()
{
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

static void writeLED(bool LEDon)
{
  LEDStatus = LEDon;
  // Note inverted logic for Adafruit HUZZAH board
  if (LEDon) {
    digitalWrite(LEDPIN, 0);
  }
  else {
    digitalWrite(LEDPIN, 1);
  }
}

void setup()
{
  pinMode(LEDPIN, OUTPUT);
  writeLED(false);

  Serial.begin(115200);
   
  //Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  currCountdown = 4;
   
  for(uint8_t t = 4; t > 0; t--) {
   
    unsigned long currTime = millis();
   
    if(countdownFlag == true)
    {
        Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
        Serial.flush();
        countdownFlag = false;
    }
   
   
    if(currTime - prevTimeCountdown > countdownInterval)
    {
        prevTimeCountdown = currTime;
        countdownFlag = true;
    } //end if
     
    else
    {
        t++;
    } //end else
     
  } //end for

  WiFiMulti.addAP(ssid, password);
/*
  prevTimeCountdown = 0;
  countdownFlag = true;
*/   
  while(WiFiMulti.run() != WL_CONNECTED) {
      /*
      unsigned long currTime = millis();
     
      if(countdownFlag == true)
      {
          Serial.print(".");
          countdownFlag = false;
      } //end if
     
      if(currTime - prevTimeCountdown > countdownInterval)
      {
          prevTimeCountdown = currTime;
          countdownFlag = true;
      } //end if
      */
      Serial.print(".");
      delay(1000);
     
  } //end while

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("espWebSock", WiFi.localIP())) {
    Serial.println("MDNS responder started");
    mdns.addService("http", "tcp", 80);
    mdns.addService("ws", "tcp", 81);
  }
  else {
    Serial.println("MDNS.begin failed");
  }
  Serial.print("Connect to http://espWebSock.local or http://");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);

  server.begin();

  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop()
{
    //Communication Protocol
    if(Serial.available() > 0)
    {
        //Serial.print("SERIAL.AVAILABLE: ");
        //Serial.println(Serial.available());
       
        if(initialCounter == 0)
        {
            rx_byte = Serial.read();
        /*
            //Print Start of Message
            Serial.print("0x");
            if(rx_byte<0x10)
            {
                Serial.print("0");
            }
            Serial.println(rx_byte, HEX);
        */
            //Serial.println(rx_byte, BIN);
            //Serial.println(rx_byte);
           
            initialCounter++;
        }
       
       
        if((!messageBegun) && (rx_byte == som))
        {
            messageBegun = true;
           
            //Serial.println("MESSAGE BEGUN TRUE");
        } //end if (messageInProgress && rx_byte)
       
        if((messageBegun) && (!messageInProgress))
        {
            serialCurrent = Serial.available();
           
            if(serialCurrent > 0)
            {     
                receivedMessageLength = (uint8_t)Serial.read();
            /*
                Serial.print("MESSAGE LENGTH: ");
                Serial.println(receivedMessageLength);
            */
                messageBegun = false;
           
                messageInProgress = true;
           
                //Serial.println("MESSAGE IN PROGRESS TRUE");
           
            } //end if (serialCurrent)
        } //end if (messageBegun && messageInProgress)
       
        if(messageInProgress)
        {
            serialCurrent = Serial.available();
           
            if(serialCurrent >= receivedMessageLength)
            {
               
                Serial.readBytes(rxBuff, receivedMessageLength);
           
                if((byte)rxBuff[receivedMessageLength-1] != eom)
                {
                    //Serial.println("ERROR");
                    //Serial.write(Serial.read());
                } //end if (rxBuff != eom)
           
                else
                {
                    messageInProgress = false;
               
                    for(int i=0; i<receivedMessageLength; i++)
                    {
                        if(rxBuff[i] == eom)
                        {
                        /*
                            //Print End of Message
                            Serial.print("0x");
                            if(rx_byte<0x10)
                            {
                                Serial.print("0");
                            }
                            Serial.println(rxBuff[i], HEX);
                        */
                            initialCounter = 0;
                       
                            receivedMessageLength = 0;
                       
                        } //end if
                   
                        else if(i == 0)
                        {
                            receivedSubsys = rxBuff[i];
                        /*
                            //Print Subsystem
                            Serial.print("0x");
                            if(rx_byte<0x10)
                            {
                                Serial.print("0");
                            }
                            Serial.println(rxBuff[i], HEX);
                        */
                        } //end if
                        else
                        {
                            if(receivedSubsys == 0x14)
                            {
                                currNumRefresh = rxBuff[i];
                            } //end if
                           
                            else if(receivedSubsys == 0x15)
                            {
                                currMicroC = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x16)
                            {
                                currMicroD = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x17)
                            {
                                currMicroE = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x18)
                            {
                                currPressureC = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x19)
                            {
                                currPressureD = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x20)
                            {
                                currPressureE = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x21)
                            {
                                currValveStatusNumC = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x22)
                            {
                                currValveStatusNumD = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x23)
                            {
                                currValveStatusNumE = rxBuff[i];
                            } //end else if
                           
                            else if(receivedSubsys == 0x24)
                            {
                                currFluid = rxBuff[i];
                            } //end else if
                           
                        } //end else
                    } //end for
               
                } //end else
           
            } //end if (serialCurrent)
               
        } //end if (messageInProgress)
    } //end if (Serial.available)
   
  webSocket.loop();
  ipAddressTest = server.handleClient();
}


P.S. I slightly modified ESP8266WebServer.cpp's handleClient() function to return the current IP address in order to track individual users, however sometimes I get 0.0.0.0 as an IP address and I don't know why or how to tell if that IP is a new IP or not.
User avatar
By rudy
#48026 I have a webpage that I have stored in SPIFFS. It has a HTML file, a .js file, a .css file, and three small image files. None of the files a big. I only have on connection to the server and most of the time it chokes on the third image. I have to do reloads and it sometime succeeds. I believe it is the same issue as you are seeing. Too many requests at the same time.

I haven't had the time to investigate it but I hope to find a solution in my case. I expect it will be in having the image files requested sequentially. To wait for the first to transfer before calling for the second.
User avatar
By Th3On3Fr33man
#48055 So I looked into this a little more after I posted this and discovered that it appeared to be because of the websocket code that I've been using. After that I researched some more and realized that while I've been storing my entire webpage in a string, there's a far better way to do this by using the FS.h library (I think this is the same method you mentioned Rudy, via SPIFFS) and having an actual filesystem with directories where I can have actual html/css/js files and what not. That seemed to solve the stability issues, and now I've been facing a new problem.

I'm using a serial connection between a teensy 3.1 and this ESP8266, however it seems that the ESP8266 has to be powered on before the teensy, otherwise it won't work (this includes whenever the ESP8266 restarts, it breaks the serial connection or something and so I always have to unplug/plug back in the teensy as well). I think it has something to do with my Serial1.begin() command on the teensy because if I add a delay in the setup() before that to give the wifi card time to set up it works fine.

To be more specific, I'm not actually hosting my own access point off the ESP8266, but merely serving a webpage to another already existing access point.
User avatar
By Th3On3Fr33man
#48060 I think the problem is that for some reason the connection on the teensy has to be set up AFTER the connection on the ESP8266, and so do you know if there would be a way to trigger a reinitialization of the teensy's serial connection after it has begun? I tried reusing the Serial1.begin() command but that doesn't appear to work?

I've tried putting this in the loop, but it's not working :(

if(!Serial1) {
Serial1.end();
Serial1.begin(115200);
} //end if

Another new thing I've noticed...it only breaks the receiving connection from the ESP8266, the teensy still transmits information to the ESP8266, but nothing is getting sent to the teensy.