Infrastructure · Pipeline
Data Flow Architecture
End-to-end data pipelines from physical sensors through edge computing, MQTT messaging, local AI inference, and cloud synchronization. Every hop is designed for offline-first reliability with deterministic latency bounds.
Pipeline 01 · Health Monitoring
🔵 Monitoring Path
Health Monitoring Pipeline
Continuous biometric data flow from wearable sensor through local AI analysis to cloud sync
ESP32 + MAX30102
Sensor2.4GHz · GATT Profile
BLEBLE→WiFi Bridge
BridgeMosquitto v2 · QoS 1
MQTTFastAPI · Python 3.12
AsyncWAL · In-process DB
WALMedGemma 4B · Ollama
llama.cppRule evaluation · CEP
InternalPostgreSQL · REST API
HTTPSFlutter · Push Notify
PushPipeline 02 · Emergency Response
🔴 Emergency Path
Emergency Response Pipeline
Life-critical gas detection with local-first hardware failsafe and multi-channel alerting
MQ-2 · MQ-7 · MQ-135
ADCDedicated safety MCU
GPIONo cloud dependency
LocalGPIO · Relay control
GPIOQoS 2 · Retained
MQTTEmergency type ID
OllamaTwilio · Fallback SIM
SMSFCM · Critical alert
FCMHome Assistant · YAML
MQTT→HA- ›Sensor → BLE → MQTT: sequential, blocking per packet
- ›GPIO relay control: hardware interrupt, <1ms guaranteed
- ›SQLite WAL write: synchronous before ACK
- ›Local threshold evaluation: immediate decision, no network
- ›Emergency MQTT publish QoS 2: requires broker confirmation
- ›AI inference via asyncio.create_task() — never blocks main loop
- ›Supabase sync runs in background queue with exponential retry
- ›Push notifications dispatched post-decision asynchronously
- ›SMS gateway call fire-and-forget with separate delivery tracking
- ›HA automations triggered via MQTT retain — eventual consistency
Execution Timeline (example: wearable HR packet)
↗ = async dispatch (does not block main pipeline) · Timeline not to scale
Latency Class Reference
Per-hop timing characteristics across the data pipeline
| Component | Protocol/Mode | Typical Latency | Max Latency | Async? |
|---|---|---|---|---|
| BLE Transport | Bluetooth 5.0 | 10ms | 50ms | No |
| WiFi (ESP32→Router) | 802.11n 2.4GHz | 2ms | 15ms | No |
| MQTT Publish | MQTT v3.1.1 | 5ms | 20ms | No (QoS 1) |
| SQLite WAL Write | WAL Journal | 1ms | 5ms | No |
| Core Engine Dispatch | asyncio | 0.5ms | 3ms | Yes |
| MedGemma Inference | llama.cpp/Ollama | 160ms | 300ms | Yes |
| Decision Engine | Internal Python | 1ms | 5ms | No |
| Supabase REST Sync | HTTPS/REST | 250ms | 2000ms | Yes (queue) |
| SMS Gateway | Twilio API | 1.5s | 5s | Yes |
| FCM Push | Firebase FCM | 300ms | 1000ms | Yes |
| GPIO Relay | ESP32 GPIO | 0.1ms | 1ms | No (hardware) |
| HA Automation | MQTT→HA WS | 80ms | 250ms | Yes |
- ·All outbound records written to sync_queue table before cloud push attempt
- ·Queue is durable — persists across process restarts and power cycles
- ·Each entry: table, operation (INSERT/UPDATE/DELETE), payload_json, retries, status
- ·Worker polls queue every 30s; on cloud availability, drains in FIFO order
- ·First retry: 30s · Second: 2min · Third: 10min · Fourth+: 1 hour cap
- ·Jitter factor ±20% added to prevent synchronized thundering herd
- ·Failed entries after 5 retries → moved to dead_letter_queue table
- ·Dead letter queue is manually reviewed via admin API: GET /api/sync/dead-letter
- ·Last-write-wins strategy using updated_at UTC timestamps
- ·Wearable metrics never conflict (append-only by device_id + timestamp)
- ·User settings: server wins unless local version has unseen field changes
- ·Emergency events: always preserved, never overwritten by cloud version
- ·Emergency alerts use MQTT QoS 2 (exactly-once delivery guarantee)
- ·SMS via Twilio with delivery receipt polling — retries until confirmed
- ·Critical events stored locally with status=unconfirmed until acked by server
- ·Separate emergency sync channel runs independently of normal sync pipeline
MQTT Subscriber Pattern
import asyncio
import json
import logging
from datetime import datetime
import aiomqtt
from sqlalchemy.ext.asyncio import AsyncSession
from rafiq.core.db import get_session
from rafiq.ai.orchestrator import AIOrchestrator
from rafiq.decision.engine import DecisionEngine
logger = logging.getLogger("mqtt-subscriber")
BROKER_HOST = "localhost"
BROKER_PORT = 1883
SUBSCRIPTIONS = [
("rafiq/wearable/#", 1), # Biometrics — QoS 1
("rafiq/emergency/#", 2), # Emergency alerts — QoS 2
("rafiq/home/#", 1), # Home events — QoS 1
("rafiq/ai/#", 0), # AI responses — QoS 0
]
async def handle_wearable(topic: str, payload: dict, session: AsyncSession) -> None:
"""Process incoming wearable sensor readings."""
metric_type = topic.split("/")[-1] # heartrate | spo2 | steps
# 1. Persist to SQLite immediately (WAL mode, <5ms)
await session.execute(
"INSERT INTO wearable_metrics (type, value, ts) VALUES (:t, :v, :ts)",
{"t": metric_type, "v": payload.get("value"), "ts": datetime.utcnow()},
)
await session.commit()
# 2. Dispatch to AI asynchronously (non-blocking)
asyncio.create_task(
AIOrchestrator.analyze_health(metric_type, payload)
)
async def handle_emergency(topic: str, payload: dict) -> None:
"""Handle emergency events — priority path, no async delay."""
event_type = payload.get("type", "unknown")
severity = payload.get("severity", "medium")
logger.critical(f"[EMERGENCY] {event_type} @ severity={severity}")
# Decision engine runs synchronously for emergencies
decision = await DecisionEngine.evaluate_emergency(event_type, severity)
await decision.execute() # Triggers GPIO, SMS, push
async def mqtt_subscriber_loop() -> None:
"""Main MQTT subscriber coroutine with auto-reconnect."""
async with aiomqtt.Client(BROKER_HOST, BROKER_PORT) as client:
# Subscribe to all topic patterns
for topic, qos in SUBSCRIPTIONS:
await client.subscribe(topic, qos=qos)
logger.info(f"Subscribed: {topic} (QoS {qos})")
async with client.messages() as messages:
async for message in messages:
topic = str(message.topic)
payload = json.loads(message.payload.decode())
try:
async with get_session() as session:
if topic.startswith("rafiq/wearable/"):
await handle_wearable(topic, payload, session)
elif topic.startswith("rafiq/emergency/"):
await handle_emergency(topic, payload)
except Exception as exc:
logger.error(f"Subscriber error [{topic}]: {exc}")
if __name__ == "__main__":
asyncio.run(mqtt_subscriber_loop())Local First
Every critical operation (emergency response, health writes, AI inference) runs without cloud. Cloud sync is additive, never critical path.
Deterministic Emergency
Gas sensor → valve shutdown path is hardware-guaranteed at <5ms using GPIO. AI classification follows asynchronously.
Bounded Latency
AI inference is capped at 300ms by llama.cpp timeout. All UI interactions stay responsive via async task dispatch.