The Muggy Weather Robotics Duo

Image
 The Muggy Weather Robotics Duo A C++ System That Thinks, Feels (Sensors!), and Acts Humidity is like the quiet character in the weather story that actually runs the show. On muggy days, everything feels heavier—breathing, drying laundry, running machines, even keeping a data center cool. For people, it’s about comfort and health; for machines, it’s about performance and reliability; for plants and buildings, it’s about moisture balance and mold risk. In robotics and automation, muggy weather isn’t just a nuisance—it’s a signal . It tells your systems when to ventilate, when to dehumidify, when to throttle physically demanding tasks, and when to take preventative maintenance actions. Today, we’ll build a two-program C++ system that “understands” muggy weather: Program A — sensor_hub.cpp A sensor-side program that generates (or ingests) a live stream of environmental data (temperature, relative humidity, pressure, CO₂, VOCs). Think of it as your robotic nose and skin , con...

Smart Expense Tracker + AI Budget Advisor

Smart Expense Tracker + AI Budget Advisor

Two Integrated Projects Made in C++

This project consists of two integrated programs written in C++:

  • Program 1: Smart Expense Tracker

  • Program 2: AI Budget Advisor

Both share a MySQL database and work together to help users track and manage their expenses intelligently.


Program 1: Smart Expense Tracker

Function

Records daily expenses such as category, amount, description, and date (e.g., transport, food, etc.) into a MySQL database.

Main Features

  • View, add, delete, and edit expenses

  • Categorize expenses (travel, rent, food, etc.)

  • Generate weekly and monthly summaries

  • Stores data in a MySQL table named expenses


Program 2: AI Budget Advisor

Function

Analyzes recorded expenses and provides budgeting tips using basic AI rules and logic.

Main Features

  • Detects overspending trends

  • Offers budgeting advice by category (weekly/monthly)

  • Predicts future spending patterns

  • Uses data from the shared expenses table


Integration of Both Programs

  • Both programs read and write to the same MySQL database.

  • The Advisor can run on demand or on a predefined schedule.


Code for Both Programs

Assumption:

MySQL C++ connector is pre-installed and configured properly.


1. Expense Tracker

Logs all expenses into the MySQL database.

// expense_tracker.cpp

#include <iostream>
#include <mysql/mysql.h>
using namespace std;

void addExpense(MYSQL* conn) {
    string category, description;
    float amount;

    cout << "Enter amount: ";
    cin >> amount;
    cin.ignore();

    cout << "Enter category (food, transport, etc): ";
    getline(cin, category);

    cout << "Enter description: ";
    getline(cin, description);

    string query = "INSERT INTO expenses (amount, category, description, date) VALUES (" +
                   to_string(amount) + ", '" + category + "', '" + description + "', CURDATE())";

    if (mysql_query(conn, query.c_str())) {
        cout << "Insert failed: " << mysql_error(conn) << endl;
    } else {
        cout << "Expense logged successfully.\n";
    }
}

void viewExpenses(MYSQL* conn) {
    if (mysql_query(conn, "SELECT * FROM expenses")) {
        cout << "Query failed: " << mysql_error(conn) << endl;
        return;
    }

    MYSQL_RES* res = mysql_store_result(conn);
    MYSQL_ROW row;

    cout << "ID | Amount | Category | Description | Date\n";
    while ((row = mysql_fetch_row(res))) {
        printf("%s | %s | %s | %s | %s\n", row[0], row[1], row[2], row[3], row[4]);
    }

    mysql_free_result(res);
}

int main() {
    MYSQL* conn = mysql_init(0);
    conn = mysql_real_connect(conn, "localhost", "root", "password", "expense_db", 3306, NULL, 0);

    if (!conn) {
        cout << "Connection failed!\n";
        return 1;
    }

    int choice;
    while (true) {
        cout << "\n1. Add Expense\n2. View Expenses\n3. Exit\nChoice: ";
        cin >> choice;

        if (choice == 1) addExpense(conn);
        else if (choice == 2) viewExpenses(conn);
        else break;
    }

    mysql_close(conn);
    return 0;
}

2. AI Budget Advisor

Analyzes expenses and gives insights.

// ai_budget_advisor.cpp

#include <iostream>
#include <mysql/mysql.h>
#include <map>
using namespace std;

void analyzeSpending(MYSQL* conn) {
    if (mysql_query(conn, "SELECT category, SUM(amount) FROM expenses GROUP BY category")) {
        cout << "Query failed: " << mysql_error(conn) << endl;
        return;
    }

    MYSQL_RES* res = mysql_store_result(conn);
    MYSQL_ROW row;
    map<string, float> categoryTotals;
    float totalSpending = 0;

    while ((row = mysql_fetch_row(res))) {
        string category = row[0];
        float amount = atof(row[1]);
        categoryTotals[category] = amount;
        totalSpending += amount;
    }
    mysql_free_result(res);

    cout << "\n----- Budget Analysis -----\n";
    cout << "Total spending: $" << totalSpending << "\n";

    for (auto& pair : categoryTotals) {
        float percent = (pair.second / totalSpending) * 100;
        cout << pair.first << ": $" << pair.second << " (" << percent << "%)\n";
        if (percent > 40) {
            cout << " - High spending in " << pair.first << "! Consider reducing it.\n";
        }
    }
}

