Software Architecture (FreeRTOS)
Relevant source files
The following files were used as context for generating this wiki page:The HomeSecurity system is built upon the FreeRTOS real-time operating system to manage concurrent operations on the ESP32 microcontroller. This multi-tasking architecture is fundamental to the system's ability to simultaneously monitor multiple sensors, manage network connectivity, and handle alert logic without blocking operations. By dedicating specific tasks to distinct functions, the system achieves a responsive and modular design.
The core of the architecture involves creating several tasks with varying priorities during system initialization. High-priority tasks are responsible for immediate sensor event handling, while lower-priority tasks manage background processes like sensor calibration and WiFi connection maintenance. This ensures that critical security events are processed with minimal latency.
Sources: HomeSecurity/README.md, HomeSecurity/src/main.cpp
Task Structure and Initialization
The system's concurrent behavior is defined by a set of FreeRTOS tasks created in the main setup() function. Each task is allocated a specific function, name, stack size, and priority, which dictates its scheduling behavior.
Sources: HomeSecurity/src/main.cpp:6-15
Task Creation
The following tasks are created upon system startup:
// HomeSecurity/src/main.cpp:10-15
xTaskCreate(WiFiCheckTask, "WiFiCheck", 2048, NULL, 2, NULL);
xTaskCreate(calibratePirSensorTask, "PIRCalibrate", 1536, NULL, 3, NULL);
xTaskCreate(handleHallMovementTask, "HallSensor", 2048, NULL, 4, NULL);
xTaskCreate(handlePirMovementTask, "PIRSensor", 2048, NULL, 4, NULL);
xTaskCreate(handleRadarMovementTask, "RadarSensor", 6144, NULL, 3, NULL);
xTaskCreate(possibleHumanMovementDetectedTask, "HumanMovement", 6144, NULL, 4, NULL);
Task Summary
The table below details the configuration of each FreeRTOS task.
| Task Function | Task Name | Priority | Stack Size (Bytes) | Description |
|---|---|---|---|---|
WiFiCheckTask | WiFiCheck | 2 (Low) | 2048 | Manages the WiFi connection and handles automatic reconnection. |
calibratePirSensorTask | PIRCalibrate | 3 (Medium) | 1536 | Manages the 30-second calibration period for the PIR sensor. |
handleRadarMovementTask | RadarSensor | 3 (Medium) | 6144 | Monitors the microwave radar sensor for sustained presence. |
handleHallMovementTask | HallSensor | 4 (High) | 2048 | Monitors the magnetic Hall effect sensor on a door/window. |
handlePirMovementTask | PIRSensor | 4 (High) | 2048 | Monitors the PIR sensor for initial motion detection. |
possibleHumanMovementDetectedTask | HumanMovement | 4 (High) | 6144 | Orchestrates the primary alert logic when PIR or Hall sensors are triggered. |
Sources: HomeSecurity/src/main.cpp:10-15, HomeSecurity/README.md
This diagram illustrates the priority levels of the FreeRTOS tasks.
Sources: HomeSecurity/README.md
Core Task Functions
System State and Connectivity
PIR Sensor Calibration (calibratePirSensorTask)
This task runs once at startup to manage the mandatory 30-second warm-up period for the PIR sensor. It uses a global flag pirCalibrated to signal to other tasks when the sensor is ready. Once calibration is complete, it turns on the green LED to indicate the system is armed and ready.
- Function:
calibratePirSensorTask - Logic: Waits for 30 seconds (
millis() - pirCalibrationStart >= 30000), setspirCalibratedtotrue, and activates the green LED. - Delay: Runs every 100ms (
pdMS_TO_TICKS(100)).
Sources: HomeSecurity/src/pir_sensor.cpp:11-20, HomeSecurity/include/pir_sensor.h:11
WiFi Management (WiFiCheckTask)
This is a low-priority background task responsible for maintaining a stable network connection. It periodically checks the WiFi status and, if a disconnection is detected, it calls connectToWiFi to attempt reconnection.
- Function:
WiFiCheckTask - Logic: If
WiFi.status() != WL_CONNECTED, it initiates the reconnection process. - Delay: Runs every 500ms (
pdMS_TO_TICKS(500)).
Sources: HomeSecurity/src/wifi_manager.cpp:30-38
Sensor Monitoring and Alert Logic
The system employs a two-stage alert mechanism orchestrated by several interacting tasks.
Stage 1: Initial Detection and Alert
The initial alert is triggered by either the PIR sensor or the Hall effect sensor.
handlePirMovementTask: Continuously checksisPirActive(). If motion is detected, it turns on the blue LED.handleHallMovementTask: Continuously checksisHallSensorTriggered(). If the door/window is opened, it turns on the yellow LED.possibleHumanMovementDetectedTask: This is the core of the Stage 1 alert. It checks if either the PIR or Hall sensor is active. If so, and if a notification has not already been sent (!notificareTrimisa), it performs three actions:- Calls
triggerAlarm()to activate the buzzer for 3 seconds. - Calls
notifier.sendNotification()to send a push notification via a Firebase Cloud Function. - Sets a flag (
notificareTrimisa = true) to prevent spamming alerts.
- Calls
Sources: HomeSecurity/src/motion_logic.cpp:28-72, HomeSecurity/src/alarm.cpp:16-23
Stage 2: Presence Confirmation
The second stage uses the microwave radar sensor to confirm sustained presence, reducing false alarms.
handleRadarMovementTask: This task runs in parallel. IfisRadarActive()returns true, it starts a timer.- If the radar remains active for a continuous period of 2 seconds (
millis() - radarStartTime >= 2000), it confirms human presence. - Upon confirmation, it turns on the red LED and sends a second, more urgent push notification ("Mișcare confirmată"). A flag (
notificareTrimisa) ensures this confirmation notification is only sent once per event. - If radar activity ceases, the timer and notification flag are reset.
Sources: HomeSecurity/src/motion_logic.cpp:103-126
Alert Logic Flow
The following diagram shows the complete flow from initial detection to confirmed alert.
External Communication
Firebase Notifier
The FirebaseNotifier class encapsulates the logic for sending alerts to the mobile application. It sends an HTTP POST request to a predefined Google Cloud Function URL.
- Class:
FirebaseNotifier - Method:
sendNotification(title, body, token) - Protocol: HTTPS POST
- Payload: A JSON object containing the notification title, body, and the target device's FCM token.
{
"title": "Mișcare detectată",
"body": "Sistemul a detectat o posibilă mișcare umană.",
"token": "device-fcm-token"
}
The client is configured with client.setInsecure() for development, which should be reviewed for production use.
Sources: HomeSecurity/src/firebase_notifier.cpp, HomeSecurity/include/firebase_notifier.h
Conclusion
The software architecture leverages FreeRTOS to create a robust, non-blocking, and event-driven security system. By segregating functionality into prioritized tasks, the application ensures that critical security monitoring and alerting functions are highly responsive. The two-stage alert logic, combining fast-response sensors (PIR, Hall) with a confirmation sensor (Radar), demonstrates a practical approach to minimizing false alarms, while the integration with Firebase provides a scalable and reliable notification pipeline.