/* 
  WiFiTelnetToSerial - Example Transparent UART to Telnet Server for esp8266

  Copyright (c) 2015 Hristo Gochkov. All rights reserved.
  This file is part of the ESP8266WiFi library for Arduino environment.
 
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
#include <ESP8266WiFi.h>
#include <algorithm>
//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 1
const char* ssid = "uCart_AP";
const char* password = "**********";

WiFiServer server(8080);
WiFiClient serverClients[MAX_SRV_CLIENTS];

int tcp_buf_size = 2048;
byte* tcp_buf = (byte*) malloc(tcp_buf_size);
int ser_buf_size = 1024;
byte* serial_buf = (byte*) malloc(ser_buf_size);

void setup() {
  Serial1.begin(115200);
  //WiFi.begin(ssid, password);

  
  // Configure chip to be access point
  WiFi.mode(WIFI_AP);

  // Wait for Access point to be created
  while (!WiFi.softAP(ssid)) {
    delay(500); // Wait half a second before re-trying
  }
  
  //start UART and the server
  Serial.begin(921600);
  Serial.setRxBufferSize(1024);
  server.begin();
  server.setNoDelay(true);

}

void loop() {
  
  uint8_t i, j;
  //check if there are any new clients
  if (server.hasClient()){
    for(i = 0; i < MAX_SRV_CLIENTS; i++){
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()){
        if(serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    serialFlush();
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }
  
  //check clients for data
  if (serverClients[0] && serverClients[0].connected()){
    //delay(1);
    while(serverClients[0].available()){
      int aval = std::min(serverClients[0].available(), tcp_buf_size);
      
      int retval = serverClients[0].read(tcp_buf, aval);
      Serial.write(tcp_buf, aval);
    }
  }
  
  if (Serial.available()) {
    size_t len = std::min(Serial.available(), ser_buf_size);
    Serial.readBytes(serial_buf, len);
    int written = serverClients[0].write((const uint8_t*)serial_buf, len);
    //Serial.write(serial_buf, len);
  }
}

void serialFlush(){
  while(Serial.available() > 0) {
    char t = Serial.read();
  }
}