refact auth 2

This commit is contained in:
2025-06-08 10:11:09 +01:00
parent 214cf1ee04
commit 25744de46c
2 changed files with 90 additions and 13 deletions

View File

@@ -8,7 +8,10 @@
#include <freertos/queue.h>
#include <esp_log.h>
#include <string.h>
#include "wiegand_reader.h" // necessário para initWiegand()
#include "wiegand_reader.h"
#include "nvs_flash.h"
#include "nvs.h"
#define MAX_TAGS 50
@@ -17,13 +20,44 @@ static bool enabled = true;
static char valid_tags[MAX_TAGS][AUTH_TAG_MAX_LEN];
static int tag_count = 0;
// Fila para enviar eventos de autenticação
// Fila de eventos enviada ao EVSE Manager
static QueueHandle_t event_queue = NULL;
void auth_set_event_queue(QueueHandle_t queue) {
event_queue = queue;
// ===========================
// Persistência em NVS
// ===========================
static void load_auth_config(void) {
nvs_handle_t handle;
esp_err_t err = nvs_open("auth", NVS_READONLY, &handle);
if (err == ESP_OK) {
uint8_t val;
if (nvs_get_u8(handle, "enabled", &val) == ESP_OK) {
enabled = val;
ESP_LOGI(TAG, "Loaded auth enabled = %d", enabled);
}
nvs_close(handle);
} else {
ESP_LOGW(TAG, "No stored auth config found. Using default.");
}
}
static void save_auth_config(void) {
nvs_handle_t handle;
if (nvs_open("auth", NVS_READWRITE, &handle) == ESP_OK) {
nvs_set_u8(handle, "enabled", enabled);
nvs_commit(handle);
nvs_close(handle);
ESP_LOGI(TAG, "Auth config saved: enabled = %d", enabled);
} else {
ESP_LOGE(TAG, "Failed to save auth config.");
}
}
// ===========================
// Internos
// ===========================
static bool is_tag_valid(const char *tag) {
for (int i = 0; i < tag_count; i++) {
if (strncmp(valid_tags[i], tag, AUTH_TAG_MAX_LEN) == 0) {
@@ -33,8 +67,17 @@ static bool is_tag_valid(const char *tag) {
return false;
}
// ===========================
// API pública
// ===========================
void auth_set_event_queue(QueueHandle_t queue) {
event_queue = queue;
}
void auth_set_enabled(bool value) {
enabled = value;
save_auth_config();
ESP_LOGI(TAG, "Auth %s", enabled ? "ENABLED" : "DISABLED");
}
@@ -80,10 +123,11 @@ void auth_list_tags(void) {
}
void auth_init(void) {
auth_set_enabled(true); // Default: enabled
initWiegand(); // Inicializa automaticamente o leitor Wiegand 26
load_auth_config(); // carrega estado de ativação
initWiegand(); // inicia leitor RFID
}
// Processa uma tag lida (chamada pelo leitor)
void auth_process_tag(const char *tag) {
if (!tag || !auth_is_enabled()) {
ESP_LOGW(TAG, "Auth disabled or NULL tag received.");