Skip to content
GiZano edited this page Jul 29, 2026 · 2 revisions

🌋 QuakeGuard Technical Wiki

Welcome to the official technical documentation for the QuakeGuard project (Release v1.1.0).

Table of Contents

  1. System Architecture & Overview
  2. Hardware & Edge Computing
  3. Cryptographic Security & Provisioning
  4. Data Plane & Message Broker
  5. Backend Services & Event Processing
  6. Mobile Client & Live Telemetry
  7. Deployment & Operations Guide

1. System Architecture & Overview

QuakeGuard is a distributed, high-throughput backend system designed for the real-time ingestion, cryptographic validation, and processing of seismic data from IoT devices. It serves as the core infrastructure for an Earthquake Early Warning (EEW) system. The architecture is explicitly designed to handle high-concurrency event firehosing during seismic swarms while maintaining strict security boundaries.

High-Level Topology

The infrastructure is decoupled into three primary tiers:

  • Edge Layer (IoT): Composed of ESP32-C3 SuperMini microcontrollers interfaced with ADXL345 digital accelerometers. These nodes execute on-device Digital Signal Processing (DSP) using the STA/LTA algorithm.
  • Core Backend & Processing: A polyglot backend architecture utilizing FastAPI (Python) as the API gateway. Validated data is asynchronously offloaded to a Redis message queue (seismic_events) and consumed by a background worker.
  • Client Presentation Layer: A React Native (Expo) mobile application providing users with real-time seismograph telemetry and instantaneous critical event notifications.

Data Plane and Control Plane

Following the v1.1.0 cloud migration, the architecture strictly separates pipelines:

  • Data Plane (Telemetry): Flows exclusively through a HiveMQ Cloud Serverless broker on port 8883 (authenticated and TLS-encrypted). A Python MQTT bridge (mqtt_subscriber.py) forwards payloads to the internal FastAPI ingestion pipeline.
  • Control Plane (Provisioning & Management): Device onboarding, cryptographic handshakes, and REST retrieval operations are routed through an ngrok HTTPS tunnel, directly exposing FastAPI endpoints.

2. Hardware & Edge Computing (ESP32-C3)

The edge layer operates on resource-constrained microcontrollers, specifically the ESP32-C3 SuperMini (RISC-V architecture).

Hardware Configuration

Due to the specific physical layout, the I2C bus is software-mapped to non-standard GPIO pins:

  • SDA (Data): GPIO 7 (requires internal pull-up).
  • SCL (Clock): GPIO 8 (requires internal pull-up).
  • Power: The ADXL345 is powered strictly via the 3.3V rail.

The sensor operates at a 100Hz sampling rate (ADXL345_DATARATE_100_HZ) with a measurement range of ±16G.

