Skip to content

AKB9988/AlertX

Repository files navigation

🚨 AlertX

Real-Time Vehicular Crash Detection & Peer-to-Peer Alert System

An Android application that leverages smartphone sensors to detect vehicular crashes in real-time, record high-frequency telemetry data, and instantly broadcast emergency alerts to nearby drivers — all without centralized infrastructure dependency.


📌 Problem Statement

Every year, thousands of lives are lost due to delayed emergency response after road accidents. Existing solutions either require expensive dedicated hardware (OBD-II dongles, dash cams) or depend on manual user action. AlertX solves this by turning any Android smartphone into an intelligent crash detection system that:

  • Automatically detects high-impact collisions using onboard sensors
  • Instantly alerts nearby drivers within seconds via a hybrid communication architecture
  • Captures forensic-grade telemetry for emergency responders and insurance analysis
  • Operates entirely in the background as a foreground service with zero user intervention

🏗️ System Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        PHONE A (Crash)                          │
│  ┌──────────────┐   ┌──────────────┐   ┌──────────────────────┐ │
│  │ SensorService│──>│ CrashDetect  │──>│ CrashDataPackage     │ │
│  │  (50Hz Poll) │   │ (≥10G Thres.)│   │ (150pts, 3s buffer)  │ │
│  └──────────────┘   └──────────────┘   └──────────┬───────────┘ │
│                                                   │             │
│                     ┌─────────────────────────────┼──────┐      │
│                     │        DISPATCH LAYER       │      │      │
│                     │                             ▼      │      │
│                     │  ┌─────────┐  ┌──────────┐  ┌────┐ │      │
│                     │  │  MQTT   │  │   REST   │  │ WM │ │      │
│                     │  │ (TX)    │  │  (POST)  │  │    │ │      │
│                     │  └────┬────┘  └────┬─────┘  └──┬─┘ │      │
│                     └───────┼────────────┼───────────┼───┘      │
└─────────────────────────────┼────────────┼───────────┼──────────┘
                              │            │           │
                              ▼            ▼           ▼
                   ┌──────────────────────────────────────────┐
                   │           BACKEND SERVER (Flask)         │
                   │                                          │
                   │  MQTT Broker ──▶ Process ──▶ Socket.IO  │
                   │  REST API   ──▶ Verify  ──▶ Broadcast   │
                   └──────────────────────┬───────────────────┘
                                          │
                                          ▼
┌─────────────────────────────────────────────────────────────────┐
│                       PHONE B (Alert)                           │
│                                                                 │
│   Socket.IO ──▶ "new_crash_alert" ──▶ AlertDialog + Vibration  │
│   (Filtered: ignores own driver_id)                             │
└─────────────────────────────────────────────────────────────────┘

Hybrid Communication Protocol

Channel Direction Purpose Payload
MQTT Phone → Server Send crash sensor data (heavy payload) Full 150-point telemetry trace
Socket.IO Server → Phone Receive real-time alerts (lightweight) Processed alert with GPS & metadata
REST API Phone → Server Crash verification & full JSON upload Complete CrashDataPackage JSON
WorkManager Phone → Server Reliable background upload with retry JSON payload (survives app kill)

Why Hybrid? MQTT excels at lightweight pub/sub for sensor telemetry, while Socket.IO provides reliable, bidirectional real-time event delivery. Using both ensures the system is resilient — crash data reaches the server via MQTT even on unstable connections, while alerts are delivered instantly via persistent Socket.IO connections.


✨ Key Features

🎯 Crash Detection Engine

  • 50Hz sensor polling via Android SensorManager (Accelerometer, Gyroscope, Magnetometer)
  • G-Force computation: √(ax² + ay² + az²) / 9.81 — triggers at ≥ 10.0G threshold
  • 3-second circular buffer (150 data points) captures the crash event window
  • Runs as an Android Foreground Service with PARTIAL_WAKE_LOCK for uninterrupted background operation

📡 Multi-Channel Data Dispatch

  • MQTT (Eclipse Paho): Publishes crash trigger alerts to alertx/raw_data topic with QoS 1 (at-least-once delivery)
  • REST API: POSTs full telemetry JSON to /verify_crash endpoint on a background thread
  • WorkManager: Enqueues reliable upload jobs that survive app process death and retry with exponential backoff

🔔 Real-Time Peer Alerts

  • Socket.IO listener receives new_crash_alert events from the server
  • Self-filtering: Ignores alerts originating from the same driver_id to prevent echo
  • Multi-sensory notification: Emergency AlertDialog + haptic vibration pattern + alarm tone

🆘 Manual SOS System

  • On-screen SOS button with animated pulse ring
  • Hardware trigger: Simultaneously press both volume keys to activate SOS
  • SOS Morse vibration pattern: ... --- ... (dot-dot-dot dash-dash-dash dot-dot-dot)

🎨 HUD-Style Dashboard

  • Dark-themed, cockpit-inspired interface built with custom views
  • Custom G-Force Meter: Semi-circular arc gauge with gradient coloring (green → amber → red)
  • Real-time display of all 9-axis sensor data (Accel XYZ, Gyro XYZ, Mag XYZ)
  • Live GPS coordinates & speed (km/h) via Google Fused Location Provider
  • Rolling event log with timestamped entries

📂 Project Structure

