Skip to content

Latest commit

ย 

History

248 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

๐ŸŒ‹ QuakeGuard

Distributed Earthquake Early Warning System

Full-Stack IoT Architecture for Real-Time Earthquake Detection

Version License C++ Python React Native PostgreSQL Redis Docker Local AI HiveMQ Cloudflare

CI Backend CI Frontend CI IoT

DOI

Security Rating Reliability Rating Maintainability Rating Quality Gate Status

Bugs Code Smells Duplicated Lines (%)

๐Ÿ“š Technical Specification: A comprehensive architecture whitepaper is available in the docs/ directory, compiled via Typst. For a browsable, topic-by-topic reference, check out the project Wiki.

QuakeGuard Logo


๐Ÿ“– Overview

QuakeGuard is a full-stack IoT architecture for real-time detection, analysis, and reporting of seismic events. The system transforms everyday household appliances โ€” washing machines, TVs, refrigerators โ€” into a distributed seismic sensor network, each node capable of detecting and reporting earthquake activity autonomously.

Intelligent edge sensors (ESP32-C3 + ADXL345) analyze vibrations locally using professional-grade algorithms and transmit cryptographically signed data to an asynchronous cloud backend. The backend is engineesred to handle the massive traffic spikes โ€” the Thundering Herd effect โ€” typical during widespread seismic events, ensuring reliable alarm delivery without bottlenecking. A React Native mobile app receives real-time haptic and visual alerts via WebSocket.

QuakeGuard Proprietary Hardware

QuakeGuard v2.0 Assembled PCB

The QuakeGuard v2.0 fully assembled PCB, featuring the ESP32-C3 SuperMini, the ADXL345 accelerometer, and the u-blox GNSS module. For a complete list of required components, refer to the Bill of Materials (BOM) in the Wiki.


๐Ÿ—๏ธ System Architecture

ESP32-C3 + ADXL345
       โ”‚
       โ”‚  MQTT (signed payload)
       โ–ผ
MQTT Bridge โ”€โ”€โ–บ POST /readings/ โ”€โ”€โ–บ ECDSA Verification
                                              โ”‚
                                              โ–ผ
                                        Redis Queue
                                              โ”‚
                                              โ–ผ
                                     Background Worker โ”€โ”€โ”€โ”€โ–บโ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                      โ”‚           โ”‚ (Queue)  โ”‚ AI Worker โ”‚
                                      โ–ผ           โ–ผ          โ”‚ (Ollama)  โ”‚
                               PostgreSQL    Redis Pub/Sub โ—„โ”€โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜
                               + PostGIS               โ”‚
                                                   โ–ผ
                                            WebSocket Broadcast
                                                  โ”‚
                                                  โ–ผ
                                        React Native Mobile App
                                        (Haptic + Visual Alert)

The project follows Microservices and Event-Driven Design principles across three fully independent layers.


๐Ÿ“ก IoT Edge (firmware/)

Feature Detail
Hardware ESP32-C3 SuperMini + ADXL345 Accelerometer
Sampling Rate 100 Hz
Detection Algorithm STA/LTA (Short Term / Long Term Average)
Signal Processing Digital High-Pass Filter (HPF) to remove gravity
Data Structure Statically allocated Ring Buffers (RingBuffer<100> STA, RingBuffer<1000> LTA)
Security ECDSA NIST256p cryptographic signing on every payload
Transmission MQTT publish to quakeguard/telemetry
Provisioning Automated device handshake on first boot via POST /devices/register
Secret Injection Compile-time ENROLLMENT_TOKEN via PlatformIO pre-script + #error fail-fast

โ˜๏ธ Backend (backend/)

Feature Detail
Framework FastAPI (Python 3.11), fully async
Security API Key auth, ECDSA signature verification, Anti-Replay (300s window)
Message Broker Redis โ€” decouples ingestion from processing
Rate Limiting Fixed-window 50 req/s per IP via Redis
Alert Engine ML-like magnitude proxy (M = log10(PGA_calib) + b), threshold M โ‰ฅ 4.5
Deduplication Redis TTL cooldown lock per zone (60s), prevents alert storms
Persistence PostgreSQL + PostGIS with recorded_at timestamps
Zone Assignment Automatic via PostGIS ST_Contains spatial query, ordered by ST_Area ascending
Zone Seeding 8 pre-populated global macro-regions + "Unknown Region" fallback
Observability GET /health โ€” concurrent PostgreSQL + Redis ping
Secrets Fail-fast RuntimeError on missing env vars at startup
MQTT Bridge mqtt_subscriber.py โ€” forwards MQTT payloads to the secure HTTP pipeline
Edge AI Asynchronous emergency report generation via local Ollama (Llama 3.2)

