Commit 28d12dfe authored by Ishankha K.C's avatar Ishankha K.C

Add arduino files

parent b117ac95
#include <WebServer.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <ESP32Servo.h>
#include <HTTPClient.h>
const char* WIFI_SSID = "SLT-Fiber-Home";
const char* WIFI_PASS = "Home@1122$1";
const char* DEVICE_ID = "8563efa6";
// Log types
const char* C_MOTION = "C_MOTION";
const char* C_WET = "C_WET";
// Server Base-Url
const char* SERVER_BASE_URL = "http://192.168.1.2:8080/api/v1/baby-care";
// Server Endpoints
const char* LOG_ENDPOINT = "/activity-logs/add";
const char* BABY_ENDPOINT = "/baby";
// motor pin
const int SERVO_MOTOR_PIN = 18;
// PIR sensor and LED pins
const int ledPin = 26; // LED pin
const int pirPin = 27; // PIR sensor pin
// Soil moisture pin
#define SOIL_MOISTURE_PIN 34
// angles
const int LEFT_ANGLE = 70;
const int RIGHT_ANGLE = 110;
// Speed delays in milliseconds for oscillation
const int LOW_SPEED_DELAY = 2000;
const int MEDIUM_SPEED_DELAY = 1000;
const int HIGH_SPEED_DELAY = 500;
Servo servo;
WebServer server(80);
bool isOscillating = false;
int currentDelay = MEDIUM_SPEED_DELAY; // Default to medium speed
// Function to handle the /servo endpoint logic
void handleServoControl() {
if (server.hasArg("plain")) {
String body = server.arg("plain");
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, body);
if (error) {
server.send(400, "application/json", "{\"error\":\"Invalid JSON\"}");
return;
}
int degree = doc["degree"];
if (degree < 0 || degree > 180) {
server.send(400, "application/json", "{\"error\":\"Degree must be between 0 and 180\"}");
return;
}
isOscillating = false; // Stop oscillation if manually setting position
servo.write(degree);
server.send(200, "application/json", "{\"status\":\"Servo moved to " + String(degree) + " degrees\"}");
} else {
server.send(400, "application/json", "{\"error\":\"No JSON body found\"}");
}
}
// Function to handle the /oscillate endpoint logic
void handleServoOscillating() {
if (server.hasArg("plain")) {
String body = server.arg("plain");
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, body);
if (error) {
server.send(400, "application/json", "{\"error\":\"Invalid JSON\"}");
return;
}
bool startOscillating = doc["start"];
isOscillating = startOscillating;
// Set speed based on the "speed" parameter
String speed = doc["speed"] | "medium"; // Default to medium if speed is not provided
if (speed == "low") {
currentDelay = LOW_SPEED_DELAY;
} else if (speed == "high") {
currentDelay = HIGH_SPEED_DELAY;
} else {
currentDelay = MEDIUM_SPEED_DELAY;
}
String status = isOscillating ? "Oscillation started at " + speed + " speed" : "Oscillation stopped";
server.send(200, "application/json", "{\"status\":\"" + status + "\"}");
} else {
server.send(400, "application/json", "{\"error\":\"No JSON body found\"}");
}
}
void connectToWiFi() {
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi.");
Serial.print("Access the server at: http://");
Serial.print(WiFi.localIP());
Serial.print("/" + String(DEVICE_ID));
Serial.println("");
Serial.println(" /servo");
Serial.println(" /oscillate");
}
// Cooldown settings
unsigned long lastMotionDetectedTime = 0;
const unsigned long motionCooldown = 5000; // Cooldown in milliseconds (e.g., 5000ms = 5 seconds)
// Handle motion detection
void motionDetection() {
// Check PIR sensor state
int pirState = digitalRead(pirPin);
unsigned long currentTime = millis();
if (pirState == HIGH) { // Motion detected
digitalWrite(ledPin, HIGH); // Turn on LED
// Check if cooldown has passed before sending log
if (currentTime - lastMotionDetectedTime >= motionCooldown) {
sendMotionDetectedLog(); // Call API to log motion
lastMotionDetectedTime = currentTime; // Reset cooldown timer
}
} else {
digitalWrite(ledPin, LOW); // Turn off LED
// Reset the last motion time if no motion is detected
lastMotionDetectedTime = 0;
}
}
// Send detected motion to server to save
void sendMotionDetectedLog() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(SERVER_BASE_URL) + LOG_ENDPOINT;
http.begin(url);
http.addHeader("Content-Type", "application/json");
// JSON payload
String payload = "{\"activityLogType\":\"" + String(C_MOTION) + "\",\"activityLogDescription\":\"Motion Detected.\"}";
// Send POST request
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
Serial.print("Log sent " + String(C_MOTION) + ", response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error in sending log " + String(C_MOTION) + ": ");
Serial.println(http.errorToString(httpResponseCode).c_str());
}
http.end();
} else {
Serial.println("WiFi not connected, unable to send log.");
}
}
unsigned long previousMillis = 0; // Stores the last time the moisture was read
const long interval = 1000; // Set delay interval in milliseconds (1 second)
const long notificationInterval = 5000; // Set notification interval in milliseconds (5 seconds)
bool isCradleWet = false; // Flag to track if the cradle is wet
unsigned long lastNotificationMillis = 0; // Timer for notifications
// Define the wet threshold percentage
const int WET_THRESHOLD = 15;
void measureWaterLevelOfCradle() {
unsigned long currentMillis = millis(); // Get the current time
// Check if the interval has elapsed
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis; // Update the last read time
int soilMoistureValue = analogRead(SOIL_MOISTURE_PIN); // Read the analog value
// Map the analog value to percentage
// Assuming 0 is completely dry and 4095 is completely wet
int moisturePercentage = map(soilMoistureValue, 0, 4095, 100, 0); // Invert percentage
// Serial.print("Soil Moisture Level: ");
// Serial.print(moisturePercentage);
// Serial.println("%"); // Print the moisture level as a percentage
// Check if the moisture level indicates the cradle is wet
if (moisturePercentage > WET_THRESHOLD) {
if (!isCradleWet) { // If cradle was previously not wet
isCradleWet = true; // Set the cradle as wet
Serial.println("Cradle is wet!"); // Log to the serial monitor
// Optionally trigger a notification or action here
// sendWetCradleNotification("Cradle is wet!"); // Function to handle wet cradle notification
}
// Handle repeated notifications every 5 seconds while the cradle is wet
if (currentMillis - lastNotificationMillis >= notificationInterval) {
lastNotificationMillis = currentMillis; // Update the notification timer
sendWetCradleNotification("Cradle is wet!"); // Send notification again
updateBabyDetails("wet");
}
} else {
// If moisture level is below threshold, reset wet status
if (isCradleWet) {
isCradleWet = false; // Set cradle as not wet
Serial.println("Cradle is dry again!"); // Log the status change
sendWetCradleNotification("Cradle is dry again!"); // Send notification cradle is dry again
updateBabyDetails("dry");
}
}
}
}
void updateBabyDetails(const char* status) {
StaticJsonDocument<300> babyDetailsDoc;
if (getBabyDetailsByDeviceId(babyDetailsDoc)) {
// Retrieve the baby ID as a long integer
long babyId = babyDetailsDoc["babyId"];
// Set the "wet" field based on the status
bool isWet = (strcmp(status, "wet") == 0);
babyDetailsDoc["wet"] = isWet;
// Serialize updated JSON document into a string
String updatePayload;
serializeJson(babyDetailsDoc, updatePayload);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(SERVER_BASE_URL) + BABY_ENDPOINT + "/" + String(babyId);
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.PUT(updatePayload);
if (httpResponseCode > 0) {
Serial.print("Update response code: ");
Serial.println(httpResponseCode);
// Serial.println(http.getString());
} else {
Serial.print("Error updating baby details: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi not connected.");
}
} else {
Serial.println("Failed to retrieve baby details.");
}
}
bool getBabyDetailsByDeviceId(JsonDocument& doc) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(SERVER_BASE_URL) + BABY_ENDPOINT + "/byDeviceId/" + DEVICE_ID;
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
// Serial.print("Baby details response: ");
// Serial.println(response);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print("JSON parse error: ");
Serial.println(error.c_str());
http.end();
return false;
}
} else {
Serial.print("Error getting baby details: ");
Serial.println(httpResponseCode);
http.end();
return false;
}
http.end();
return true;
} else {
Serial.println("WiFi not connected.");
return false;
}
}
// Function to handle notification for wet cradle
void sendWetCradleNotification(String activityLogDescription) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(SERVER_BASE_URL) + LOG_ENDPOINT;
http.begin(url);
http.addHeader("Content-Type", "application/json");
// JSON payload
String payload = "{\"activityLogType\":\"" + String(C_WET) + "\",\"activityLogDescription\":\"" + activityLogDescription + "\"}";
// Send POST request
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
Serial.print("Log sent " + String(C_WET) + ", response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error in sending log " + String(C_WET) + ": ");
Serial.println(http.errorToString(httpResponseCode).c_str());
}
http.end();
} else {
Serial.println("WiFi not connected, unable to send log.");
}
}
void setup() {
Serial.begin(115200);
// Set up LED and PIR sensor
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
pinMode(pirPin, INPUT); // Set the PIR pin as an input
digitalWrite(ledPin, LOW); // Ensure LED is off initially
// Set up Soil Moisture sensor
pinMode(SOIL_MOISTURE_PIN, INPUT);
servo.attach(SERVO_MOTOR_PIN);
connectToWiFi();
// Endpoint to set the servo position manually
server.on("/" + String(DEVICE_ID) + "/servo", HTTP_POST, handleServoControl);
// Endpoint to start or stop oscillation
server.on("/" + String(DEVICE_ID) + "/oscillate", HTTP_POST, handleServoOscillating);
server.begin();
}
void loop() {
server.handleClient();
// Check PIR sensor state
motionDetection();
// Check water level of cradle
measureWaterLevelOfCradle();
// Handle oscillation when enabled
if (isOscillating) {
servo.write(LEFT_ANGLE);
delay(currentDelay);
servo.write(RIGHT_ANGLE);
delay(currentDelay);
}
}
#include <WebServer.h>
#include <WiFi.h>
#include <esp32cam.h>
#include <time.h>
#include <ArduinoJson.h>
const char* WIFI_SSID = "SLT-Fiber-Home";
const char* WIFI_PASS = "Home@1122$1";
const char* DEVICE_ID = "8563efa6";
// Flashlight pin
const int FLASHLIGHT_PIN = 4;
// Time interval to consider as daytime or nighttime
const int DAY_START_HOUR = 6; // 6 AM
const int NIGHT_START_HOUR = 18; // 6 PM
// Time zone offset (5 hours 30 minutes) in seconds
const int TIME_ZONE_OFFSET = 5 * 3600 + 30 * 60;
WebServer server(80);
static auto loRes = esp32cam::Resolution::find(320, 240);
static auto midRes = esp32cam::Resolution::find(350, 530);
static auto hiRes = esp32cam::Resolution::find(800, 600);
void serveJpg()
{
auto frame = esp32cam::capture();
if (frame == nullptr) {
Serial.println("CAPTURE FAIL");
server.send(503, "", "");
return;
}
Serial.printf("CAPTURE OK %dx%d %db\n", frame->getWidth(), frame->getHeight(),
static_cast<int>(frame->size()));
server.setContentLength(frame->size());
server.send(200, "image/jpeg");
WiFiClient client = server.client();
frame->writeTo(client);
}
void handleJpgLo()
{
if (!esp32cam::Camera.changeResolution(loRes)) {
Serial.println("SET-LO-RES FAIL");
}
serveJpg();
}
void handleJpgHi()
{
if (!esp32cam::Camera.changeResolution(hiRes)) {
Serial.println("SET-HI-RES FAIL");
}
serveJpg();
}
void handleJpgMid()
{
if (!esp32cam::Camera.changeResolution(midRes)) {
Serial.println("SET-MID-RES FAIL");
}
serveJpg();
}
// API handler to turn the flashlight on
void handleFlashlightOn()
{
digitalWrite(FLASHLIGHT_PIN, HIGH);
// Create a JSON document
StaticJsonDocument<200> jsonDoc;
jsonDoc["status"] = "ON";
jsonDoc["message"] = "Flashlight turned ON";
// Serialize JSON document to a string
String response;
serializeJson(jsonDoc, response);
// Send the JSON response
server.send(200, "application/json", response);
}
// API handler to turn the flashlight off
void handleFlashlightOff()
{
digitalWrite(FLASHLIGHT_PIN, LOW);
// Create a JSON document
StaticJsonDocument<200> jsonDoc;
jsonDoc["status"] = "OFF";
jsonDoc["message"] = "Flashlight turned OFF";
// Serialize JSON document to a string
String response;
serializeJson(jsonDoc, response);
// Send the JSON response
server.send(200, "application/json", response);
}
void setup(){
Serial.begin(115200);
Serial.println();
pinMode(FLASHLIGHT_PIN, OUTPUT);
digitalWrite(FLASHLIGHT_PIN, LOW); // Ensure flashlight is off initially
{
using namespace esp32cam;
Config cfg;
cfg.setPins(pins::AiThinker);
cfg.setResolution(hiRes);
cfg.setBufferCount(2);
cfg.setJpeg(80);
bool ok = Camera.begin(cfg);
Serial.println(DEVICE_ID);
Serial.println(ok ? "CAMERA OK" : "CAMERA FAIL");
}
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("");
Serial.print("Connecting to WiFi.");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.print("/" + String(DEVICE_ID));
Serial.println("");
Serial.println(" /cam-lo.jpg");
Serial.println(" /cam-hi.jpg");
Serial.println(" /cam-mid.jpg");
Serial.println(" /flashlight/on");
Serial.println(" /flashlight/off");
server.on("/"+String(DEVICE_ID)+"/cam-lo.jpg", handleJpgLo);
server.on("/"+String(DEVICE_ID)+"/cam-hi.jpg", handleJpgHi);
server.on("/"+String(DEVICE_ID)+"/cam-mid.jpg", handleJpgMid);
server.on("/"+String(DEVICE_ID)+"/flashlight/on", handleFlashlightOn);
server.on("/"+String(DEVICE_ID)+"/flashlight/off", handleFlashlightOff);
server.begin();
// Initialize time
configTime(0, 0, "pool.ntp.org");
}
unsigned long lastPrintTime = 0; // Last time the time was printed
const unsigned long printInterval = 10000; // Interval to print time (10 seconds)
void loop()
{
server.handleClient();
unsigned long currentMillis = millis();
if (currentMillis - lastPrintTime >= printInterval) {
// It's been 10 seconds, so print the time
struct tm timeinfo;
if (getLocalTime(&timeinfo)) {
// Adjust time for GMT+5:30
timeinfo.tm_hour += 5;
timeinfo.tm_min += 30;
if (timeinfo.tm_min >= 60) {
timeinfo.tm_min -= 60;
timeinfo.tm_hour++;
}
if (timeinfo.tm_hour >= 24) {
timeinfo.tm_hour -= 24;
}
int hour = timeinfo.tm_hour;
int minute = timeinfo.tm_min;
int second = timeinfo.tm_sec;
// Print the adjusted time
Serial.printf("Time: %02d:%02d:%02d\n", hour, minute, second);
} else {
Serial.println("Failed to obtain time");
}
// Update the last print time
lastPrintTime = currentMillis;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment