Hello
I am using esp32 along with temperature and accelerometer to sense and store the data in arrays which are then sent to a server through http post method and on the server side the index.php handles the data and saves it to files.
Now I want to send a string along with this data to the server which contains the OTA url generated in the code through which we can upload code to the esp32 in the future.
I don't understand how should i do it. I tried this but it gives me error.
void sendDataToServer(const String& payload, const String& url ) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload, url);
Can anybody help me with how should i modify the code to send the URL as a string separately along with the data I am sending?
here is the full code:
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <Temperature_LM75_Derived.h>
#include <WiFi.h>
#include <NTPClient.h>
#include <HTTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
#include <Preferences.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
String url;
const int batteryPin = 34 ; // Analog input pin for battery voltage measurement
const float batteryMaxVoltage = 4.2; // Maximum voltage of the battery
const float batteryMinVoltage = 2.8; // Minimum voltage of the battery
const char* ntpServer = "pool.ntp.org";
const long gmtOffset = 18000;
const int daylightOffset = 0;
const int intervalDuration = 60; // Duration of the interval in seconds
const int bufferSize = intervalDuration; // Total buffer size
Adafruit_MPU6050 mpu;
Generic_LM75 LM75;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, ntpServer, gmtOffset, daylightOffset);
WebServer server(80);
const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
// Circular buffer size
// const int bufferSize = 6; // Store 6 entries within a 1-minute interval
// Data structure to store sensor readings
struct SensorData {
float accelerationX;
float accelerationY;
float accelerationZ;
float temperature;
float batteryVoltage;
float batteryPercentage;
String timestamp;
};
// Circular buffer to store sensor data
SensorData circularBuffer[bufferSize];
int bufferIndex = 0;
// Timer variables
unsigned long previousMillis = 0;
bool isIntervalCompleted = false;
void handleUpdate() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected! IP Address: ");
Serial.println(WiFi.localIP());
// Initialize NTP
timeClient.begin();
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
Wire.begin();
delay(100);
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
server.on("/update", HTTP_POST, handleUpdate, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
});
server.begin();
MDNS.begin("esp32-webupdate");
MDNS.addService("http", "tcp", 80);
url = String("http://") + "esp32-webupdate.local/";
Serial.printf("Ready! Open %s in your browser\n", url.c_str());
}
void loop() {
server.handleClient();
timeClient.update(); // Update the time from the NTP server
// Store data in circular buffer
circularBuffer[bufferIndex].accelerationX = a.acceleration.x;
circularBuffer[bufferIndex].accelerationY = a.acceleration.y;
circularBuffer[bufferIndex].accelerationZ = a.acceleration.z;
circularBuffer[bufferIndex].temperature = tempC;
circularBuffer[bufferIndex].timestamp = getCurrentDateTime();
circularBuffer[bufferIndex].batteryVoltage = batteryVoltage;
circularBuffer[bufferIndex].batteryPercentage = batteryPercentage;
// Update buffer index
bufferIndex = (bufferIndex + 1) % bufferSize;
// Check if the interval is completed
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= intervalDuration * 1000) { // Interval time (60 seconds)
previousMillis = currentMillis;
isIntervalCompleted = true;
}
// Create the JSON payload with timestamp and sensor data
if (isIntervalCompleted) {
isIntervalCompleted = false;
// Bulk payload
String bulkPayload = "[";
for (int i = 0; i < bufferSize; i++) {
int index = (bufferIndex + i) % bufferSize;
// Check if the timestamp is empty or all data values are zero
if (circularBuffer[index].timestamp != "" &&
(circularBuffer[index].temperature != 0.0 ||
circularBuffer[index].accelerationX != 0.0 ||
circularBuffer[index].accelerationY != 0.0 ||
circularBuffer[index].accelerationZ != 0.0 ||
circularBuffer[index].batteryVoltage != 0.0 ||
circularBuffer[index].batteryPercentage != 0.0 )) {
// Single payload object
String payload = "{\"timestamp\":\"";
payload += circularBuffer[index].timestamp;
payload += "\",\"temp\":";
payload += circularBuffer[index].temperature;
payload += ",\"accel_x\":";
payload += circularBuffer[index].accelerationX;
payload += ",\"accel_y\":";
payload += circularBuffer[index].accelerationY;
payload += ",\"accel_z\":";
payload += circularBuffer[index].accelerationZ;
payload += ",\"battery_voltage\":";
payload += circularBuffer[index].batteryVoltage;
payload += ",\"battery_percentage\":";
payload += circularBuffer[index].batteryPercentage;
payload += "}";
// Add payload object to bulk payload
bulkPayload += payload;
if (i < bufferSize - 1) {
bulkPayload += ",";
}
// Print each data point on a separate line
bulkPayload += "\n";
}
}
bulkPayload += "]";
Serial.println(bulkPayload);
if (WiFi.status() == WL_CONNECTED) {
sendDataToServer(url, bulkPayload);
} else {
connectToWiFi();
sendDataToServer(url,bulkPayload);
disconnectFromWiFi();
}
// Clear stored data
memset(circularBuffer, 0, sizeof(circularBuffer));
bufferIndex = 0;
}
delay(10000); // Adjust the delay according to your requirements
}
void connectToWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected! IP Address: ");
Serial.println(WiFi.localIP());
}
void disconnectFromWiFi() {
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void sendDataToServer(const String& payload) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload, url);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
if (httpResponseCode == HTTP_CODE_OK) {
// Data successfully sent to the server
Serial.println("Data sent to server successfully");
} else {
// Error sending data to the server
Serial.println("Error sending data to the server");
}
} else {
// Error making the HTTP request
Serial.println("Error sending HTTP request");
}
http.end();
}
String getCurrentDateTime() {
time_t now = timeClient.getEpochTime();
struct tm* timeinfo;
timeinfo = localtime(&now);
char dateTime[20];
sprintf(dateTime, "%04d-%02d-%02dT%02d:%02d:%02d",
timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday,
timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
return String(dateTime);
}