#include "WiFiEsp.h"

/*
  Filename: Project template
  Author: Mykola Kyrylenko
  Date: 16/11/21
  Description: Testing ESP data transmission
 */

char ssid[] = "Wokwi-GUEST";            // your network SSID (name)
char pass[] = "";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

// URL of server
char server[] = "v-p.bnr.la";
String content;

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  // print the network connection information
  printWifiData();
}

void loop()
{
  // dummy DHT11 data
  content = "api_key=tPmAT5Ab3j7F9&sensor=DHT11&location=Wokwi&value1=19.77&value2=39.95&value3=1025.56";

  // send HTTP request
  httpRequest();
  
  // wait 10 seconds
  delay(10000);
}

void httpRequest() {
  // connect to server
  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("POST /~micros/insert.php HTTP/1.1");
    client.println("Host: valery-presto.bnr.la");
    client.println("Connection: keep-alive");
    client.println("Accept: */*");
    client.println("Content-Length: " + String(content.length()));
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(content);

    // read and discard response
    while (client.available()) {
      char c = client.read(); 
    }
    // disconnect
    Serial.println("Disconnecting from server...");
    client.stop(); 
  }  
}

void printWifiData()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI): ");
  Serial.println(rssi);
  
  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

}