#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <BluetoothSerial.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
BluetoothSerial SerialBT;
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverURL = "http://your_server_url.com/post_data_endpoint";
const float R1 = 15000.0; // Value of R1 in ohms (15K)
const float R2 = 4700.0; // Value of R2 in ohms (4.7K)
float I = 0.0; // Initialize 'I' with a default value
// Define NTP settings
const char* ntpServer = "pool.ntp.org";
const int utcOffset = 0; // UTC offset in seconds
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, ntpServer, utcOffset);
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32_BT"); // Bluetooth device name
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize the NTP client and set the time update interval (in seconds)
timeClient.begin();
timeClient.update();
}
void loop() {
// Update the NTP time client
timeClient.update();
if (SerialBT.available()) {
// If there's Bluetooth data available, read 'I' value
I = SerialBT.parseFloat();
Serial.print("Received I: ");
Serial.println(I);
calculateAndPost(I);
}
}
void calculateAndPost(float I) {
float V = I * (R1 + R2);
Serial.print("Calculated Voltage (V): ");
Serial.println(V);
// Get the current timestamp from the NTP client
String timestamp = timeClient.getFormattedTime();
WiFiClient client;
HTTPClient http;
String serverResponse;
// Create a JSON object with the provided structure, including the timestamp
StaticJsonDocument<400> jsonDoc;
jsonDoc["device"] = "XC015145";
jsonDoc["gsmgateway"] = "XC015145";
jsonDoc["timestamp"] = timestamp;
JsonArray data = jsonDoc.createNestedArray("data");
data.add("ANA-MACADDRESS-RTCTIMESTAMP-" + String(V, 2)); // Adjust the format as needed
if (http.begin(client, serverURL)) {
http.addHeader("Content-Type", "application/json");
serializeJson(jsonDoc, client);
int httpResponseCode = http.POST(serverResponse);
if (httpResponseCode > 0) {
Serial.print("HTTP Response Code: ");
Serial.println(httpResponseCode);
Serial.print("Server Response: ");
Serial.println(serverResponse);
} else {
Serial.print("Error in HTTP POST request. Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Failed to connect to the server");
}
}