Smart Home Guardian + AI Intruder Detector

Smart Home Guardian + AI Intruder Detector

Two Integrated Projects in C++ and Robotic Sensors

This project is a fusion of two powerful systems developed using C++ and Raspberry Pi:

  1. Smart Home Guardian – a real-time monitoring and alert system.

  2. AI-Powered Intruder Detector – an analysis-driven system that flags suspicious activity using basic AI logic.


Program 1: Smart Home Guardian

Main System

This system provides real-time monitoring using various sensors. The Raspberry Pi runs a C++ program that interfaces with sensors and triggers GPIO-based outputs like buzzers or LEDs.

Components Used:

  • PIR Motion Sensor – to detect any movement.

  • DHT11 Sensor – to monitor room temperature and humidity.

  • MQ2 Gas Sensor – for detecting gas leaks or smoke.

  • LDR (via MCP3008 ADC) – to measure light levels.

  • LEDs & Buzzers – for visual and sound alerts.

  • MySQL Database – for storing logs of sensor readings.

  • Python Script – to read DHT11 values.

How It Works:

  • C++ handles real-time sensor reading and alert triggering.

  • Python assists in reading DHT11 data.

  • All readings (motion, temp, humidity, light) are stored in a MySQL database.

  • GPIO is used for input/output control.


Directory Structure:

smart_home_guardian/
│
├── main.cpp
├── dht_reader.py  # Python helper for DHT11
└── CMakeLists.txt

main.cpp (C++ Code)

#include <wiringPi.h>
#include <mysql/mysql.h>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>

#define PIR_PIN 0        // GPIO 17
#define BUZZER_PIN 1     // GPIO 18

int read_mcp3008(int channel) {
    int fd = open("/dev/spidev0.0", O_RDWR);
    if (fd < 0) {
        perror("SPI device open failed");
        return -1;
    }

    uint8_t tx[] = {1, (8 + channel) << 4, 0};
    uint8_t rx[3] = {0};

    struct spi_ioc_transfer tr = {
        .tx_buf = (unsigned long)tx,
        .rx_buf = (unsigned long)rx,
        .len = 3,
        .speed_hz = 1000000,
        .bits_per_word = 8,
    };

    ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
    close(fd);

    return ((rx[1] & 3) << 8) + rx[2];
}

void readDHT(float &temperature, float &humidity) {
    FILE *fp = popen("python3 dht_reader.py", "r");
    if (!fp) return;
    fscanf(fp, "%f %f", &temperature, &humidity);
    pclose(fp);
}

void logToDatabase(int motion, float temp, float humid, int lightLevel) {
    MYSQL *conn = mysql_init(NULL);
    mysql_real_connect(conn, "localhost", "your_user", "your_password", "smart_home", 0, NULL, 0);

    char query[512];
    snprintf(query, sizeof(query),
             "INSERT INTO sensor_logs (motion, temperature, humidity, light_level, log_time) "
             "VALUES (%d, %.2f, %.2f, %d, NOW());",
             motion, temp, humid, lightLevel);

    mysql_query(conn, query);
    mysql_close(conn);
}

int main() {
    wiringPiSetup();
    pinMode(PIR_PIN, INPUT);
    pinMode(BUZZER_PIN, OUTPUT);

    while (true) {
        int motion = digitalRead(PIR_PIN);
        int lightLevel = read_mcp3008(0);
        float temperature = 0.0, humidity = 0.0;
        readDHT(temperature, humidity);

        logToDatabase(motion, temperature, humidity, lightLevel);

        if (motion) {
            digitalWrite(BUZZER_PIN, HIGH);
            std::cout << "[ALERT] Motion detected!" << std::endl;
        } else {
            digitalWrite(BUZZER_PIN, LOW);
        }

        sleep(5);
    }

    return 0;
}

dht_reader.py (Python Code)

import Adafruit_DHT

sensor = Adafruit_DHT.DHT11
pin = 4  # GPIO 4

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

if temperature is not None and humidity is not None:
    print(f"{temperature:.1f} {humidity:.1f}")
else:
    print("0.0 0.0")

MySQL Table Structure

CREATE DATABASE smart_home;
USE smart_home;

CREATE TABLE sensor_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    motion TINYINT,
    temperature FLOAT,
    humidity FLOAT,
    light_level INT,
    log_time DATETIME
);