int main() {
    MYSQL* conn = mysql_init(0);
    conn = mysql_real_connect(conn, "localhost", "root", "password", "expense_db", 3306, NULL, 0);

    if (!conn) {
        cout << "Connection failed!\n";
        return 1;
    }

    analyzeSpending(conn);
    mysql_close(conn);
    return 0;
}

MySQL Table Setup

Run the following SQL commands to set up the database and table:

CREATE DATABASE IF NOT EXISTS expense_db;
USE expense_db;

CREATE TABLE IF NOT EXISTS expenses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    amount FLOAT NOT NULL,
    category VARCHAR(50),
    description VARCHAR(100),
    date DATE
);

AI Prediction Using Linear Regression

Upgraded the advisor with linear regression to predict next day’s expenses.

Usage

Uses daily total expenses to forecast the next day using:
y = a * x + b
Where:

  • x = Day index (e.g., Day1, Day2...)

  • y = Total expenses on that day

Code

// ai_budget_advisor_predict.cpp

#include <iostream>
#include <vector>
#include <mysql/mysql.h>
using namespace std;

bool fetchDailyTotals(MYSQL* conn, vector<int>& x, vector<float>& y) {
    string query = "SELECT date, SUM(amount) FROM expenses GROUP BY date ORDER BY date";
    if (mysql_query(conn, query.c_str())) {
        cout << "Query failed: " << mysql_error(conn) << endl;
        return false;
    }

    MYSQL_RES* res = mysql_store_result(conn);
    MYSQL_ROW row;
    int index = 1;

    while ((row = mysql_fetch_row(res))) {
        float dailyTotal = atof(row[1]);
        x.push_back(index++);
        y.push_back(dailyTotal);
    }

    mysql_free_result(res);
    return true;
}

void linearRegression(const vector<int>& x, const vector<float>& y, float& a, float& b) {
    int n = x.size();
    float sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;

    for (int i = 0; i < n; ++i) {
        sumX += x[i];
        sumY += y[i];
        sumXY += x[i] * y[i];
        sumX2 += x[i] * x[i];
    }

    a = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
    b = (sumY - a * sumX) / n;
}

int main() {
    MYSQL* conn = mysql_init(0);
    conn = mysql_real_connect(conn, "localhost", "root", "password", "expense_db", 3306, NULL, 0);

    if (!conn) {
        cout << "Connection failed!" << endl;
        return 1;
    }

    vector<int> x;
    vector<float> y;

    if (!fetchDailyTotals(conn, x, y) || x.size() < 2) {
        cout << "Not enough data to predict.\n";
        mysql_close(conn);
        return 1;
    }

    float a, b;
    linearRegression(x, y, a, b);
    int nextDay = x.back() + 1;
    float predicted = a * nextDay + b;

    cout << "\n---- Expense Prediction ----\n";
    printf("Based on past %d days, predicted expense for next day: $%.2f\n", (int)x.size(), predicted);

    mysql_close(conn);
    return 0;
}

Bonus Ideas

  • Predict expenses per category using individual regression models

  • Add alerts when prediction exceeds a set budget


Real-World Examples

Example 1: Freelancers

Challenge: Irregular income and poor cash flow
How it helps:

  • Tracks expenses automatically

  • Advises spending limits during low-income periods

  • Predicts upcoming spending to plan ahead

Example 2: College Students

Challenge: Overspending on food and entertainment
How it helps:

  • Warns if food spending exceeds 40% of budget

  • Suggests reducing unnecessary expenses

  • Encourages financial discipline

Example 3: Small Businesses

Challenge: Mixing personal and business expenses
How it helps:

  • Categorizes and separates expenses

  • Analyzes overspending trends

  • Predicts inventory-related expenses


Case Studies

Case Study 1: Overspending Pattern

User: A digital artist
Insight: 50% spending on online shopping
Result: Suggested a $100/month cap

Case Study 2: Budget Prediction Saved the Month

User: A student
Insight: Upcoming subscriptions detected
Result: Adjusted food budget and avoided overdraft

Case Study 3: Family Budgeting

User: Parent tracking groceries, fuel, bills
Insight: Weekly fuel spikes
Result: Combined shopping trips and saved 25%


Problem-Solving Approaches

Approach 1: Pattern Recognition

  • Group logs by week

  • Use mean and variance

  • Identify abnormal spikes or dips

Approach 2: Smart Advice Rules

  • If a category > 40% → Show balance alert

  • If expenses grow > 20% of available budget → Warning

  • If spending is flat → Suggest savings/investments

Approach 3: Predictive Forecasting

  • Use linear regression:
    Future Expense = (slope * next_day) + intercept

  • Detect shortfalls before they occur

Comments

Popular posts from this blog

C++ Projects: Basic Traffic Management System

C++ Projects: Book Shop Management System

🌿 Smart Garden Manager in C++ with Robotics, UI, Drones, and Sound "A Rainwater Conservation System for Tomorrow’s Farms"