4 Sensors Active
Safety LayerESP32 v1.3
Gas Sensors4 MQ Array
Response<50ms
OfflineCapable

Safety Layer

RAQEEB Safety Monitor

RAQEEB is a hardware-level safety monitoring system built on ESP32. It operates completely independently of the MiniPC — gas detection, valve control, and SMS alerts function even when RAFIQ Core is offline or unreachable.

System Components

MQ Sensor Array

4-gas detection · ADC inputs

MQ-2, MQ-4, MQ-7, MQ-135 sensors cover LPG, methane, CO, and CO₂. Each sensor uses analog voltage divider circuit read by ESP32's 12-bit ADC. Calibrated Ro values stored in firmware.

Sensors
MQ-2/4/7/135
ADC
12-bit
Sample
500ms
AnalogADCCalibrated

ESP32 Emergency MCU

Dual-core · Offline capable

ESP32 runs FreeRTOS with a dedicated safety task on Core 0. Network stack runs on Core 1. Emergency logic executes regardless of WiFi/MQTT availability — valve control is hardware-direct.

CPU
240MHz dual
RAM
520KB
Core
FreeRTOS
ESP32FreeRTOSOffline

Valve Controller

NC Relays · Failsafe closed

Normally-Closed (NC) relay configuration means power loss = valves closed. ESP32 holds relays open during normal operation; any firmware crash or power cut defaults to safe state.

Valves
2 zones
Type
NC Relay
Latency
<50ms
NC RelayFailsafeGPIO

SMS Gateway

SIM800L · GSM fallback

SIM800L GSM module provides offline SMS capability. When internet is unavailable, ESP32 sends emergency alerts via cellular network directly — completely independent of Supabase or internet.

Module
SIM800L
Network
GSM 2G
Fallback
Yes
GSMSIM800LSMS

MQTT Bridge

Bidirectional · QoS 2

ESP32 publishes sensor telemetry to MQTT broker every 500ms and subscribes to control commands from RAFIQ Core. Emergency messages use QoS 2 with retain flag for guaranteed delivery.

Pub
500ms cycle
QoS
0 / 2
Retain
Emergency
MQTTQoS 2Non-blocking

MQ Sensor Array — Thresholds & GPIO

ppm thresholds calibrated for residential environment

SensorGas DetectedThresholdAction TriggeredGPIO PinCalibration
MQ-2LPG / Propane / Smoke1000 ppmValve OFF + Siren + SMSGPIO34 (ADC)Ro = 9.83kΩ
MQ-4Methane / Natural Gas800 ppmValve OFF + Siren + SMSGPIO35 (ADC)Ro = 4.15kΩ
MQ-7Carbon Monoxide (CO)50 ppmAlarm + Ventilate + CallGPIO32 (ADC)Ro = 27.5kΩ
MQ-135CO₂ / Air Quality2000 ppmOpen windows + AlertGPIO33 (ADC)Ro = 41.7kΩ
Emergency State MachineRAQEEB safety state transitions
NORMAL

All sensors below threshold. Valves open. MQTT telemetry publishing every 500ms.

→ ALERT if any sensor > 80% threshold
ALERT

Pre-threshold warning. Increase sampling to 100ms. Send alert to RAFIQ Core.

→ EMERGENCY if > threshold
→ NORMAL if clears
EMERGENCY

Valves CLOSE immediately. Siren ON. SMS sent. MQTT emergency published.

→ SHUTDOWN after 30s unacknowledged
→ NORMAL on manual reset
SHUTDOWN

All outputs OFF except siren. Requires physical MCU reset + manual valve inspection.

→ NORMAL only via hard reset

ESP32 GPIO Pin Assignments

hardware mapping for all RAQEEB peripherals

GPIO PinRole / DeviceTypeLogic LevelNotes
GPIO4Gas Valve Relay 1 (Kitchen)OUTPUTActive LOWNC relay — failsafe closed
GPIO5Gas Valve Relay 2 (Bathroom)OUTPUTActive LOWNC relay — failsafe closed
GPIO16Siren RelayOUTPUTActive HIGH12V piezo siren module
GPIO17GSM Module UART TXUARTSerial 9600SIM800L for SMS fallback
GPIO18Status LED (Red)OUTPUTActive HIGHEmergency indicator
GPIO19Status LED (Green)OUTPUTActive HIGHNormal operation
GPIO34MQ-2 Analog InputADC1_CH6Analog 0–3.3V12-bit ADC, attn 11dB
GPIO35MQ-4 Analog InputADC1_CH7Analog 0–3.3V12-bit ADC, attn 11dB
Local-First Safety Guaranteeoffline operation architecture
When RAFIQ Core is Down
  • ESP32 sensors continue reading every 500ms
  • Threshold logic runs on MCU independently
  • Valve relay control fires via GPIO directly
  • Siren activates via GPIO relay
  • SMS sent via SIM800L GSM module
  • MQTT publish to Core (queued locally)
  • Supabase event logging (synced on reconnect)