Digital Signal Processing (DSP) Pipeline

  • High-Pass Filter (HPF): A digital filter (HPF_ALPHA = 0.9f) isolates dynamic vibration data by subtracting the static DC component (Earth's gravity).
  • Noise Gate: Micro-vibrations below the empirical threshold of 0.04G are clamped to zero to prevent false positives from electrical noise.
  • Dropout Protection: The firmware automatically drops frames reporting near-zero absolute acceleration (< 2.0 $m/s^2$ prior to filtering), mitigating corrupted readings from I2C disconnects.

STA/LTA Seismic Detection Algorithm

The implementation utilizes a custom, memory-efficient RingBuffer template class in C++ to maintain rolling sums for $O(1)$ average calculations:

  • Short-Term Window (STA): 100 samples (1 second).
  • Long-Term Window (LTA): 1000 samples (10 seconds).
  • Trigger Condition: An earthquake is registered when the STA/LTA ratio exceeds 1.8f, provided the STA absolute value is above the noise floor.

3. Cryptographic Security & Provisioning

QuakeGuard implements a Zero-Trust security model for its IoT edge nodes.

Cryptographic Identity (ECDSA)

Upon its first boot, the ESP32-C3 uses mbedtls to generate a unique ECDSA key pair using the NIST P-256 curve (secp256r1).

  • Private Key: Stored permanently in Non-Volatile Storage (NVS) to sign outgoing telemetry.
  • Public Key: Extracted in DER format, acting as the unforgeable cryptographic identity of the sensor.

Automated Provisioning Handshake

  1. The device sends a POST to /devices/register with its public_key_hex, MAC address, coordinates, and ENROLLMENT_TOKEN.
  2. The backend validates the token and uses PostGIS (ST_Contains) to assign the sensor to the smallest containing geographic polygon.
  3. A unique sensor_id is returned and saved to NVS.

Payload Authentication

Telemetry payloads (value:timestamp) are hashed via SHA-256 and signed with the private key. The validate_iot_payload dependency pipeline enforces:

  1. API Key Verification: Constant-time hmac.compare_digest check.
  2. Sensor Status: Verifies the sensor ID is active.
  3. Anti-Replay Protection: Rejects payloads older than a 300-second threshold.
  4. Signature Verification: Uses the Python cryptography library to verify the ECDSA signature against the device's public key.

4. Data Plane & Message Broker (MQTT)

With v1.1.0, QuakeGuard migrated its Data Plane from HTTP/local MQTT to a robust cloud infrastructure.

HiveMQ Cloud Infrastructure

  • Encrypted Transport: Telemetry is transmitted over port 8883 using strict TLS.
  • Authentication: Requires explicit MQTT_USERNAME and MQTT_PASSWORD.
  • Topic Topology: Anomalies are published to quakeguard/telemetry.

Internal MQTT Bridge Service

The backend securely ingests data via mqtt_subscriber.py.

  • Uses paho.mqtt.client with secure TLS settings (client.tls_set).
  • Forwards payloads to the internal FastAPI ingestion endpoint (/readings/) via HTTP POST.
  • Injects the X-API-Key header, acting as a trusted proxy.

5. Backend Services & Event Processing

API Gateway

  • Rate Limiting: Protects against DoS via a sliding-window rate limiter in Redis (50 req/s per IP).
  • Queue Offloading: Validated payloads are non-blockingly serialized and pushed to a Redis List (seismic_events), returning a 202 Accepted immediately.

Background Worker & Persistence

A decoupled Python worker (worker.py) consumes the seismic_events queue via a blocking brpop.

  • Shares a highly optimized SQLAlchemy connection pool targeting PostgreSQL/PostGIS.
  • Evaluates the alarm logic within a single, atomic database transaction (db.commit()).

Magnitude Estimation & Deduplication

The worker estimates physical magnitude based on a MyShake-style MEMS calibration approach:

$$ M_{IoT} = \log_{10}(PGA_{calib}) + b $$

Where $PGA_{calib}$ accounts for the hardware calibration constant (K_CALIBRATION = 1.6), and $b$ is an empirical offset (B_OFFSET = 3.0).

  • Thresholding: Triggers an Alert if the magnitude reaches or exceeds 4.5.
  • Redis Deduplication: Uses an atomic check-and-set (SET nx=True, ex=60) keyed by zone_id to enforce a 60-second cooldown per zone, preventing notification spam during a swarm.
  • Outbox Pattern: Publishes the JSON payload to the quake_alerts Redis Pub/Sub channel.

6. Mobile Client & Live Telemetry

Built with React Native and Expo, the client serves as the primary EEW notification interface.

Real-Time Alerting (WebSockets)

  • Connection: Maintains a persistent WebSocket to /ws/alerts, authenticated via MOBILE_WS_TOKEN with exponential backoff.
  • Native Haptics & Notifications: "CRITICAL" payloads trigger an SOS vibration pattern and schedule a high-priority system push notification (AndroidImportance.MAX).

Telemetry Visualization

  • Data Fetching: Standard REST operations are managed by TanStack Query for automatic caching and background refetching.
  • Live Seismograph: Uses victory-native to render a dynamic line chart of aggregated seismic activity.
  • Geospatial Map: react-native-maps displays custom markers based on exact PostGIS coordinates, colored by active/offline status.

Resilience (Zustand)

  • Alert Store: useAlertStore maintains a rolling history of the 10 most recent alerts.
  • Offline Mode: usePreferencesStore controls an "Offline Mode" that intentionally closes WebSockets and disables React Query polling to conserve battery.

7. Deployment & Operations Guide

This section outlines the procedures for provisioning the QuakeGuard infrastructure.

Prerequisites

  • Backend: Docker Engine & Docker Compose.
  • Edge (IoT): VS Code + PlatformIO extension.
  • Mobile: Node.js (v18+) & Expo Go app.

Backend Provisioning

  1. Navigate to backend/api.
  2. Copy the environment variables: cp .env.example .env and fill in your HiveMQ credentials.
  3. Launch the stack:
docker compose up --build -d
  1. Verify health at http://localhost:8000/health.

Edge Node Flashing

  1. Navigate to firmware/esp32_code.
  2. Copy the config: cp esp32_config.env.example esp32_config.env.
  3. Update WiFi credentials, SERVER_HOST, and ENROLLMENT_TOKEN.
  4. Flash via PlatformIO.
  5. Open Serial Monitor (115200 baud) to verify successful automated registration.

Mobile Client Initialization

  1. Navigate to mobile/ and run npm install.
  2. Create a .env file mapping your backend secrets and IP:
EXPO_PUBLIC_IOT_API_KEY=your_secret_key
EXPO_PUBLIC_MOBILE_WS_TOKEN=your_ws_token
EXPO_PUBLIC_API_BASE_URL=http://YOUR_LOCAL_IP:8000
  1. Run npx expo start and scan the QR code with your smartphone.

System Certification (Stress Test)

Validate your infrastructure by simulating a 150-node seismic swarm:

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

A successful run ends with 🏆 SYSTEM CERTIFIED.