#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// REPLACE THIS WITH YOUR NEW DEPLOYMENT URL (Ends in /exec)
const char* SCRIPT_URL = "https://script.google.com/macros/s/AKfycbxX9SU3DP1m9vcRi5rDnqEwG_OatYU3EWXHGgpUSkxh53KIXRwtOupyYdVM_UolxP5y/exec";
// Define the headers we want to capture
const char* headerKeys[] = {"Location"};
void setup() {
Serial.begin(115200);
delay(2000);
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
}
void loop() {
// 1️⃣ Create JSON payload
StaticJsonDocument<256> doc;
doc["rmsACVoltage"] = random(100, 200);
doc["ChargingVoltage"] = random(10, 20);
doc["BatteryVoltage"] = random(12, 18);
String payload;
serializeJson(doc, payload);
Serial.println("\n--- Starting Request ---");
Serial.println("Payload: " + payload);
// 2️⃣ Setup HTTPS client
WiFiClientSecure client;
client.setInsecure();
client.setTimeout(15000);
HTTPClient http;
Serial.println("Sending POST...");
if (http.begin(client, SCRIPT_URL)) {
http.addHeader("Content-Type", "application/json");
// CRITICAL FIX 1: Tell library to collect the "Location" header
http.collectHeaders(headerKeys, 1);
// CRITICAL FIX 2: Disable Auto Redirects
http.setFollowRedirects(HTTPC_DISABLE_FOLLOW_REDIRECTS);
int httpCode = http.POST(payload);
if (httpCode == 302) {
// Now this should actually return the string!
String newUrl = http.header("Location");
Serial.println("✔ POST Accepted! (Received 302)");
Serial.println(" Redirecting to: " + newUrl);
http.end(); // Close old connection
if (newUrl.length() > 5) { // Basic validation
Serial.println(" Following redirect...");
http.begin(client, newUrl);
int newCode = http.GET();
if (newCode == 200) {
Serial.println("✔ Final Success: " + http.getString());
} else {
Serial.print("❌ Redirect Failed. Code: ");
Serial.println(newCode);
Serial.println("Response: " + http.getString());
}
http.end();
} else {
Serial.println("❌ Error: 'Location' header was empty or invalid.");
}
}
else if (httpCode == 200) {
Serial.println("✔ Success (No redirect): " + http.getString());
http.end();
}
else {
Serial.print("❌ HTTP Error: ");
Serial.println(httpCode);
if(httpCode > 0) Serial.println("Response: " + http.getString());
http.end();
}
} else {
Serial.println("Unable to connect to server");
}
Serial.println("Waiting 10 seconds...");
delay(10000);
}
// #include <WiFi.h>
// #include <HTTPClient.h>
// #include <ArduinoJson.h>
// #include <WiFiClientSecure.h>
// const char* ssid = "Wokwi-GUEST";
// const char* password = "";
// // Use the "exec" deployment URL of your Google Apps Script
// const char* SCRIPT_URL = "https://script.google.com/macros/s/AKfycbypZ7ctJCJQozt5PAYS48EzttFf6JhDQqDo482stLQPMRclpYKR7ncfqSqSLS3QErG1Ww/exec";
// void setup() {
// Serial.begin(115200);
// Serial.println("Connecting to Wi-Fi...");
// WiFi.begin(ssid, password);
// while (WiFi.status() != WL_CONNECTED) {
// delay(500);
// Serial.print(".");
// }
// Serial.println("\nWiFi connected!");
// Serial.print("IP address: ");
// Serial.println(WiFi.localIP());
// }
// void loop()
// {
// // 1️⃣ Create JSON payload
// StaticJsonDocument<256> doc;
// doc["rmsACVoltage"] = random(100, 200);
// doc["ChargingVoltage"] = random(10, 20);
// doc["BatteryVoltage"] = random(12, 18);
// String payload;
// serializeJson(doc, payload);
// Serial.println("Sending payload: " + payload);
// // 2️⃣ Setup HTTPS client
// WiFiClientSecure client;
// client.setInsecure(); // Trust Google without certificate
// HTTPClient http;
// http.begin(client, SCRIPT_URL);
// http.addHeader("Content-Type", "application/json");
// // ====================================================================
// // THE FIX: Use STRICT mode to let the library handle the redirect.
// // This mode correctly switches from POST to GET, which HTTPC_FORCE
// // often fails to do.
// http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
// // ====================================================================
// // 3️⃣ POST request (The library will now handle the 302->GET chain)
// int httpCode = http.POST(payload);
// if (httpCode > 0) {
// Serial.print("HTTP Response Code: ");
// Serial.println(httpCode);
// String response = http.getString();
// // The final code should be 200 OK after the redirect is handled.
// if (httpCode == 200) {
// Serial.println("Final Response: " + response);
// StaticJsonDocument<128> respDoc;
// DeserializationError err = deserializeJson(respDoc, response);
// if (!err) {
// const char* status = respDoc["status"];
// const char* message = respDoc["message"];
// if (status) {
// if (strcmp(status, "success") == 0) Serial.println("✔ Server acknowledged success!");
// else if (strcmp(status, "warning") == 0) Serial.print("⚠ Server warning: "), Serial.println(message ? message : "No message");
// else if (strcmp(status, "error") == 0) Serial.print("❌ Server error: "), Serial.println(message ? message : "No message");
// else Serial.println("⚠ Unexpected server status!");
// }
// } else {
// Serial.println("⚠ Failed to parse server JSON response!");
// }
// } else {
// Serial.println("⚠ Server returned non-JSON response:");
// Serial.println(response);
// }
// } else {
// Serial.print("HTTP Request failed: ");
// Serial.println(http.errorToString(httpCode));
// }
// http.end();
// delay(10000); // Wait 10 seconds before sending next payload
// }
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4