Hard fault caused due to TCPServer begin if system firmware resets WLAN due to SPARK_WLAN_RESET

Hello,
I am running semi-automatic mode. I have 2 WiFi network credentials stored in my P1. If P1 is unable to connect using the first config it tries to connect using the second config. Let’s say the first WiFi config to which it tries to connect is valid and P1 always connects to the second WiFi config.

The following is a part of my code.

TCPServer debugServer = TCPServer(23);
bool startDebugServerStatus = false;

void setup( ) {

}

void loop( ) {

if(WiFi.ready()) {
  if(!startDebugServerStatus){
      debugServer.begin();
      startDebugServerStatus = true;
  }
  if(debugServerClient.available()){
      Serial.println("Client connected to server");
      char readBuf[200] = {0};
      int index = 0;
  	while(debugServerClient.available() && (index < 200)){
  	 char c = debugServerClient.read();
  	 readBuf[index] = c;
  	 index++;
  	}
  	Serial.printf("Sent to server: %s\n", readBuf);
  }
  else{
      debugServerClient = debugServer.available();
  }

}
else{
//WiFi got reset, so start the server again
startDebugServerStatus = false;
}
}

With P1 connected using the second WiFi config, I turned internet connectivity off keeping the WiFi on. The system logs showed that Cloud socket connection failed = -1 and after some time Resetting WLAN due to SPARK_WLAN_RESET. After this message, P1 crashes. The RGB LED blink pattern shows that it’s a hard fault.

My understanding is if WLAN gets reset after TCPServer.begin() is called P1 crashes. I tried stopping the server when WiFi.ready() is false using TCPServer.stop(). This instantly causes the P1 to crash. Also before resetting WLAN and after starting TCPServer, I was able to connect to P1 using it’s local IP on port 23 using

telnet localIP 23

But when I try to send data nothing is being received on the P1 side. I am not sure why. Any ideas?

Thanks
Dheeraj