When RAFIQ Core is Online
  • Full telemetry stream to Core via MQTT QoS 0
  • Core forwards sensor data to AI for anomaly detection
  • Emergency events logged to SQLite + sync queue
  • Home Assistant automation triggered via MQTT
  • Real-time dashboard updates via WebSocket
  • Historical trend analysis by AI engine
  • Remote configuration of thresholds via MQTT command

Firmware Implementation

raqeeb_safety/main.cpp
cpp
// RAQEEB ESP32 — Emergency Threshold Logic (Arduino C++)

#include <Arduino.h>
#include <PubSubClient.h>
#include <WiFi.h>
#define VALVE_1_PIN    4    // Kitchen gas valve relay (NC — active LOW)
#define VALVE_2_PIN    5    // Bathroom gas valve relay (NC — active LOW)
#define SIREN_PIN      16   // Emergency siren (active HIGH)
#define MQ2_PIN        34   // LPG/Propane sensor (ADC)
#define MQ4_PIN        35   // Methane sensor (ADC)
#define MQ7_PIN        32   // CO sensor (ADC)
#define MQ135_PIN      33   // CO2/Air quality sensor (ADC)
#define MQ2_THRESHOLD  1000  // ppm
#define MQ4_THRESHOLD  800   // ppm
#define MQ7_THRESHOLD  50    // ppm
#define MQ135_THRESHOLD 2000 // ppm
enum SafetyState { NORMAL, ALERT, EMERGENCY, SHUTDOWN };
SafetyState currentState = NORMAL;
bool mqttConnected = false;
unsigned long lastMqttRetry = 0;
const unsigned long MQTT_RETRY_INTERVAL = 5000;
float readPPM(int pin, float Ro, float a, float b) {
  int raw = analogRead(pin);
  float voltage = raw * (3.3f / 4095.0f);
  float Rs = ((3.3f - voltage) / voltage) * 10.0f; // load resistance = 10kΩ
  float ratio = Rs / Ro;
  return a * pow(ratio, b);
}
void triggerEmergency(const char* reason) {
  digitalWrite(VALVE_1_PIN, LOW);   // NC relay — close
  digitalWrite(VALVE_2_PIN, LOW);   // NC relay — close
  digitalWrite(SIREN_PIN, HIGH);    // Sound alarm
  
  Serial.printf("[EMERGENCY] %s — Valves CLOSED, Siren ON\n", reason);
  currentState = EMERGENCY;
  if (mqttConnected) {
    String payload = String("{"type":"GAS","reason":"") + reason +
                     "","ts":" + millis() + "}";
    mqttClient.publish("rafiq/raqeeb/emergency", payload.c_str(), true);
  }
  sendSMS("+966XXXXXXXXX", String("RAQEEB ALERT: ") + reason);
}

void loop() {
  float mq2_ppm  = readPPM(MQ2_PIN,  9.83, 574.25, -2.222);
  float mq4_ppm  = readPPM(MQ4_PIN,  4.15, 1012.7, -2.786);
  float mq7_ppm  = readPPM(MQ7_PIN,  27.5, 99.042, -1.518);
  float mq135_ppm = readPPM(MQ135_PIN, 41.7, 116.6, -2.769);
  if (mq2_ppm > MQ2_THRESHOLD) triggerEmergency("LPG_PROPANE_HIGH");
  if (mq4_ppm > MQ4_THRESHOLD) triggerEmergency("METHANE_HIGH");
  if (mq7_ppm > MQ7_THRESHOLD) triggerEmergency("CO_HIGH");
  if (mqttConnected) {
    String telemetry = String("{") +
      "\"mq2\":" + mq2_ppm + "," +
      "\"mq4\":" + mq4_ppm + "," +
      "\"mq7\":" + mq7_ppm + "," +
      "\"mq135\":" + mq135_ppm + "," +
      "\"state\":\"" + stateToString(currentState) + "\"" +
      "}";
    mqttClient.publish("rafiq/raqeeb/telemetry", telemetry.c_str());
  }

  delay(500);
}
Emergency Response Timelinegas detected to full response
0ms
MQ sensor ADC read exceeds threshold
ESP32 MCU
<50ms
Valve relay opens — gas flow stopped
GPIO Direct
<50ms
Siren relay activates
GPIO Direct
<100ms
MQTT emergency topic published (QoS 2)
ESP32 WiFi
<150ms
Home Assistant automation triggers
HA Core
<200ms
Curtains/windows commanded open
MQTT/Zigbee
<500ms
RAFIQ Core logs emergency event to SQLite
Core Python
<2s
SMS notification dispatched
SIM800L
<5s
AI system generates incident report
MedGemma