#include <WiFi.h>
#include <HTTPClient.h>

// Replace with your WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Replace with your webhook URL
const char* webhook_url = "https://script.google.com/macros/s/AKfycbzjc58NTObAelIwLYC3nhx7RO7ZyHOZyl1aECLcgjdAl891mWjZVUOH33C3cJo8E1xY/exec";

unsigned long previousMillis = 0;
const long interval = 5000; 


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

  // Connect to WiFi
  Serial.print("Connecting to WiFi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi!");


}

void loop() {
unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis >= interval) {
    // save the last time you read the sensor 
    previousMillis = currentMillis;   
    
      // Send the POST request
    sendPostRequest();
  
  }
}
void sendPostRequest() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Specify the target URL
    http.begin(webhook_url);
    http.addHeader("Content-Type", "application/json"); // Set content type to JSON
    
    float volt = random(2000,2500) / 10.0; 
    float ampere = random(1,50) / 10.0; 
    String jsonPayload= "{\"volt\":" + String(volt, 2) + ",\"amp\":" + String(ampere, 1) +"}";
    // Send POST request
    int httpResponseCode = http.POST(jsonPayload);

    // Check the response
    if (httpResponseCode > 0) {
      Serial.println("POST Sent!");
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      Serial.print("Response payload: ");
      Serial.println(http.getString());
    } else {
      Serial.print("Error on sending POST: ");
      Serial.println(http.errorToString(httpResponseCode));
    }

    // End the HTTP connection
    http.end();
  } else {
    Serial.println("WiFi Disconnected!");
  }
}