//------INCLUDE HEADER FUNCTIONS-----
#include <WiFi.h> //Using WiFi Library
#include <PubSubClient.h> //Using MQTT Library
#include <HTTPClient.h>
#define RELAY_PIN 2 // ESP32 Pin GIOP2 Connected to the IN pin of the RELAY
#include "time.h"
float time1 = 0;
float waterbill;
// Variables to store water usage data
unsigned long startTime;
unsigned long endTime;
unsigned long totalWaterUsed;
void callback(char* subscribetopic, byte* payload, unsigned int payloadLength);
//------CREDENTIALS OF IBM CLOUD WATSON ACCOUNTS------
#define ORG "7rql44" //IBM ORGANITION ID
#define DEVICE_TYPE "SMART" // Device type mentioned in IBM WATSON IOT platform
#define DEVICE_ID "123456" //Device ID mentioned in IBM WATSON IOT platform
#define TOKEN "12345678" // Device TOKEN mentioned in IBM WATSON platform
String data3;
const char* ntpServer = "pool.ntp.org";
const long gmtoffset_sec = 0;
const int daylightoffset_sec = 3600;
//-----CUSTOMISE THE ABOVE VALUES-----
char server[] =ORG ".messaging.internetofthings.ibmcloud.com"; //Server name
char publishTopic[] = "iot-2/evt/Data/fmt/json"; //Topic name and type of event perform and format in which data to be send
char subscribetopic[] = "iot-2/cmd/command/fmt/String"; //CMD represent command type and cammand is test of format string
char authMethod[] = "use-token-auth"; //Authentication method
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID; //client id
//-----
WiFiClient wifiClient; //Creating the instance for wificlient
PubSubClient client(server, 1883, callback ,wifiClient); //Calling the predefined client id by passing parameter like server id,portand wificredential
/*//The setup function runs once when you press reset or power the board
void setup()
{
//Initialize digital pin as an output
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
delay(10);
configTime(gmtoffset_sec, daylightoffset_sec, ntpServer);
wificonnect();
mqttconnect();
}
//The loop function runs over and over again forever
void loop()
{
digitalWrite(RELAY_PIN, HIGH);
delay(1000);
digitalWrite(RELAY_PIN, LOW);
delay(1000);
waterbill = random(60,200);
waterbill = waterbill*5;
delay(1000);
publishData(waterbill);
if(!client.loop())
{
mqttconnect();
}
}
//PUBLISHING THE WATERBILL
void publishData(float waterbill)
{
mqttconnect(); //Function call for connecting to IBM
String payload = "{\"waterbill\":"; //Creating the string in form JSon to update to IBM CLOUD
payload += waterbill;
payload += "}";
Serial.print("Sending payload: ");
Serial.println(payload);
if(client.publish(publishTopic, (char*) payload.c_str()))
{
Serial.println("Publish Ok"); //Successfully upload to IBM CLOUD
}else{
Serial.println("Publish Failed"); //Failed to upload to IBM CLOUD
}
}*/
//CONNECT THE CODE THROUGH MQTT
void mqttconnect()
{
if(!client.connected())
{
Serial.print("Reconnecting client to "); //Reconnect the code to IBM CLOUD
Serial.print(server);
while(!!!client.connect(clientId, authMethod, token))
{
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
//CONNECT TO WIFI
void wificonnect()
{
Serial.println();
Serial.print("Connecting to "); //Connecting to WIFI
WiFi.begin("Wokwi-GUEST", "", 6); //Passing the WIFI credentials
while(WiFi.status() !=WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void initManagedDevice()
{
if(client.subscribe(subscribetopic))
{
Serial.println((subscribetopic));
Serial.println("Subscribe to CMD ok"); //Successfully subscribe to CMD
}else{
Serial.println("Subscribe to CMD Failed"); //Failed to subscribe to CMD
}
}
/*void callback(char* subscribetopic, byte* payload, unsigned int payloadLength)
{
Serial.print("callback invoked for topic: ");
Serial.println(subscribetopic);
for(int i = 0; i < payloadLength; i++)
{
data3 += (char)payload[i];
}
Serial.println("data: "+ data3);
if(data3 == "on")
{
Serial.println(data3);
digitalWrite(RELAY_PIN, HIGH);
publishData(0);
Serial.println("The time at wshich the motor is switched on: ");
printLocalTime();
time1 += 1;
}
else if(data3 == "off")
{
Serial.println(data3);
digitalWrite(RELAY_PIN, LOW);
waterbill = random(60,200);
waterbill = waterbill*5;
delay(1000);
printLocalTime();
time1 = 0;
}
data3 = "";
}
void printLocalTime()
{
struct tm* timeinfo;
time_t now;
time(&now);
timeinfo = localtime(&now);
Serial.print(timeinfo,"%H:%M:%S");
Serial.println("Hour: ");
Serial.println(timeinfo, "%H");
Serial.println("Hour (12 hour format): ");
Serial.println("Minute: ");
Serial.println(timeinfo, "%M");
Serial.println("Second: ");
Serial.println(timeinfo, "%S");
}*/
// Calculate water bill based on usage
float calculateWaterBill(unsigned long waterUsed) {
// Implement your own billing logic here
// This is just a placeholder calculation
float bill = waterUsed * 0.001; // Assuming 1 liter of water costs 0.001 units
return bill;
}
void sendDataToWatson(float waterBill, unsigned long waterUsed, unsigned long duration) {
WiFiClient client;
HTTPClient http;
String url = "http://" + String(server) + ":" + String(DEVICE_ID) + "/events/water-usage";
String payload = "{ \"water_bill\": " + String(waterBill) + ", \"water_used\": " + String(waterUsed) + ", \"duration\": " + String(duration) + " }";
http.begin(client, url);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer " + String(token));
int httpResponseCode = http.POST(payload);
if (httpResponseCode == 200) {
Serial.println("Data sent to Watson successfully");
} else {
Serial.print("Error sending data to Watson. Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
void setup() {
Serial.begin(115200);
// Set the relay pin as output
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
wificonnect();
}
void loop() {
if (Serial.available()) {
char command = Serial.read();
if (command == '1') {
// Store the start time
startTime = millis();
// Turn on the relay
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Water supply turned on");
} else if (command == '0') {
// Store the end time
endTime = millis();
// Turn off the relay
digitalWrite(RELAY_PIN, LOW);
// Calculate the water used
totalWaterUsed += endTime - startTime;
// Calculate the water bill
float bill = calculateWaterBill(totalWaterUsed);
Serial.println("Water supply turned off");
Serial.println("Total water used: " + String(totalWaterUsed) + " liters");
Serial.println("Water bill: $" + String(bill));
// Send data to IBM Watson Cloud
sendDataToWatson(bill, totalWaterUsed, endTime - startTime);
}
}
}