๐Ÿ“ฑ Frontend (mobile/)

Feature Detail
Framework React Native (Expo) with TypeScript
Navigation Expo Router โ€” 3-tab Bottom Navigator (Monitor, Sensors Map, Settings)
State Management Zustand slices (usePreferencesStore, useAlertStore)
Server State TanStack Query + Axios โ€” caching, background refetch, retry
Real-Time WebSocket context with exponential backoff reconnection
Alert Delivery SOS haptic vibration pattern + OS push notification via expo-notifications
Alert History In-session feed of last 10 critical events
AI Report Banner Inline AI-generated emergency report (summary + recommendations) for the latest alert, with "Report unavailable" badge on failures
Offline Mode Toggle silences WebSocket, halts all TanStack Query polling
Notifications notificationsEnabled toggle gates haptics and push notifications
Safe Areas react-native-safe-area-context โ€” Dynamic Island and punch-hole compatible

๐Ÿ” Security Model

Data integrity is paramount in an emergency system. Every telemetry packet is cryptographically secured end-to-end.

ESP32 signs payload with ECDSA NIST256p (SHA256)
         โ†“
Backend verifies signature against registered public key
         โ†“
Timestamp validated within 300-second window (Anti-Replay)
         โ†“
API Key checked on every request (X-API-Key header)
         โ†“
Payload accepted โ†’ Redis Queue

Threat model coverage:

  • โœ… Man-in-the-Middle (MitM) โ€” ECDSA signature verification
  • โœ… Spoofing โ€” public key registration + signature check
  • โœ… Replay attacks โ€” 300-second timestamp window
  • โœ… Brute force โ€” rate limiting 50 req/s per IP
  • โœ… Unauthorized access โ€” API Key + enrollment token fail-fast

๐Ÿš€ Quick Start

Prerequisites

  • Docker Desktop & Docker Compose
  • PlatformIO (VS Code Extension)
  • Node.js 18+ & Expo Go (mobile)
  • A mobile hotspot or shared WiFi network for ESP32 + backend connectivity

1. Configure Environment Variables

cd backend
cp .env.example .env

Edit .env and set the required secrets:

# --- Application Secrets ---
IOT_API_KEY=your_secret_key
MOBILE_WS_TOKEN=your_ws_token
ENROLLMENT_TOKEN=your_enrollment_token

# --- Database ---
POSTGRES_DB=quakeguard_db
POSTGRES_USER=developer
POSTGRES_PASSWORD=your_db_password
API_PORT=8000

# --- Cloud MQTT (HiveMQ) ---
MQTT_BROKER=your-cluster-id.s1.eu.hivemq.cloud
MQTT_PORT=8883
MQTT_USERNAME=your_mqtt_username
MQTT_PASSWORD=your_mqtt_password

# --- AI Emergency Reports (hybrid Edge AI architecture) ---
AI_REPORT_ENABLED=true
OLLAMA_HOST=http://127.0.0.1:11434
OLLAMA_MODEL=llama3.2:1b

โš ๏ธ The backend will refuse to start if any of these are missing โ€” this is intentional fail-fast behavior.

๐Ÿ’ก Edge AI Architecture (v2.0.0): To maximize hardware efficiency and avoid Docker's GPU passthrough overhead, QuakeGuard employs an industrial Hybrid Edge AI pattern (similar to NVIDIA Jetson or Tesla FSD architectures). The core AI inference engine (Ollama) runs bare-metal on the host Linux OS, while the application microservices run in Docker and communicate via network_mode: "host".

To enable on-premise AI reports:

  1. Install Ollama natively on your Linux host: curl -fsSL https://ollama.com/install.sh | sh
  2. Pull the model natively: ollama pull llama3.2:1b
  3. Start the Docker stack with the AI worker profile: docker compose --profile ai up --build -d

Reports are generated entirely on your machine: telemetry never leaves the host.

2. Launch the Backend Stack

cd backend
docker compose up --build -d
Endpoint URL
API http://localhost:8000
Swagger UI http://localhost:8000/docs
Health Check http://localhost:8000/health

3. Configure and Flash the IoT Firmware

