/* --------------------------------------------------------------
Application: 06
Class: Real Time Systems - Sp 2026
Author: [S Candelaria]
Email: [[email protected]]
Company: [University of Central Florida]
Website: theDRACOlab.com
---------------------------------------------------------------*/
#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 1024
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //Requires by memset
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include <esp_http_server.h>
#include "esp_wifi.h"
#include "esp_event.h"
#include "freertos/event_groups.h"
#include "driver/gpio.h"
#include "driver/adc.h"
#include "math.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "driver/gpio.h"
#include <lwip/sockets.h>
#include <lwip/sys.h>
#include <lwip/api.h>
#include <lwip/netdb.h>
#define CONFIG_LOG_DEFAULT_LEVEL_INFO 1
#define CONFIG_LOG_MAXIMUM_LEVEL 5
#define STATUS_LED_PIN 5
#define BOOKED_LED_PIN 2
#define OCCUPIED_LED_PIN 4
#define BUTTON_PIN GPIO_NUM_18
#define POT_ADC_CHANNEL ADC1_CHANNEL_6 // GPIO34
#define LDR_ADC_CHANNEL ADC1_CHANNEL_4 // GPIO32
#define MAX_COUNT_SEM 10
#define POT_THRESHOLD 340 // Average skin temperature of human body in tenths of Celsius
#define LDR_THRESHOLD 20 // Maximum light reading of covered photoresistor
#define AVG_WINDOW 5
#define TEMP_THRESH_PASSED BIT0
#define LIGHT_THRESH_PASSED BIT1
static const char *TAG = "APP6"; // TAG for debug
bool occupied = false;
bool booked = false;
SemaphoreHandle_t sem_check_button;
SemaphoreHandle_t booked_mutex;
SemaphoreHandle_t occupied_mutex;
EventGroupHandle_t sensor_event_group;
#define EXAMPLE_ESP_WIFI_SSID "Wokwi-GUEST"
#define EXAMPLE_ESP_WIFI_PASS ""
#define EXAMPLE_ESP_MAXIMUM_RETRY 5
char booked_occupied_resp[] = "<!DOCTYPE html><html><head><style type=\"text/css\">html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}h1{ color: #070812; padding: 2vh;}.button { display: inline-block; background-color: #b30000; //red color border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2 { background-color: #364cf4; //blue color}.content { padding: 50px;}.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));}.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}.card-title { font-size: 1.2rem; font-weight: bold; color: #034078}</style> <title>ESP32 WEB SERVER</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" href=\"data:,\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\"></head><body> <h2>ROOM AVAILABILITY WEB SERVER</h2> <div class=\"content\"> <div class=\"card-grid\"> <div class=\"card\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>Conference Room Information</strong></p>Room Status: Occupied</p> <p>Room Schedule: Booked</p> <p> <a href=\"/check-in\"><button class=\"button\">Check-In</button></a> <a href=\"/check-out\"><button class=\"button button2\">Check-Out</button></a> </p> </div> </div> </div></body></html>";
char free_occupied_resp[] = "<!DOCTYPE html><html><head><style type=\"text/css\">html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}h1{ color: #070812; padding: 2vh;}.button { display: inline-block; background-color: #b30000; //red color border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2 { background-color: #364cf4; //blue color}.content { padding: 50px;}.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));}.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}.card-title { font-size: 1.2rem; font-weight: bold; color: #034078}</style> <title>ESP32 WEB SERVER</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" href=\"data:,\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\"></head><body> <h2>ROOM AVAILABILITY WEB SERVER</h2> <div class=\"content\"> <div class=\"card-grid\"> <div class=\"card\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>Conference Room Information</strong></p>Room Status: Occupied</p> <p>Room Schedule: Free</p> <p> <a href=\"/check-in\"><button class=\"button\">Check-In</button></a> <a href=\"/check-out\"><button class=\"button button2\">Check-Out</button></a> </p> </div> </div> </div></body></html>";
char booked_vacant_resp[] = "<!DOCTYPE html><html><head><style type=\"text/css\">html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}h1{ color: #070812; padding: 2vh;}.button { display: inline-block; background-color: #b30000; //red color border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2 { background-color: #364cf4; //blue color}.content { padding: 50px;}.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));}.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}.card-title { font-size: 1.2rem; font-weight: bold; color: #034078}</style> <title>ESP32 WEB SERVER</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" href=\"data:,\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\"></head><body> <h2>ROOM AVAILABILITY WEB SERVER</h2> <div class=\"content\"> <div class=\"card-grid\"> <div class=\"card\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>Conference Room Information</strong></p>Room Status: Vacant</p> <p>Room Schedule: Booked</p> <p> <a href=\"/check-in\"><button class=\"button\">Check-In</button></a> <a href=\"/check-out\"><button class=\"button button2\">Check-Out</button></a> </p> </div> </div> </div></body></html>";
char free_vacant_resp[] = "<!DOCTYPE html><html><head><style type=\"text/css\">html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}h1{ color: #070812; padding: 2vh;}.button { display: inline-block; background-color: #b30000; //red color border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2 { background-color: #364cf4; //blue color}.content { padding: 50px;}.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));}.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}.card-title { font-size: 1.2rem; font-weight: bold; color: #034078}</style> <title>ESP32 WEB SERVER</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" href=\"data:,\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\"></head><body> <h2>ROOM AVAILABILITY WEB SERVER</h2> <div class=\"content\"> <div class=\"card-grid\"> <div class=\"card\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>Conference Room Information</strong></p>Room Status: Vacant</p> <p>Room Schedule: Free</p> <p> <a href=\"/check-in\"><button class=\"button\">Check-In</button></a> <a href=\"/check-out\"><button class=\"button button2\">Check-Out</button></a> </p> </div> </div> </div></body></html>";
/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;
/* The event group allows multiple bits for each event, but we only care about two events:
* - we are connected to the AP with an IP
* - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
static int s_retry_num = 0;
static void event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
{
esp_wifi_connect();
}
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY)
{
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(TAG, "retry to connect to the AP");
}
else
{
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(TAG, "connect to the AP fail");
}
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
{
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void connect_wifi(void)
{
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&event_handler,
NULL,
&instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&event_handler,
NULL,
&instance_got_ip));
wifi_config_t wifi_config = {
.sta = {
.ssid = EXAMPLE_ESP_WIFI_SSID,
.password = EXAMPLE_ESP_WIFI_PASS,
/* Setting a password implies station will connect to all security modes including WEP/WPA.
* However these modes are deprecated and not advisable to be used. Incase your Access point
* doesn't support WPA2, these mode can be enabled by commenting below line */
// .threshold.authmode = WIFI_AUTH_WPA2_PSK,
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "wifi_init_sta finished.");
/* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
* number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
portMAX_DELAY);
/* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
* happened. */
if (bits & WIFI_CONNECTED_BIT)
{
ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
}
else if (bits & WIFI_FAIL_BIT)
{
ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
}
else
{
ESP_LOGE(TAG, "UNEXPECTED EVENT");
}
vEventGroupDelete(s_wifi_event_group);
}
esp_err_t send_web_page(httpd_req_t *req)
{
char* resp;
xSemaphoreTake(booked_mutex, portMAX_DELAY);
xSemaphoreTake(occupied_mutex, portMAX_DELAY);
if (booked) {
if (occupied) {
resp = booked_occupied_resp;
} else {
resp = booked_vacant_resp;
}
} else {
if (occupied) {
resp = free_occupied_resp;
} else {
resp = free_vacant_resp;
}
}
xSemaphoreGive(occupied_mutex);
xSemaphoreGive(booked_mutex);
int response = httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return response;
}
// Receive any default access request
esp_err_t get_req_handler(httpd_req_t *req)
{
return send_web_page(req);
}
// Receive request to check in to room
esp_err_t check_in_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "Web check-in button pressed");
xSemaphoreTake(booked_mutex, portMAX_DELAY);
if (!booked) {
ESP_LOGI(TAG, "Room Schedule Update: Room now booked!");
booked = true;
}
xSemaphoreGive(booked_mutex);
gpio_set_level(BOOKED_LED_PIN, 1);
return send_web_page(req);
}
// Receive request to check out of room
esp_err_t check_out_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "Web check-out button pressed");
xSemaphoreTake(booked_mutex, portMAX_DELAY);
if (booked) {
booked = false;
ESP_LOGI(TAG, "Room Schedule Update: Room now free!");
}
xSemaphoreGive(booked_mutex);
gpio_set_level(BOOKED_LED_PIN, 0);
return send_web_page(req);
}
httpd_uri_t uri_get = {
.uri = "/",
.method = HTTP_GET,
.handler = get_req_handler,
.user_ctx = NULL};
httpd_uri_t uri_check_in = {
.uri = "/check-in",
.method = HTTP_GET,
.handler = check_in_handler,
.user_ctx = NULL};
httpd_uri_t uri_check_out = {
.uri = "/check-out",
.method = HTTP_GET,
.handler = check_out_handler,
.user_ctx = NULL};
// Hard Task: Check server for bookings and update with room status
httpd_handle_t setup_server(void)
{
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.max_uri_handlers = 1024;
config.max_resp_headers = 1024;
// max_resp_headers can also be bumped if needed
// Run web server task, including URI handlers, on core 0
config.core_id = 0;
// Consider web server task as top-priority
config.task_priority = 5;
httpd_handle_t server = NULL;
if (httpd_start(&server, &config) == ESP_OK)
{
httpd_register_uri_handler(server, &uri_get);
httpd_register_uri_handler(server, &uri_check_in);
httpd_register_uri_handler(server, &uri_check_out);
}
return server;
}
// Toggle heartbeat LED at 1 Hz
void heartbeat_task(void *pvParameters) {
bool heartbeat_status = true; // Green LED state
// Set LED to state, toggle state, and cycle once per second
while (1) {
gpio_set_level(STATUS_LED_PIN, heartbeat_status);
heartbeat_status = !heartbeat_status;
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
// Read maximum temp of room's heat sensor and detect passes between threshold
void temp_sensor_task(void *pvParameters) {
TickType_t lastWakeTime = xTaskGetTickCount(); // Initialize last wake time
bool prev_below_threshold = true;
while (1) {
int val = adc1_get_raw(POT_ADC_CHANNEL);
// ESP_LOGI("Value: %d\n", val); // Display rad reading
// Gate access to reading occupied variable
if (xSemaphoreTake(occupied_mutex, portMAX_DELAY)) {
// When the room is occupied, indicate when all heat has left (below threshold)
if (occupied) {
if (val > POT_THRESHOLD && prev_below_threshold) {
prev_below_threshold = false;
ESP_LOGI(TAG, "Temp sensor event: Heat detected!\n");
xEventGroupClearBits(sensor_event_group, TEMP_THRESH_PASSED);
} else if (val <= POT_THRESHOLD && !prev_below_threshold) {
prev_below_threshold = true;
ESP_LOGI(TAG, "Temp sensor event: Heat not detected!\n");
xEventGroupSetBits(sensor_event_group, TEMP_THRESH_PASSED);
}
}
// When the room is vacant, indicate when heat has entered (above threshold)
else {
if (val > POT_THRESHOLD && prev_below_threshold) {
prev_below_threshold = false;
ESP_LOGI(TAG, "Temp sensor event: Heat detected!\n");
xEventGroupSetBits(sensor_event_group, TEMP_THRESH_PASSED);
} else if (val <= POT_THRESHOLD && !prev_below_threshold) {
prev_below_threshold = true;
ESP_LOGI(TAG, "Temp sensor event: Heat not detected!\n");
xEventGroupClearBits(sensor_event_group, TEMP_THRESH_PASSED);
}
}
xSemaphoreGive(occupied_mutex);
}
vTaskDelayUntil(&lastWakeTime, pdMS_TO_TICKS(100));
}
}
// Read minimum light of principal chair's photoresistor and detect passes through threshold
void light_sensor_task(void *pvParameters) {
//adc1_config_width(ADC_WIDTH_BIT_12);
//adc1_config_channel_atten(LDR_ADC_CHANNEL, ADC_ATTEN_DB_12); //could be ADC_ATTEN_DB_11
// Note: Completed in main function
// Variables to compute LUX
int raw;
float Vmeasure = 0.;
float Rmeasure = 0.;
float lux = 0.;
// Variables for moving average
int luxreadings[AVG_WINDOW] = {0};
int idx = 0;
float sum = 0;
// Pre-fill the readings array with an initial sample to avoid startup anomaly
for(int i = 0; i < AVG_WINDOW; ++i) {
raw = adc1_get_raw(LDR_ADC_CHANNEL);
Vmeasure = (raw / 4096.0) * 3.3; //TODO11a (Analog Value / ADC Range) * Vsource
Rmeasure = (Vmeasure * 10000) / (3.3 - Vmeasure); //TODO11b (Vmeasure * Rfix) / (Vsource - Vmeasure)
lux = pow(((50 * 1000 * pow(10.0, 0.7)) / Rmeasure), 1.0 / 0.7); //TODO11c ((RL * 1000 * 10 ** Gamma) / Rmeasured) ** (1 / Gamma)
luxreadings[i] = lux;
sum += luxreadings[i];
}
const TickType_t periodTicks = pdMS_TO_TICKS(100); // e.g. 500 ms period
TickType_t lastWakeTime = xTaskGetTickCount(); // initialize last wake time
// TickType_t currentTime = pdTICKS_TO_MS(xTaskGetTickCount()); // Last wake time in ms
// TickType_t previousTime = 0; // Previous time awake
bool prev_above_threshold = true;
while (1) {
// Update wake times
// previousTime = currentTime;
// currentTime = pdTICKS_TO_MS(xTaskGetTickCount());
// Read current sensor value
raw = adc1_get_raw(LDR_ADC_CHANNEL);
// printf("**raw **: Sensor %d\n", raw);
// Compute LUX
Vmeasure = (raw / 4096.0) * 3.3; // (Analog Value / ADC Range) * Vsources
Rmeasure = (Vmeasure * 10000) / (3.3 - Vmeasure); // (Vmeasure * Rfix) / (Vsource - Vmeasure)
lux = pow((50 * 1000 * pow(10.0, 0.7)) / Rmeasure, 1.0 / 0.7); // ((RL * 1000* 10 ** Gamma) / Rmeasured) ** (1 / Gamma)
// Update moving average buffer
sum -= luxreadings[idx]; // remove oldest value from sum
luxreadings[idx] = lux; // place new reading
sum += luxreadings[idx]; // add new value to sum
idx = (idx + 1) % AVG_WINDOW;
int avg = sum / AVG_WINDOW; // compute average
if (xSemaphoreTake(occupied_mutex, portMAX_DELAY)) {
// When the room is occupied, indicate when all heat has left (below threshold)
if (occupied) {
if (avg < LDR_THRESHOLD && prev_above_threshold) {
prev_above_threshold = false;
ESP_LOGI(TAG, "Light sensor event: Object detected!\n");
xEventGroupClearBits(sensor_event_group, LIGHT_THRESH_PASSED);
} else if (avg >= LDR_THRESHOLD && !prev_above_threshold) {
prev_above_threshold = true;
ESP_LOGI(TAG, "Light sensor event: Object not detected!\n");
xEventGroupSetBits(sensor_event_group, LIGHT_THRESH_PASSED);
}
}
// When the room is vacant, indicate when heat has entered (above threshold)
else {
if (avg < LDR_THRESHOLD && prev_above_threshold) {
prev_above_threshold = false;
ESP_LOGI(TAG, "Light sensor event: Object detected!\n");
xEventGroupSetBits(sensor_event_group, LIGHT_THRESH_PASSED);
} else if (avg >= LDR_THRESHOLD && !prev_above_threshold) {
prev_above_threshold = true;
ESP_LOGI(TAG, "Light sensor event: Object not detected!\n");
xEventGroupClearBits(sensor_event_group, LIGHT_THRESH_PASSED);
}
}
xSemaphoreGive(occupied_mutex);
}
// printf("Solar Sensor Period: %lu\n", currentTime - previousTime);
vTaskDelayUntil(&lastWakeTime, periodTicks);
}
}
// Monitor physical button press to check-in/check-out offline
void check_button_task(void *pvParameters) {
int button_active_count = 0;
bool button_activated = false;
while (1) {
int state = gpio_get_level(BUTTON_PIN);
// If ground-control button has not been confirmed active:
if (!button_activated) {
// If button has remained "ON" for more than 5 polls:
if (button_active_count > 5){
ESP_LOGI(TAG, "Physical button pressed!\n");
// Indicate button is active, give semaphore, and reset count
button_activated = true;
button_active_count = 0;
xSemaphoreGive(sem_check_button); // Signal mode change event
// If button is currently "ON", increment count
} else if (state == 0) {
button_active_count++;
// Reset count upon button bouncing back to "OFF"
} else {
button_active_count = 0;
}
}
// If button has been let go ("OFF"), indicate button is inactive
else if (state == 1) {
button_activated = false;
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}
// // Hard Task: Update occupied status and current room schedule based on sensor and button events
void event_handler_task(void *pvParameters) {
TickType_t lastWakeTime = xTaskGetTickCount();
while (1) {
EventBits_t sensor_bits = xEventGroupWaitBits(sensor_event_group, TEMP_THRESH_PASSED | LIGHT_THRESH_PASSED, true, true, 0);
// If sensors both activate, update occupancy and booked status
if (sensor_bits == (TEMP_THRESH_PASSED | LIGHT_THRESH_PASSED)) {
xSemaphoreTake(occupied_mutex, portMAX_DELAY);
// If the room was occupied, set to vacant and clear booking
if (occupied) {
ESP_LOGI(TAG, "Room Status Update: Room now vacant!\n");
occupied = false;
xSemaphoreTake(booked_mutex, portMAX_DELAY);
if (booked) {
ESP_LOGI(TAG, "Room Schedule Update: Room now free!\n");
booked = false;
gpio_set_level(BOOKED_LED_PIN, 0);
}
xSemaphoreGive(booked_mutex);
gpio_set_level(OCCUPIED_LED_PIN, 0);
// Else, set to occupied
} else {
ESP_LOGI(TAG, "Room Status Update: Room now occupied!\n");
occupied = true;
gpio_set_level(OCCUPIED_LED_PIN, 1);
}
xSemaphoreGive(occupied_mutex);
xEventGroupClearBits(sensor_event_group, TEMP_THRESH_PASSED | LIGHT_THRESH_PASSED);
}
// If on-board button is pressed, check-in to / check-out of room
if (xSemaphoreTake(sem_check_button, 0)) {
xSemaphoreTake(booked_mutex, portMAX_DELAY);
if (booked) {
ESP_LOGI(TAG, "Room Schedule Update: Room now free!\n");
booked = false;
gpio_set_level(BOOKED_LED_PIN, 0);
} else {
ESP_LOGI(TAG, "Room Schedule Update: Room now booked!\n");
booked = true;
gpio_set_level(BOOKED_LED_PIN, 1);
}
xSemaphoreGive(booked_mutex);
}
vTaskDelayUntil(&lastWakeTime, pdMS_TO_TICKS(10)); // Idle delay to yield CPU
}
}
void app_main() {
esp_log_level_set(TAG, ESP_LOG_INFO);
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
connect_wifi();
// GPIO initialization
gpio_reset_pin(STATUS_LED_PIN);
gpio_set_direction(STATUS_LED_PIN, GPIO_MODE_OUTPUT);
gpio_reset_pin(OCCUPIED_LED_PIN);
gpio_set_direction(OCCUPIED_LED_PIN, GPIO_MODE_OUTPUT);
gpio_reset_pin(BOOKED_LED_PIN);
gpio_set_direction(BOOKED_LED_PIN, GPIO_MODE_OUTPUT);
// Configure input button
gpio_config_t btn_conf = {
.pin_bit_mask = (1ULL << BUTTON_PIN),
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE
};
gpio_config(&btn_conf);
// Configure ADC
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(POT_ADC_CHANNEL, ADC_ATTEN_DB_11);
adc1_config_channel_atten(LDR_ADC_CHANNEL, ADC_ATTEN_DB_11);
// Create sync primitives
sem_check_button = xSemaphoreCreateBinary();
booked_mutex = xSemaphoreCreateMutex();
occupied_mutex = xSemaphoreCreateMutex();
sensor_event_group = xEventGroupCreate();
// Set up web server
ESP_LOGI(TAG, "Room Availability Web Server is running ... ...\n");
setup_server();
// Create tasks running on Core 1
xTaskCreatePinnedToCore(heartbeat_task, "heartbeat", 2048, NULL, 0, NULL, 1); // Lowest priority to check for system stall
xTaskCreatePinnedToCore(temp_sensor_task, "temp_sensor", 2048, NULL, 1, NULL, 1); // Moderate priority to consistently read temperature data
xTaskCreatePinnedToCore(light_sensor_task, "light_sensor", 2048, NULL, 1, NULL, 1); // Moderate priority to consistently read temperature data
xTaskCreatePinnedToCore(check_button_task, "check_button", 2048, NULL, 2, NULL, 1); // High priority to more consistently check for button press
xTaskCreatePinnedToCore(event_handler_task, "event_handler", 2048, NULL, 3, NULL, 1); // Second-to-top priority to handle on-board events
}