/*

  Example of writing info to Google Sheets over wifi.

  Original Source: https://www.youtube.com/watch?v=u7TYu61l0t4

*/

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

// Defining LED PINs on the ESP32 Board.
const int LED_PIN = 10;
const int VAL1_POT_PIN = 2;
const int VAL2_POT_PIN = 3;

// Google script Web_App_URL.
const String WEB_APP_URL = "PUT URL TO YOUR GOOGLE APPS SCRIPT HERE";
const String SHEET_NAME = "Scratch";

void setup() {
  Serial.begin(115200);
  Serial.println();

  pinMode(LED_PIN, OUTPUT);
  pinMode(VAL1_POT_PIN, INPUT);
  pinMode(VAL2_POT_PIN, INPUT);

  WiFi.mode(WIFI_STA);
  Serial.print("Connecting to WiFi");
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected.");
  Serial.println("------------");

  digitalWrite(LED_PIN, LOW);
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(LED_PIN, HIGH);

    // Create a URL for sending or writing data to Google Sheets.
    String Send_Data_URL = WEB_APP_URL + "?sts=write";
    Send_Data_URL += "&sheet=" + SHEET_NAME;
    Send_Data_URL += "&val1=" + (String)analogRead(VAL1_POT_PIN);
    Send_Data_URL += "&val2=" + (String)analogRead(VAL2_POT_PIN);

    Serial.println();
    Serial.println("-------------");
    Serial.println("Send data to Google Spreadsheet...");
    Serial.print("URL : ");
    Serial.println(Send_Data_URL);

    // Writing data to Google Sheets.
    HTTPClient http;

    // HTTP GET Request.
    http.begin(Send_Data_URL.c_str());
    http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);

    // Gets the HTTP status code.
    int httpCode = http.GET();
    Serial.print("HTTP Status Code : ");
    Serial.println(httpCode);

    // Getting response from google sheets.
    String payload;
    if (httpCode > 0) {
      payload = http.getString();
      Serial.println("Response: " + payload);
    }

    http.end();

    digitalWrite(LED_PIN, LOW);
    Serial.println("-------------");
  }

  // Save every 10 seconds. Adjust to frequency desired. This is a blocking delay for simplicity, switch
  // to millis() mechanisim or simular if need to do other processing between writes. 
  delay(10000);
}