refact auth

This commit is contained in:
2025-06-08 10:06:28 +01:00
parent 71b6cb7878
commit 214cf1ee04
236 changed files with 466 additions and 251 deletions

View File

@@ -14,5 +14,5 @@ idf_component_register(
SRCS ${srcs}
INCLUDE_DIRS "include"
PRIV_REQUIRES nvs_flash
REQUIRES peripherals
REQUIRES peripherals auth
)

View File

@@ -45,13 +45,8 @@ void evse_process(void) {
evse_error_check(pilot_voltage, is_n12v);
if (evse_get_error() == 0 && !evse_is_error_cleared()) {
// Autorização temporária se exigida
if (!authorized && evse_is_require_auth()) {
authorized = auth_grant_to >= xTaskGetTickCount();
if (auth_grant_to) auth_grant_to = 0;
} else {
authorized = true;
}
bool authorized = evse_state_get_authorized();
evse_fsm_process(
pilot_voltage,
@@ -109,7 +104,7 @@ bool evse_is_pending_auth(void) {
void evse_authorize(void) {
ESP_LOGI(TAG, "Authorize");
auth_grant_to = xTaskGetTickCount() + pdMS_TO_TICKS(60000);
evse_state_set_authorized(true);
}
void evse_set_authorized(bool value) {

View File

@@ -3,59 +3,102 @@
#include "evse_error.h"
#include "evse_hardware.h"
#include "evse_config.h"
#include "evse_api.h"
#include "auth.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include <string.h>
static const char *TAG = "evse_manager";
static const char *TAG = "EVSE_Manager";
static TickType_t auth_expiration = 0;
static SemaphoreHandle_t evse_mutex;
static QueueHandle_t auth_event_queue = NULL;
#define EVSE_MANAGER_TICK_PERIOD_MS 1000 // 1 segundo
void evse_manager_init(void) {
evse_mutex = xSemaphoreCreateMutex();
evse_config_init();
evse_error_init();
evse_hardware_init();
evse_state_init();
ESP_LOGI(TAG, "EVSE Manager initialized");
xTaskCreate(
evse_manager_task,
"evse_manager_task",
4096, // stack size
NULL, // param
5, // priority
NULL // handle
);
}
void evse_manager_task(void *arg) {
// ===== Task de ciclo principal =====
static void evse_manager_task(void *arg) {
while (true) {
evse_manager_tick();
vTaskDelay(pdMS_TO_TICKS(EVSE_MANAGER_TICK_PERIOD_MS));
}
}
static void evse_auth_event_task(void *arg) {
auth_event_t evt;
while (true) {
if (xQueueReceive(auth_event_queue, &evt, portMAX_DELAY)) {
ESP_LOGI(TAG, "Evento de autenticação recebido: %s (%s)",
evt.tag, evt.authorized ? "AUTORIZADO" : "NEGADO");
if (evt.authorized) {
evse_authorize();
auth_expiration = xTaskGetTickCount() + pdMS_TO_TICKS(2 * 60 * 1000); // 2 minutos
} else {
evse_manager_set_authorized(false);
ESP_LOGW(TAG, "Tag inválida, carregamento negado.");
}
}
}
}
// ===== Inicialização dos módulos do EVSE =====
void evse_manager_init(void) {
evse_mutex = xSemaphoreCreateMutex();
evse_config_init();
evse_error_init();
evse_hardware_init();
evse_state_init();
ESP_LOGI(TAG, "EVSE Manager inicializado.");
xTaskCreate(evse_manager_task, "evse_manager_task", 4096, NULL, 5, NULL);
}
// ===== Inicia processamento de eventos de autenticação =====
void evse_manager_start(QueueHandle_t queue) {
auth_event_queue = queue;
xTaskCreate(evse_auth_event_task, "evse_auth_evt", 4096, NULL, 5, NULL);
}
void evse_manager_tick(void) {
xSemaphoreTake(evse_mutex, portMAX_DELAY);
// Atualizações cíclicas de módulos
evse_hardware_tick();
evse_error_tick();
evse_state_tick();
evse_temperature_check();
// Verifica expiração de autorização somente se auth está habilitado
if (auth_is_enabled()) {
if (evse_state_get_authorized() && auth_expiration > 0 &&
xTaskGetTickCount() >= auth_expiration) {
ESP_LOGI(TAG, "Autorização expirada após 2 minutos.");
evse_state_set_authorized(false);
auth_expiration = 0;
}
} else {
// Se autenticação não é necessária, sempre considera autorizado
if (!evse_state_get_authorized()) {
evse_state_set_authorized(true);
ESP_LOGI(TAG, "Autenticação desativada: autorização forçada.");
}
}
xSemaphoreGive(evse_mutex);
}
// ===== Controles e status =====
bool evse_manager_is_available(void) {
return evse_config_is_available();
}

View File

@@ -1,13 +1,24 @@
#include "evse_state.h"
#include "freertos/FreeRTOS.h"
#include "freertos/portmacro.h"
static evse_state_t current_state = EVSE_STATE_A;
static bool is_authorized = false;
// Proteção básica para variáveis globais em sistemas concorrentes
static portMUX_TYPE state_mux = portMUX_INITIALIZER_UNLOCKED;
void evse_set_state(evse_state_t state) {
portENTER_CRITICAL(&state_mux);
current_state = state;
portEXIT_CRITICAL(&state_mux);
}
evse_state_t evse_get_state(void) {
return current_state;
portENTER_CRITICAL(&state_mux);
evse_state_t s = current_state;
portEXIT_CRITICAL(&state_mux);
return s;
}
const char* evse_state_to_str(evse_state_t state) {
@@ -26,10 +37,12 @@ const char* evse_state_to_str(evse_state_t state) {
}
void evse_state_init(void) {
// Inicialização do estado EVSE
portENTER_CRITICAL(&state_mux);
current_state = EVSE_STATE_A;
is_authorized = false;
portEXIT_CRITICAL(&state_mux);
}
void evse_state_tick(void) {
// Tick do estado (placeholder)
}
@@ -47,3 +60,16 @@ bool evse_state_is_plugged(evse_state_t state) {
bool evse_state_is_session(evse_state_t state) {
return state == EVSE_STATE_B2 || state == EVSE_STATE_C1 || state == EVSE_STATE_C2;
}
void evse_state_set_authorized(bool authorized) {
portENTER_CRITICAL(&state_mux);
is_authorized = authorized;
portEXIT_CRITICAL(&state_mux);
}
bool evse_state_get_authorized(void) {
portENTER_CRITICAL(&state_mux);
bool result = is_authorized;
portEXIT_CRITICAL(&state_mux);
return result;
}

View File

@@ -6,46 +6,54 @@ extern "C" {
#endif
#include <stdbool.h>
#include "evse_state.h"
#include "evse_error.h"
#include "evse_config.h"
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
/**
* @brief Inicializa todos os módulos do EVSE e inicia a tarefa de supervisão periódica.
* @brief Inicializa os módulos internos do EVSE (hardware, estado, erros, etc.)
* e inicia a tarefa de supervisão periódica (tick).
*/
void evse_manager_init(void);
/**
* @brief Executa uma iteração do ciclo de controle do EVSE (chamada automaticamente pela task).
* @brief Inicia a tarefa que processa eventos de autenticação recebidos via fila.
*
* Você normalmente não precisa chamar isso manualmente.
* @param queue Fila de eventos do tipo auth_event_t enviada pelo módulo auth.
*/
void evse_manager_start(QueueHandle_t queue);
/**
* @brief Executa uma iteração do ciclo de controle do EVSE.
*
* Esta função é chamada automaticamente pela task periódica,
* mas pode ser chamada manualmente em testes.
*/
void evse_manager_tick(void);
/**
* @brief Verifica se o EVSE está disponível para conexão (não bloqueado, sem falha crítica, etc).
* @brief Verifica se o EVSE está disponível para uso.
*
* Isso considera falhas críticas, disponibilidade configurada, etc.
*/
bool evse_manager_is_available(void);
/**
* @brief Define se o EVSE deve estar disponível.
*
* Pode ser usado, por exemplo, para bloquear carregamento via comando remoto.
* @brief Define se o EVSE deve estar disponível (ex: via controle remoto).
*/
void evse_manager_set_available(bool available);
/**
* @brief Define se o EVSE está autorizado a iniciar carregamento (ex: após autenticação).
* @brief Define se o EVSE está autorizado a carregar (ex: após autenticação).
*/
void evse_manager_set_authorized(bool authorized);
/**
* @brief Verifica se o EVSE está em estado de carregamento ativo.
* @brief Verifica se o EVSE está atualmente carregando.
*/
bool evse_manager_is_charging(void);
/**
* @brief Ativa ou desativa o EVSE (liga/desliga logicamente o carregamento).
* @brief Ativa ou desativa logicamente o EVSE (controla habilitação geral).
*/
void evse_manager_set_enabled(bool enabled);
@@ -54,8 +62,6 @@ void evse_manager_set_enabled(bool enabled);
*/
bool evse_manager_is_enabled(void);
void evse_manager_task(void *arg);
#ifdef __cplusplus
}
#endif

View File

@@ -22,6 +22,8 @@ void evse_state_init(void);
void evse_state_tick(void);
void evse_state_set_authorized(bool authorized);
bool evse_state_get_authorized(void);
evse_state_t evse_get_state(void);