cd firmware
cp esp32_config.env.example esp32_config.env
# Edit esp32_config.env with your network IP and ENROLLMENT_TOKEN

Flash via PlatformIO. On first boot the device will:

  1. Open a WiFi captive portal (QuakeGuard-Setup)
  2. Connect to your network
  3. Automatically register with the backend and receive a sensor_id

๐Ÿ’ก If the sensor registers with latitude=0.0, longitude=0.0 it will be assigned to "Unknown Region". Hardcode your coordinates in main.cpp for correct zone assignment until GPS integration is complete.

4. Launch the Mobile App

cd mobile
npm install

Update constants/config.ts with your machine's local IP:

export const API_BASE_URL = "http://YOUR_LOCAL_IP:8000";

Create .env in the mobile root:

EXPO_PUBLIC_IOT_API_KEY=your_secret_key
EXPO_PUBLIC_MOBILE_WS_TOKEN=your_ws_token
npx expo start

Scan the QR code with Expo Go. Ensure your phone is on the same WiFi network as the backend machine.


๐Ÿงช Stress Test

Validates the full pipeline: ingestion โ†’ Redis โ†’ worker โ†’ PostGIS โ†’ WebSocket alerts.

cd backend
export API_URL="http://localhost:8000"
export NUM_SENSORS=150
export CONCURRENCY_LIMIT=50
python -m tests.stress_test

Three phases:

Phase What it tests
๐Ÿ”ฅ Phase 1 โ€” Firehose 150 concurrent sensors, rate limiter validation
โš”๏ธ Phase 2 โ€” Security Bad signature blocked (401), Replay attack blocked (403)
๐Ÿ” Phase 3 โ€” E2E DB persistence verified via polling GET /sensors/{id}/statistics

A successful run ends with ๐Ÿ† SYSTEM CERTIFIED.


๐ŸŽฎ Demo Mode

Trigger a simulated earthquake instantly from Swagger UI without running the stress test:

POST /demo/trigger-earthquake

Default payload (works with empty {}):

{
  "zone_id": 1,
  "magnitude": 7.5,
  "message": "Simulated Critical Event"
}

This publishes directly to the Redis quake_alerts channel, bypassing the IoT pipeline entirely and triggering the mobile app alert UI within milliseconds.


๐Ÿ—บ๏ธ Geographic Zones

The database is pre-seeded with 8 global macro-regions. Sensors are automatically assigned to the correct zone via PostGIS spatial query at registration time.

Zone Coverage
Italy - North Lombardy, Veneto, Piedmont
Italy - Center Tuscany, Lazio, Umbria
Italy - South & Islands Campania, Sicily, Sardinia
Western Europe France, Spain, Germany, UK
North America USA, Canada, Mexico
South America Brazil, Argentina, Chile
East Asia China, Japan, India
Unknown Region Fallback for unmapped coordinates

๐Ÿ”„ CI/CD Pipeline

