Core Infrastructure
RAFIQ Core Engine
The central orchestration layer running on Ubuntu Server. Manages all services, event loops, threading models, offline execution, and system lifecycle — independently of any cloud connectivity.
Core Services · 8 components
FastAPI Application Server
Uvicorn · ASGI · async/await
Main HTTP and WebSocket server. Handles REST API, WebSocket connections, and event broadcasting. Runs on asyncio event loop with worker threads for CPU-bound AI tasks.
SQLite + WAL Engine
Write-Ahead Logging · Local-first
Primary local database with WAL mode for concurrent reads. Stores all patient data, events, AI logs, and sync queues. Zero network dependency for reads/writes.
MQTT Broker (Mosquitto)
Eclipse Mosquitto · QoS 0/1/2
Central message bus for all sensor data, device commands, and event notifications. Runs locally on port 1883, supports retained messages and last-will-testament.
AI Decision Engine
Ollama · MedGemma · Rule Engine
Orchestrates AI inference requests across local LLMs. Applies health rules, generates interventions, classifies emergencies, and manages conversational memory.
Emergency Engine
Real-time · Local-only · Fail-secure
Standalone safety processing loop that never depends on cloud or AI. Evaluates raw sensor thresholds, triggers valve shutdowns, activates sirens, and sends emergency SMS.
Sync Engine
SQLite ↔ Supabase · Retry Queue
Background service for bidirectional cloud synchronization. Maintains an offline queue when Supabase is unreachable, replays on reconnect with conflict resolution.
Home Assistant Bridge
HA API · Automation · MQTT
Bidirectional bridge between RAFIQ core and Home Assistant. Subscribes to HA events via WebSocket API and publishes device commands through MQTT.
Local Cache Layer
In-memory · TTL · LRU
High-speed in-memory cache for frequently accessed data: recent wearable readings, AI responses, device states, and authentication tokens. Python dict + TTL expiry.
Threading Model
Python asyncio event loop + OS threads for blocking operations
| Thread / Task | Type | Responsibility |
|---|---|---|
| Main Event Loop | asyncio | HTTP, WebSocket, MQTT subscribe, coroutine scheduling |
| AI Worker Pool | ThreadPool | Ollama inference calls (blocking I/O, CPU-bound) |
| Emergency Watchdog | Thread | Sensor threshold polling — never blocked by async queue |
| Sync Background Task | asyncio Task | Supabase push/pull cycle every 30 seconds |
| MQTT Publisher | asyncio | Outbound MQTT messages to broker |
| STT/TTS Pipeline | Thread | Voice stream processing (Whisper, Piper TTS) |
Startup Sequence
# RAFIQ Core startup sequence
async def startup():
# 1. Initialize SQLite with WAL mode
await db.connect(pragmas={"journal_mode": "WAL", "cache_size": -65536})
# 2. Run Alembic migrations
await run_migrations()
# 3. Connect to MQTT broker
await mqtt_client.connect(host="localhost", port=1883)
await mqtt_client.subscribe("rafiq/#", qos=1)
# 4. Start background services
asyncio.create_task(sync_engine.run())
asyncio.create_task(emergency_engine.run())
asyncio.create_task(ai_orchestrator.warmup())
# 5. Initialize Home Assistant bridge
await ha_bridge.connect(token=settings.HA_TOKEN)
# 6. Ready signal
logger.info("RAFIQ Core online — all services initialized")Shutdown Lifecycle
# Graceful shutdown sequence
@app.on_event("shutdown")
async def shutdown():
# 1. Stop accepting new requests
# 2. Complete in-flight AI requests (max 5s timeout)
await asyncio.wait_for(ai_orchestrator.drain(), timeout=5.0)
# 3. Flush sync queue to disk
await sync_engine.flush_to_disk()
# 4. Close MQTT cleanly (send LWT disconnect)
await mqtt_client.disconnect(reasoncode=0)
# 5. Checkpoint SQLite WAL
await db.execute("PRAGMA wal_checkpoint(FULL)")
await db.disconnect()
logger.info("RAFIQ Core shutdown complete")Local-first Storage
All writes go to SQLite first. Supabase sync is a background best-effort operation. No write is ever lost due to network failure.
Local AI Inference
Ollama runs entirely on-device. AI reasoning, health analysis, and emergency classification work without any internet connection.
Emergency Independence
Emergency engine operates on raw sensor data with zero AI/cloud dependency. Gas valve control, sirens, SMS — all fully local.