# mritunjay2007/hack4delhi architecture

> Architecture diagram of the GitHub repository mritunjay2007/hack4delhi, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-02-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/mritunjay2007/hack4delhi
- Repository: https://github.com/mritunjay2007/hack4delhi

## Overview

##### What this project is (type + purpose)

**RailGuard Command Center** is a **full-stack IoT + AI real-time monitoring system** for railway sabotage/tamper detection.

From the README + tree, it’s a **linear data pipeline** spanning:
- **Edge hardware**: ESP32 collecting multi-sensor telemetry (vibration/magnetic/sound).
- **Messaging layer**: MQTT broker (HiveMQ per README).
- **Backend “bridge”**: Node.js/Express service subscribing to MQTT, calling AI inference, and pushing updates to UI.
- **AI service**: Python **FastAPI** service running Isolation Forest + rules + (likely) sensor fusion + optional vision/VLM hooks.
- **Operator UI**: React (Vite) dashboard with maps/telemetry.

##### Hardware / Edge
- `Software/esp32/src/main/main.ino`
- Sensors → ESP32 sampling → preprocessing/packaging → MQTT publish.

##### Backend (Node.js) – bridge/orchestrator
- `Software/backend/node-server/index.js` (service entrypoint)
- `mqtt/mqttClient.js` (MQTT subscribe)
- `socket/socket.js` (Socket.io real-time push)
- `controllers/dataController.js` (HTTP API endpoints)
- `services/alertService.js` (alert logic/formatting)
- `ai/aiService.js` (HTTP client to Python AI service)
- `data/alerts.json` (prototype persistence / store)

This suggests a small layered structure: **transport (MQTT, Socket)** + **API/controllers** + **services** + **storage (JSON)**.

##### AI service (Python / FastAPI)
- `ai-service/main.py` (FastAPI app entrypoint per README uvicorn main:app)
- `model.py`, `prepare_data.py`, `scaler.pkl`, `isolation_forest.pkl` (ML pipeline artifacts)
- `fusion.py` (multi-sensor fusion logic)
- `dataExtract.py` (feature extraction)
- `simulate_event.py` (test/sim mode)
- `camera.py`, `vlm_model.py`, `captures/` and `captured_images/` (camera ingestion + vision-language model integration hooks)

##### Frontend (React/Vite)
- `Software/frontend/src/components/Dashboard.jsx` (main UI)
- `App.jsx`, plus Tailwind config, etc.

It as a **web client** subscribing via **Socket.io** and optionally calling REST endpoints for initial state/history.

Goal: show boundaries and external dependencies.
Include:
- Operator / Control Room user
- RailGuard System
- External MQTT broker (HiveMQ)
- Optional: “Railway Ops Systems / Incident Management” as future integration (even if not implemented)
- Physical environment (trackside sensors)

##### Node.js Backend (Express + MQTT + Socket.io) (`index.js`)
- Sub-components called out: MQTT Client, REST API, AI Client, Socket Gateway, Alert Service, Alerts Store (`alerts.json`)
##### Python AI Service (FastAPI) (`ai-service/main.py`)
- Sub-components: Feature Extract, Sensor Fusion, Isolation Forest inference, Rules Engine, (Optional) Vision/VLM module, Model artifacts (`*.pkl`)
##### React Dashboard (Vite) (`Dashboard.jsx`)
- Sub-components: Map/Telemetry UI, alert stream, test/sim mode toggle

- ESP32 → MQTT Broker (**MQTT publish**)
- Node Backend ← MQTT Broker (**MQTT subscribe**)
- Node Backend → AI Service (**HTTP POST /predict** or similar)
- AI Service → Node Backend (**prediction response**)
- Node Backend → React Dashboard (**Socket.io events**)
- React Dashboard → Node Backend (**optional REST fetch / mode change / ack**)

This repo explicitly supports simulation (“TEST (SIM) mode”). Show two sequences:
- **LIVE**: ESP32 publishes → backend subscribes → AI inference → socket emit
- **SIM**: dashboard/backend triggers simulation (`simulate_event.py` or backend-generated) → AI inference → socket emit

This clarifies operational reality, not just static containers.

- **MQTT link**: from `Software/backend/node-server/mqtt/mqttClient.js`
- **AI call**: from `Software/backend/node-server/ai/aiService.js`
- **Websocket**: from `Software/backend/node-server/socket/socket.js`
- **REST**: from `controllers/dataController.js`

**where state lives**:
- Model persistence: `*.pkl` inside AI service

##### Edge-to-Cloud streaming pipeline
Sensors → broker → backend → AI → real-time UI. Emphasize low-latency path.