AlertX/
├── app/src/main/
│   ├── java/com/example/alertx/
│   │   ├── MainActivity.java          # Main HUD dashboard & event orchestration
│   │   ├── SensorService.java         # Foreground service — 50Hz sensor engine
│   │   ├── SensorDataPoint.java       # Data model for a single sensor reading
│   │   ├── CrashDataPackage.java      # Serializable crash payload (Gson)
│   │   ├── GForceMeterView.java       # Custom View — animated arc gauge
│   │   ├── MqttHelper.java            # MQTT client (Eclipse Paho async)
│   │   ├── SocketIOHelper.java        # Socket.IO client for real-time alerts
│   │   ├── NetworkHelper.java         # REST API helper (background HTTP POST)
│   │   ├── CrashUploadWorker.java     # WorkManager — reliable background upload
│   │   └── Constants.java             # Centralized server config (IP, port, URLs)
│   ├── res/
│   │   ├── layout/activity_main.xml   # HUD dashboard layout (CardView-based)
│   │   └── drawable/                  # Custom button, card, and SOS ring drawables
│   └── AndroidManifest.xml            # Permissions & service declarations
├── gradle/libs.versions.toml          # Version catalog for dependencies
└── README.md

🛠️ Tech Stack

Layer Technology Version
Language Java 17
Build System Gradle (Kotlin DSL) AGP 8.10.0
UI Android Views + Custom Canvas Material 1.13.0
Sensors Android SensorManager 50Hz polling (20ms)
Location Google Play Services Fused Location 21.3.0
MQTT Eclipse Paho MQTT Client 1.2.5
WebSocket Socket.IO Client (Java)
HTTP java.net.HttpURLConnection Built-in
Serialization Google Gson 2.11.0
Background AndroidX WorkManager 2.10.1
Min SDK Android 8.0 (API 26)

⚡ Getting Started

Prerequisites

  • Android Studio Ladybug (2024.2+) or newer
  • JDK 17
  • An Android device or emulator running API 26+
  • (Optional) A backend server running the Flask crash-processing service

Installation

  1. Clone the repository

    git clone https://github.com/AKB9988/AlertX.git
    cd AlertX
  2. Configure the backend URL

    Edit Constants.java and set your server's IP:

    public static final String SERVER_IP = "YOUR_SERVER_IP";
    public static final int SERVER_PORT = 5000;
  3. Open in Android Studio → Let Gradle sync complete

  4. Build & Run on a physical device (sensor APIs require real hardware)

Permissions Required

Permission Purpose
ACCESS_FINE_LOCATION GPS coordinates for crash location
ACCESS_COARSE_LOCATION Fallback location provider
INTERNET MQTT, Socket.IO, REST communication
FOREGROUND_SERVICE Keep sensor polling alive
FOREGROUND_SERVICE_LOCATION Location tracking in foreground service
WAKE_LOCK Prevent CPU sleep during monitoring
VIBRATE SOS and alert haptic feedback
POST_NOTIFICATIONS Android 13+ notification permission

📊 Data Flow

Crash Detection Pipeline

Accelerometer Event (50Hz)
        │
        ▼
  Compute G-Force = √(x² + y² + z²) / 9.81
        │
        ├── G < 10.0 → Continue monitoring
        │
        └── G ≥ 10.0 → CRASH DETECTED!
                │
                ▼
        Start 3-second recording (150 data points)
                │
                ▼
        Package into CrashDataPackage
        {driver_id, timestamp, accel[], gyro[], gps, max_gforce, trigger_type}
                │
                ├──▶ MQTT Publish  (alertx/raw_data, QoS 1)
                ├──▶ REST POST     (/verify_crash, background thread)
                └──▶ WorkManager   (reliable retry with backoff)

Crash Data Payload (JSON)

{
  "driver_id": "AlertX_Pixel7_4821",
  "timestamp": 1707742800000,
  "accelerometer": ["[2.31,9.74,1.05]", "[12.45,8.91,-3.22]", "..."],
  "gyroscope": ["[0.0012,0.0034,-0.0021]", "..."],
  "gps": { "lat": 28.6139, "long": 77.2090 },
  "max_gforce": 12.7,
  "trigger_type": "auto",
  "fog_level": "local_weather_api_call"
}

🖥️ Screenshots

The app features a dark, HUD-style interface inspired by automotive cockpit displays:

Dashboard (Monitoring) G-Force Meter (Crash) Alert Received
Real-time 9-axis sensor data, speed, GPS Custom arc gauge with gradient coloring Emergency dialog with vibration pattern

🔒 Security & Privacy

  • No cloud dependency: MQTT broker can be self-hosted; data stays on your network
  • Self-filtering: Devices ignore their own crash alerts (prevents echo loops)
  • No PII collection: Only sensor telemetry, GPS, and a device-derived anonymous ID are transmitted
  • Cleartext traffic: Enabled for local development; should use TLS/SSL in production

🗺️ Roadmap

  • ML-based crash classification (distinguish crash vs. pothole vs. speed bump)
  • Geohash-based topic subscription for proximity-aware alerting
  • Integration with emergency services (auto-dial 112/911)
  • Fog/weather-aware alert severity scaling
  • Wear OS companion app for wrist notifications
  • Firebase Cloud Messaging fallback for alerts

🤝 Contributing

Contributions are welcome! Please open an issue or submit a pull request.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/ml-crash-model)
  3. Commit your changes (git commit -m 'Add ML crash classifier')
  4. Push to the branch (git push origin feature/ml-crash-model)
  5. Open a Pull Request

Built with ❤️ for road safety

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages