/**
 * This sketch was written in order to stress test the TCPServer and WEBServer classes used in my project and 
 * hopefully find why the WEBServer class isn't stable ...
 * This test is aimed toward spotting possible causes of crash
 * /!\ Don't forget to define SSID and PASSWD macros ...
 * Created by Anatole SCHRAMM-HENRY the 12/12/2020
 */

#include "StressServer.h"
#include "credentials.h"

WiFiEventHandler gotIpEventHandler, disconnectedEventHandler;
StressServer<TCPClient> ss(1234,10,400);

unsigned long ts(0);

void setup()
{
  Serial.begin(115200);
  Serial.printf("\nSetup start\n");
  ss.enableTCPKeepAlive(15, 5, 5);
  gotIpEventHandler = WiFi.onStationModeGotIP(&(gotIp));
  disconnectedEventHandler = WiFi.onStationModeDisconnected(&(lostCon));
  WiFi.persistent(false);
  WiFi.begin(SSID,PASSWD);//Connect to AccessPoint as a STAtion
  Serial.printf("Setup end\n");
}


void loop()
{
  if(millis() - ts > 5000)
  {
    debugInfo();
    ts = millis();
  }
  ss.run();
}

void debugInfo()
{
  uint32_t freeMem;
  uint16_t biggestContigMemBlock;
  uint8_t frag;
  ESP.getHeapStats(&freeMem, &biggestContigMemBlock, &frag);
  
  Serial.printf("Free MEM : %lu\nHeap Frag : %u\nMax Block : %u\nRunning since %u s\n",freeMem, frag, biggestContigMemBlock, millis()/1000);
}

void gotIp(const WiFiEventStationModeGotIP& event)
{
  Serial.print("Got IP : ");Serial.println(WiFi.localIP());
}

void lostCon(const WiFiEventStationModeDisconnected& event)
{
  Serial.println("Lost connection");
}
