#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

// GPIO where the DS18B20s are connected
const int oneWireBus = 12;

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

// Google Sheets API details
const char* google_script_id = "AKfycbzqP-j1L4cLd2TkbbbYWMGUI7_q09IZqja56CQ9RQrjCrRYBax08MNN2u6101fmSKAPSA";

// Setup a oneWire instance to communicate with OneWire devices
OneWire oneWire(oneWireBus);

// Pass the oneWire reference to DallasTemperature sensor
DallasTemperature sensors(&oneWire);

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);

  // Start the DS18B20 sensors
  sensors.begin();

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  // Request temperature readings from all sensors
  sensors.requestTemperatures();

  // Prepare the data to be sent
  String data = "";
  data += "timestamp=" + String(millis()) + "&";

  for (int i = 0; i < sensors.getDeviceCount(); i++) {
    float temperatureC = sensors.getTempCByIndex(i);
    data += "sensor" + String(i+1) + "=" + String(temperatureC) + "&";
  }

  // Remove the last '&'
  data = data.substring(0, data.length() - 1);

  // Send data to Google Sheets
  sendToGoogleSheets(data);

  delay(10000); // Delay for 10 seconds
}

void sendToGoogleSheets(String data) {
  WiFiClientSecure client;
  HTTPClient http;

  client.setInsecure();
  String url = String("https://script.google.com/macros/s/") + google_script_id + "/exec?" + data;

  http.begin(client, url);
  int httpCode = http.GET();

  if (httpCode > 0) {
    String payload = http.getString();
    Serial.println("Data sent successfully");
  } else {
    Serial.println("Error in sending data");
  }

  http.end();
}