#define BLYNK_TEMPLATE_ID "TMPL2o2SqlCwx"
#define BLYNK_TEMPLATE_NAME "Quickstart Template"
#define BLYNK_AUTH_TOKEN "ctuVteBw_QTpAOSQcU5f3Z34IiO0CdjU"
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <BlynkSimpleEsp32.h>
#include <HTTPClient.h>
#include <EmonLib.h> // Include Emon Library
#include <time.h> // Include time library for timestamp
#include <ArduinoJson.h> // Include ArduinoJson library for JSON parsing and serialization
// Your WiFi credentials
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// Your Blynk Auth Token
char auth[] = "ctuVteBw_QTpAOSQcU5f3Z34IiO0CdjU";
// Appwrite configuration
const char* appwriteHost = "cloud.appwrite.io";
const char* projectID = "66ad2625001249bd442c";
const char* collectionID = "66ad2db100146cb4e965";
const char* databaseID = "66ad2c74001a1bc74f45";
const char* apiKey = "c82a5f96d2690914c4524bed259b33fe68b83243289a42843f581ac53c3108e7f667c5154f5d36de6168045102d9a05b8a6cc03e5978a6584f063cfbea4d15c6d8c869a9bc3d3499f00318e086e498b6df9d40f9b8d1b7996cadfedb687645c5b359c40e027011b7df381b30d0648ac0bc31c970b9a16f53fa73314bf5c64d40";
const char* secondCollectionID = "66ad2cb5002b7c3a820b";
// Create an instance of the Emon class
EnergyMonitor emon1;
unsigned long lastMillis = 0;
float energy = 0.0; // Total energy in watt-seconds (Joules)
bool deviceStatus = false; // Device status: true for ON, false for OFF
void setup() {
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
// Initialize the Emon library
emon1.voltage(12, 255.47, 1.7); // Voltage: input pin, calibration, phase_shift
emon1.current(12, 77); // Current: input pin, calibration
// Initialize time
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
while (!time(nullptr)) {
Serial.println("Waiting for time synchronization...");
delay(1000);
}
// Push initial device status to Appwrite (second collection)
String deviceId = "Smart Switch"; // Use the current timestamp as a unique ID
String timestamp = getFormattedTime(); // Get the formatted timestamp
String userId = "your_user_id"; // User ID from Appwrite (hardcoded for now, replace with actual logic to retrieve user ID)
sendDataToAppwrite(deviceId, userId, deviceStatus, timestamp);
}
String getFormattedTime() {
time_t now = time(nullptr);
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
char buffer[25];
strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", &timeinfo);
return String(buffer);
}
void sendDataToAppwrite(const String& deviceId, const String& userId, bool status, const String& timestamp) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String("https://") + appwriteHost + "/v1/databases/" + String(databaseID) + "/collections/" + String(secondCollectionID) + "/documents";
http.begin(url);
http.addHeader("Content-Type", "application/json");
http.addHeader("X-Appwrite-Project", projectID);
http.addHeader("X-Appwrite-Key", apiKey);
String jsonPayload = "{\"documentId\": \"unique()\", \"data\": {\"deviceName\": \"" + deviceId + "\", \"userId\": \"" + userId + "\", \"status\": " + (status ? "true" : "false") + "}}";
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Error in WiFi connection");
}
}
void loop() {
Blynk.run();
// Calculate all. No.of crossings, time-out
emon1.calcVI(20, 2000);
float voltage = emon1.Vrms; // Extract Vrms value
float current = emon1.Irms; // Extract Irms value
float power = emon1.realPower; // Extract real power value
// float powerFactor = emon1.powerFactor; // Extract power factor value
// Calculate energy
unsigned long currentMillis = millis();
float deltaTime = (currentMillis - lastMillis) / 1000.0; // Time in seconds since last measurement
lastMillis = currentMillis;
energy += power * deltaTime; // Increment total energy by power * time interval
// Send data to Blynk
Blynk.virtualWrite(V4, voltage);
Blynk.virtualWrite(V0, current);
Blynk.virtualWrite(V1, power);
Blynk.virtualWrite(V3, energy);
// Blynk.virtualWrite(V5, powerFactor);
// Generate a unique measurement ID
String deviceId = "Smart Switch"; // Use the current timestamp as a unique ID
String timestamp = getFormattedTime(); // Get the formatted timestamp
int price = 2000;
// Device status (ON/OFF)
bool status = deviceStatus;
// Send data to Appwrite (first collection)
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String("https://") + appwriteHost + "/v1/databases/" + String(databaseID) + "/collections/" + String(collectionID) + "/documents";
http.begin(url);
http.addHeader("Content-Type", "application/json");
http.addHeader("X-Appwrite-Project", projectID);
http.addHeader("X-Appwrite-Key", apiKey);
String jsonPayload = "{\"documentId\": \"unique()\", \"data\": {\"deviceId\": \"" + deviceId + "\", \"timestamp\": \"" + timestamp + "\", \"voltage\": " + String(voltage) +
", \"current\": " + String(current) +
", \"power\": " + String(power) +
",\"price\": " + String(price) +
", \"energy\": " + String(energy) +
"}}";
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Error in WiFi connection");
}
Serial.print("Voltage: ");
Serial.print(voltage);
Serial.print(" V, Current: ");
Serial.print(current);
Serial.print(" A, Power: ");
Serial.print(power);
Serial.print(" W, Energy: ");
Serial.print(energy);
Serial.print(" Joules, Status: ");
Serial.println(status ? "ON" : "OFF");
delay(500); // Wait half a second before taking another reading
}