Program 2: AI Intruder Detector

Second Integrated Program

This system analyzes stored logs to detect suspicious activity using rule-based AI logic.

Objectives:

  • Detect movements at odd hours (e.g., midnight to 5 AM).

  • Identify frequent/repeated movements in a short time.

  • Flag unusual light or temperature changes (future enhancement).


C++ Code for AI Detector

#include <mysql/mysql.h>
#include <iostream>
#include <ctime>
#include <vector>
#include <string>

struct LogEntry {
    int motion;
    std::string timestamp;
};

std::vector<LogEntry> fetchLogs() {
    MYSQL *conn = mysql_init(NULL);
    mysql_real_connect(conn, "localhost", "your_user", "your_password", "smart_home", 0, NULL, 0);

    MYSQL_RES *res;
    MYSQL_ROW row;
    std::vector<LogEntry> logs;

    mysql_query(conn, "SELECT motion, log_time FROM sensor_logs ORDER BY log_time DESC LIMIT 100;");
    res = mysql_store_result(conn);

    while ((row = mysql_fetch_row(res)) != NULL) {
        logs.push_back({std::stoi(row[0]), row[1]});
    }

    mysql_free_result(res);
    mysql_close(conn);
    return logs;
}

bool isOddHour(const std::string &timestamp) {
    struct tm tm{};
    strptime(timestamp.c_str(), "%Y-%m-%d %H:%M:%S", &tm);
    return (tm.tm_hour >= 0 && tm.tm_hour < 5);
}

void analyzeLogs(const std::vector<LogEntry> &logs) {
    int suspiciousCount = 0;
    for (size_t i = 0; i < logs.size(); ++i) {
        if (logs[i].motion == 1) {
            if (isOddHour(logs[i].timestamp)) {
                std::cout << "[Suspicious] Motion at odd hours: " << logs[i].timestamp << std::endl;
                suspiciousCount++;
            }

            if (i >= 5) {
                bool frequent = true;
                for (size_t j = i - 5; j < i; ++j) {
                    if (logs[j].motion == 0) {
                        frequent = false;
                        break;
                    }
                }
                if (frequent) {
                    std::cout << "[Suspicious] Frequent motion around: " << logs[i].timestamp << std::endl;
                    suspiciousCount++;
                }
            }
        }
    }
}

int main() {
    std::vector<LogEntry> logs = fetchLogs();
    analyzeLogs(logs);
    return 0;
}

System Workflow

  1. Sensor Data Logging – via Program 1.

  2. Data Analysis – via Program 2.

  3. Suspicious Activity Detection:

    • Motion detected during odd hours.

    • Repeated movement patterns.

  4. Optional Integration:

    • Email/SMS alerts.

    • Storing flagged entries for AI training.


Tips & Enhancements

  • Use MySQL indexing on log_time for faster queries.

  • Store credentials in a config file.

  • Maintain a separate table for flagged entries.

  • Integrate with MQTT or Telegram bots for real-time alerts.

  • Expand rules to analyze temperature and light patterns.


Real-World Use Cases

1. Home Security

Useful for:

  • Detecting intrusions while the owner is asleep or away.

  • Apartments or rural homes with limited surveillance.

2. Office Security

  • Monitor server rooms or restricted areas.

  • Detect unauthorized access during off-hours.

3. Elderly Care Monitoring

  • Flag unusual activity or inactivity at night.

  • Alert caregivers via real-time systems.


Case Studies

Case Study 1: Suburban Home

A Raspberry Pi setup alerted a homeowner of a prowler near his carport. The buzzer sounded and footage was recorded for police evidence.

Case Study 2: Startup Intrusion

A small startup detected unauthorized entry during off-hours by a former employee through repeated sensor logs.

Case Study 3: Agricultural Storage

The system flagged animal intrusions and optimized night lighting by analyzing light and motion logs.


Problem Solving Approaches

  1. Reducing False Positives

    • Combine motion detection with light and temperature patterns.

    • Use ML to learn regular behavior patterns.

  2. Storage Optimization

    • Store only flagged event footage.

    • Use lightweight formats and auto-delete routines.

  3. Real-Time Notifications

    • Integrate with Telegram or MQTT to send immediate alerts.