#include <ESP8266WiFi.h>


#ifndef STASSID
#define STASSID "601_IoT_WIFI"
#define STAPSK "wuhcw64667_jsj"
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

const char* host = "192.168.1.111";
const uint16_t port = 1347;


WiFiClient client;

uint8_t uart_rx_buffer[1024];
size_t uart_rx_buffer_index = 0;

uint8_t uart_tx_buffer[1024];
size_t uart_tx_buffer_index = 0;

// static uint8_t test_buff[40960] = {0};


void connectToServer() {
    // Serial.print("connecting to ");
    // Serial.print(host);
    // Serial.print(':');
    // Serial.println(port);
    
    if (!client.connect(host, port)) {
        // Serial.println("connection failed");
        return;
    }
    client.keepAlive();
    client.setTimeout(1);
    // Serial.println("connected");
}


void setup() {
    Serial.begin(115200);
    Serial.setTimeout(1);
    Serial.setRxBufferSize(1024);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        // Serial.print(".");
    }
    // Serial.println(WiFi.localIP());
    connectToServer();
}



void loop() {
  
    // static bool wait = false;

    // Serial.print("connecting to ");
    // Serial.print(host);
    // Serial.print(':');
    // Serial.println(port);

    // Use WiFiClient class to create TCP connections

    // This will send a string to the server
    // Serial.println("sending data to server");
    uart_rx_buffer_index = Serial.readBytes(uart_rx_buffer,64);
    if (client.connected()) {
        client.write(uart_rx_buffer,uart_rx_buffer_index);
        // while(1){
        //     client.write(test_buff,40960);
        // }
        // while(Serial.available()) {
        //     char ch = static_cast<char>(Serial.read());
        //     client.print(ch);
        // }
        // client.println("hello from ESP8266"); 
    }
    else {
        connectToServer();
    }

    while (client.available()) {
        // char ch = static_cast<char>(client.read());
        // Serial.print(ch);
        uart_tx_buffer_index = client.read(uart_tx_buffer,32);
        Serial.write(uart_tx_buffer,uart_tx_buffer_index);
    }

    // unsigned long timeout = millis();
    // while (client.available() == 0) {
    //     if (millis() - timeout > 5000) {
    //         // Serial.println(">>> Client Timeout !");
    //         client.stop();
    //         delay(1000);
    //         return;
    //     }
    // }

    // Read all the lines of the reply from server and print them to Serial
    // Serial.println("receiving from remote server");
    // not testing 'client.connected()' since we do not need to send data here
    

    // Close the connection
    // Serial.println();
    // Serial.println("closing connection");
    // client.stop();

    // if (wait) {
    //     delay(300000);  // execute once every 5 minutes, don't flood remote service
    // }
    // wait = true;

}