##### Bridge/Orchestrator Backend
Node.js is not just an API; it’s the **protocol bridge** (MQTT ↔ HTTP ↔ Socket.io).

##### AI service separation
Python service is independently deployable/scalable. Show it as its own container/process.

##### Event-driven alerting
Alerts are derived events (anomaly score / rule triggers) pushed to UI.

##### Simulation mode as a first-class runtime path

- Sensors (ADXL345, QMC5883L, INMP441)
- ESP32 Firmware (`main.ino`)
- Output: JSON payload

##### MQTT Broker
- HiveMQ (external)

- MQTT Subscriber (`mqttClient.js`)
- REST API (`dataController.js`)
- AI Client (`aiService.js`)
- Alert Service (`alertService.js`)
- Socket.io Server (`socket.js`)
- Alerts Store (`alerts.json`)

- FastAPI app (`main.py`)
- Feature extraction (`dataExtract.py`)
- Fusion (`fusion.py`)
- Anomaly model (`model.py` + `isolation_forest.pkl` + `scaler.pkl`)
- Optional vision (`camera.py`, `vlm_model.py`)
- Sim generator (`simulate_event.py`)

- Dashboard UI (`Dashboard.jsx`)
- Live socket subscription
- + charts

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% Context / Boundaries (vertical)
  %% =========================

  Operator["Operator (Control Room User)"]:::actor

  subgraph "Operator Workstation"
    Browser["Web Browser"]:::external
    ReactApp["React Dashboard (Vite)"]:::frontend
    UIMap["Map + Telemetry Views"]:::frontend
    UIAlerts["Alert Stream + Controls"]:::frontend
  end

  subgraph "Internet / Messaging"
    HiveMQ{{"MQTT Broker (HiveMQ)"}}:::messaging
  end

  subgraph "Control Center / Cloud Backend"
    subgraph "Node.js Backend (Express + MQTT + Socket.io)"
      NodeEntry["Service Entrypoint (index.js)"]:::service
      Config["Configuration (config.js)"]:::service

      MQTTClient["MQTT Client (subscribe)"]:::service
      RESTAPI["REST API Controllers"]:::service
      SocketGW["Socket.io Gateway"]:::service
      AICLient["AI Client (HTTP)"]:::service
      AlertSvc["Alert Service (format/logic)"]:::service

      AlertsStore[("Alerts Store (alerts.json)")]:::datastore
    end

    subgraph "Python AI Service (FastAPI)"
      FastAPI["FastAPI App (main.py)"]:::service

      FeatureExtract["Feature Extraction (dataExtract.py)"]:::service
      Fusion["Sensor Fusion (fusion.py)"]:::service
      ModelLogic["Model / Inference (model.py)"]:::service
      Rules["Rules / Heuristics"]:::service
      PrepareData["Data Preparation (prepare_data.py)"]:::service

      IFModel[("Isolation Forest Artifact (.pkl)")]:::datastore
      Scaler[("Scaler Artifact (.pkl)")]:::datastore

      SimGen["Simulation Generator (simulate_event.py)"]:::service

      subgraph "Optional Vision/VLM Hooks"
        Camera["Camera Ingestion (camera.py)"]:::service
        VLM["Vision-Language Module (vlm_model.py)"]:::service
        CapturesDir[("Capture Workspace (captures/)")]:::datastore
        CapturedImagesDir[("Captured Images (captured_images/)")]:::datastore
      end
    end
  end

  subgraph "Trackside / Edge Network"
    Environment["Rail Track Environment"]:::external
    Sensors["Sensors (vibration / magnetic / sound)"]:::edge
    ESP32["ESP32 Firmware (main.ino)"]:::edge
    Preprocess["Sampling / Filtering / Packaging (JSON payload)"]:::edge
    MQTTPub["MQTT Publish (telemetry topic)"]:::edge
  end

  %% =========================
  %% Primary Data Flow (low-latency path)
  %% =========================
  Operator -->|"monitors"| Browser
  Browser -->|"loads"| ReactApp
  ReactApp -->|"renders"| UIMap
  ReactApp -->|"renders"| UIAlerts

  Environment -->|"signals"| Sensors
  Sensors -->|"raw_telemetry"| ESP32
  ESP32 -->|"reads_sensors"| Preprocess
  Preprocess -->|"builds_payload"| MQTTPub
  MQTTPub -->|"MQTT_publish(telemetry)"| HiveMQ

  HiveMQ -->|"MQTT_subscribe(telemetry)"| MQTTClient
  MQTTClient -->|"dispatches_to"| NodeEntry

  NodeEntry -->|"routes_to"| AICLient
  AICLient -->|"HTTP_POST_/predict"| FastAPI
  FastAPI -->|"calls"| FeatureExtract
  FeatureExtract -->|"features"| Fusion
  Fusion -->|"fused_features"| ModelLogic
  ModelLogic -->|"loads"| IFModel
  ModelLogic -->|"loads"| Scaler
  ModelLogic -->|"score"| Rules
  Rules -->|"prediction_response"| FastAPI
  FastAPI -->|"HTTP_response(score+labels)"| AICLient

  NodeEntry -->|"derives_alerts"| AlertSvc
  AlertSvc -->|"persist(alert_event)"| AlertsStore
  AlertSvc -->|"emit(telemetry+alerts)"| SocketGW
  SocketGW -->|"Socket.io_event(telemetry_update/alert)"| ReactApp

  %% =========================
  %% Request/Response Path (REST for history/config)
  %% =========================
  ReactApp -->|"REST_GET_/alerts"| RESTAPI
  RESTAPI -->|"read_history"| AlertsStore
  RESTAPI -->|"REST_response(alerts)"| ReactApp

  ReactApp -->|"REST(health/config)"| RESTAPI
  RESTAPI -->|"uses"| Config

  %% =========================
  %% Simulation / Test Mode Path (first-class)
  %% =========================
  ReactApp -->|"toggle_SIM_or_trigger"| RESTAPI
  RESTAPI -->|"invoke_simulation"| NodeEntry
  NodeEntry -->|"run_sim_event"| SimGen
  SimGen -->|"synthetic_telemetry"| FastAPI
  FastAPI -->|"prediction"| AICLient
  AICLient -->|"result"| AlertSvc
  AlertSvc -->|"Socket.io_event(alert)"| SocketGW

  %% =========================
  %% Optional Vision/VLM Hooks
  %% =========================
  FastAPI -->|"optional_pipeline"| Camera
  Camera -->|"writes"| CapturesDir
  Camera -->|"writes"| CapturedImagesDir
  Camera -->|"frames/metadata"| VLM
  VLM -->|"enrich_context"| Rules

  %% =========================
  %% Click Events (component mapping)
  %% =========================
  click ESP32 "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/esp32/src/main/main.ino"
  click NodeEntry "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/index.js"
  click MQTTClient "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/mqtt/mqttClient.js"
  click SocketGW "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/socket/socket.js"
  click RESTAPI "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/controllers/dataController.js"
  click AlertSvc "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/services/alertService.js"
  click AICLient "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai/aiService.js"
  click AlertsStore "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/data/alerts.json"
  click Config "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/config/config.js"

  click FastAPI "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/main.py"
  click ModelLogic "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/model.py"
  click FeatureExtract "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/dataExtract.py"
  click Fusion "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/fusion.py"
  click PrepareData "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/prepare_data.py"
  click IFModel "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/isolation_forest.pkl"
  click Scaler "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/scaler.pkl"
  click SimGen "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/simulate_event.py"
  click Camera "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/camera.py"
  click VLM "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/backend/node-server/ai-service/vlm_model.py"
  click CapturedImagesDir "https://github.com/mritunjay2007/hack4delhi/tree/main/Software/backend/node-server/ai-service/captured_images"
  click CapturesDir "https://github.com/mritunjay2007/hack4delhi/tree/main/Software/backend/node-server/ai-service/captures"

  click ReactApp "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/frontend/src/App.jsx"
  click UIMap "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/frontend/src/components/Dashboard.jsx"
  click UIAlerts "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/frontend/src/components/Dashboard.jsx"
  click Browser "https://github.com/mritunjay2007/hack4delhi/blob/main/Software/frontend/src/main.jsx"

  %% =========================
  %% Styles (color critical)
  %% =========================
  classDef actor fill:#0f172a,stroke:#0f172a,color:#ffffff,stroke-width:1px
  classDef edge fill:#1d4ed8,stroke:#0b3aa6,color:#ffffff,stroke-width:1px
  classDef messaging fill:#6d28d9,stroke:#4c1d95,color:#ffffff,stroke-width:1px
  classDef service fill:#16a34a,stroke:#166534,color:#ffffff,stroke-width:1px
  classDef frontend fill:#f59e0b,stroke:#b45309,color:#111827,stroke-width:1px
  classDef datastore fill:#94a3b8,stroke:#475569,color:#0f172a,stroke-width:1px
  classDef external fill:#0ea5e9,stroke:#0369a1,color:#ffffff,stroke-width:1px
```