Workflow Trigger Checks
backend-ci.yml backend/** Bandit, Safety, stress test
frontend-ci.yml mobile/** ESLint, npm audit
iot-ci.yml firmware/** PlatformIO compilation
pr-lint.yml All PRs Semantic PR title (type(scope): message)
devops-ci.yml .github/workflows/** Actionlint workflow validation

๐Ÿ—‚๏ธ Project Structure

QuakeGuard/
โ”œโ”€โ”€ backend/
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ main.py              # FastAPI gateway + REST endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ security.py          # ECDSA, API Key, Anti-Replay
โ”‚   โ”‚   โ”œโ”€โ”€ worker.py            # Redis consumer + magnitude + alert engine + AI enqueue
โ”‚   โ”‚   โ”œโ”€โ”€ ai_report_worker.py  # Dedicated AI report consumer (Ollama + state machine)
โ”‚   โ”‚   โ”œโ”€โ”€ ollama_client.py     # Deterministic LLM client (anti-hallucination)
โ”‚   โ”‚   โ”œโ”€โ”€ mqtt_subscriber.py   # MQTT to HTTP bridge
โ”‚   โ”‚   โ”œโ”€โ”€ seed.py              # Geographic zone seeder
โ”‚   โ”‚   โ”œโ”€โ”€ models.py            # SQLAlchemy ORM models (+ EmergencyReport)
โ”‚   โ”‚   โ”œโ”€โ”€ schemas.py           # Pydantic request/response schemas
โ”‚   โ”‚   โ””โ”€โ”€ database.py          # DB engine and session factory
โ”‚   โ”œโ”€โ”€ tests/
โ”‚   โ”‚   โ”œโ”€โ”€ stress_test.py       # Critical E2E stress test suite
โ”‚   โ”‚   โ””โ”€โ”€ unit/                # Unit tests (worker, ollama client, AI worker, models, ...)
โ”‚   โ”œโ”€โ”€ init-scripts/
โ”‚   โ”‚   โ””โ”€โ”€ ollama-entrypoint.sh # Auto-pulls the Ollama model on startup
โ”‚   โ”œโ”€โ”€ build.ps1                # Automatic container publish
โ”‚   โ”œโ”€โ”€ docker-compose.yml
โ”‚   โ”œโ”€โ”€ Dockerfile
โ”‚   โ”œโ”€โ”€ mosquitto.conf
โ”‚   โ”œโ”€โ”€ requirements.txt         # Python requirements for backend development
โ”‚   โ””โ”€โ”€ .env.example
โ”œโ”€โ”€ mobile/
โ”‚   โ”œโ”€โ”€ app/                         # Expo Router screens
โ”‚   โ”‚   โ””โ”€โ”€ (tabs)/
โ”‚   โ”‚       โ”œโ”€โ”€ index.tsx            # Monitor / Dashboard
โ”‚   โ”‚       โ”œโ”€โ”€ map.tsx              # Sensor Network Map
โ”‚   โ”‚       โ””โ”€โ”€ settings.tsx         # User Preferences
โ”‚   โ”œโ”€โ”€ api/                         # Axios client + TanStack Query hooks
โ”‚   โ”œโ”€โ”€ components/                  # Shared UI components
โ”‚   โ”œโ”€โ”€ store/                       # Zustand state slices
โ”‚   โ”œโ”€โ”€ context/
โ”‚   โ”‚   โ””โ”€โ”€ WebSocketContext.tsx     # Real-time alert context
โ”‚   โ””โ”€โ”€ constants/
โ”‚       โ””โ”€โ”€ config.ts                # Centralized configuration
โ”œโ”€โ”€ firmware/
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ main.cpp             # FreeRTOS tasks, STA/LTA, MQTT, provisioning
โ”‚   โ”‚   โ”œโ”€โ”€ DetectionCore.h      # Pure-C++ STA/LTA core (shared firmware/host, R1)
โ”‚   โ”‚   โ””โ”€โ”€ RingBuffer.h         # Statically allocated circular buffer
โ”‚   โ”œโ”€โ”€ tools/
โ”‚   โ”‚   โ””โ”€โ”€ detect_cli.cpp       # Native host CLI (SIL replay, same core)
โ”‚   โ”œโ”€โ”€ test/                    # Test scripts to insert into the ESP32
โ”‚   โ”œโ”€โ”€ key-generator/           # ECDSA key generator for backend testing
โ”‚   โ”œโ”€โ”€ esp32_config.env.example
โ”‚   โ”œโ”€โ”€ extra_script.py          # ENV variables injector
โ”‚   โ””โ”€โ”€ platformio.ini
โ”œโ”€โ”€ research/                    # SIL validation (ROADMAP R1)
โ”‚   โ”œโ”€โ”€ fetch_itaca.py           # ITACA download (graceful degradation) / synthetic fallback
โ”‚   โ”œโ”€โ”€ synthetic.py             # Realistic synthetic dataset generator
โ”‚   โ”œโ”€โ”€ calibrate_io.py          # Dataset layout I/O + path-injection guard
โ”‚   โ”œโ”€โ”€ orchestrator.py          # Compile & run the host C++ CLI (subprocess bridge)
โ”‚   โ”œโ”€โ”€ metrics.py               # Sensitivity, False-Alarm Rate, latency, ROC
โ”‚   โ”œโ”€โ”€ calibrate.py             # TRIGGER_RATIO x NOISE_FLOOR sweep (F1 maximization)
โ”‚   โ”œโ”€โ”€ plot_roc.py              # ROC curve figure for the paper
โ”‚   โ”œโ”€โ”€ requirements.txt         # matplotlib (optional, plotting)
โ”‚   โ””โ”€โ”€ README.md                # Dataset layout, unit conversion, licensing policy
โ””โ”€โ”€ docs/                            # Technical Documentation
    โ”œโ”€โ”€ main.typ                     # Typst Whitepaper Entrypoint
    โ”œโ”€โ”€ 01-architecture.typ          # System Architecture & Overview
    โ”œโ”€โ”€ 02-hardware.typ              # Hardware & Edge Computing (ESP32-C3)
    โ”œโ”€โ”€ 03-security.typ              # Cryptographic Security & Provisioning
    โ”œโ”€โ”€ 04-broker.typ                # Data Plane & Message Broker (MQTT)
    โ”œโ”€โ”€ 05-backend.typ               # Backend Services & Event Processing
    โ”œโ”€โ”€ 06-mobile.typ                # Mobile Client & Live Telemetry
    โ”œโ”€โ”€ 07-deployment.typ            # Deployment & CI/CD
    โ””โ”€โ”€ 08-ai.typ                    # AI Emergency Report Service (v1.2.0)

๐Ÿ”ฎ Roadmap

Version Focus
v1.0 โœ… Released โ€” edge seismic detection on ESP32, local alerts
v1.1 โœ… Released โ€” HiveMQ Cloud MQTT (TLS), ngrok HTTPS tunnel, security hardening
v1.2 โœ… Released โ€” On-Premise AI Worker (Local Ollama / Llama 3.2) for privacy-preserving emergency reports
v1.2.1 โœ… Released โ€” Geo-Zoning & Cooldown Fragmentation โ€” geohash Redis zone index (FastAPI/PostGIS source of truth), per-area cooldown, GNSS-ready data model (Sensor.last_fix_at, Reading.lat/lon), per-zone live seismograph
v1.2.2 โœ… Released โ€” Zero-Trust Serial Fallback โ€” signed telemetry over USB CDC (serial) when MQTT is unreachable
v2.0.0 โœ… Released โ€” Triangulation (multi-node spatial correlation), Hybrid Network Architecture, Automated DevOps Orchestration (Ptyxis), Local Factory Provisioning, GNSS sync, NTP+PPS, ADXL calibration, and INGV FDSN SIL validation
v2.0.1 โœ… Released โ€” Documentation & Zenodo Sync: PDF/Wiki architectural coherence (Cloudflare, 300s anti-replay), CERN-OHL hardware licensing, SIL vs Firmware threshold clarification, and CITATION.cff bump
v2.1 Data Dashboards โ€” Grafana dashboards for real-time visualization of seismic telemetry
v2.1.1 Timeseries DB & Mobile Fix โ€” migration to TimescaleDB/InfluxDB; per-sensor chart isolation in React Native mobile
v2.2 Heterogeneous Edge Intelligence โ€” hybrid Tier A (STA/LTA) + Tier B (quantized CNN) decision fusion
Future Cloud IaC โ€” Kubernetes + Terraform auto-scaling platform (see ROADMAP.md)

#Research โ€” Scientific Validation (SIL)

Node Focus
#Research Parallel ongoing node โ€” SIL cross-validation: replay of the exact production C++ STA/LTA core (DetectionCore.h) on the host via the same C++ source, Python-only as orchestrator, ROC metrics + AI benchmarking (latency P50/P99, hallucination rate). R1 pipeline (core isolation, host CLI, orchestrator, metrics, calibration) implemented; see ROADMAP.md

๐Ÿ† Awards & Recognition

QuakeGuard's architecture and real-world applicability have been recognized in the following academic and industrial contexts:

  • ๐Ÿฅ‡ 1st Place Overall - Institute Project Day (2025): Awarded best technical project out of ~20 prototypes across four engineering disciplines (Computer Science, Automation, Mechanics, Chemistry). The full-stack architecture was evaluated and awarded by an industrial jury featuring technical representatives from Siemens, ABB, SORINT.lab, SAME, Ferrero, and Confindustria.
  • ๐ŸŽ“ Academic Origin & Consultation: The system's conceptualization originated during the 2025 CQIIA-MatNet Summer School (Universitร  di Bergamo). The distributed network logic and spatial deployment strategy were subsequently refined following technical consultations with Prof. F. Finazzi.
  • ๐Ÿ… GF Marilli Competition: [Currently competing - Pending evaluation].

๐Ÿ“„ License

This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). See the LICENSE file for details.


Developed by GiZano and riccardo0731
Open Source โ€” AGPL-3.0 License

About

Distributed Earthquake Early Warning (EEW) system built on low-cost ESP32-C3 IoT sensors with Zero-Trust security, multi-node epicenter triangulation, and on-premise AI emergency reports. Includes custom PCB, FastAPI/Redis/TimescaleDB backend, and a React Native mobile app.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

18 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages