new release
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "input_filter.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "nvs.h"
|
||||
@@ -25,6 +26,16 @@ static const char *TAG = "loadbalancer";
|
||||
#define MIN_GRID_CURRENT_LIMIT 6 // A
|
||||
#define MAX_GRID_CURRENT_LIMIT 100 // A
|
||||
|
||||
// Pequena tolerância para considerar "sem margem"
|
||||
#define AVAILABLE_EPS 1.0f
|
||||
|
||||
// Histerese de suspensão / retoma (em torno dos 6A)
|
||||
#define LB_SUSPEND_THRESHOLD 5.0f // abaixo disto -> suspende
|
||||
#define LB_RESUME_THRESHOLD 7.0f // acima disto -> pode retomar
|
||||
|
||||
// Timeout para perda de medição de GRID (fail-safe)
|
||||
#define GRID_METER_TIMEOUT_US (10LL * 1000000LL) // 30 segundos
|
||||
|
||||
// Parâmetros
|
||||
static uint8_t max_grid_current = MAX_GRID_CURRENT_LIMIT;
|
||||
static bool loadbalancer_enabled = false;
|
||||
@@ -34,9 +45,14 @@ static float evse_current = 0.0f;
|
||||
static input_filter_t grid_filter;
|
||||
static input_filter_t evse_filter;
|
||||
|
||||
static int64_t last_grid_timestamp_us = 0; // última atualização de medição GRID
|
||||
|
||||
#define MAX_SLAVES 255
|
||||
#define CONNECTOR_COUNT (MAX_SLAVES + 1)
|
||||
|
||||
// Proteção simples de concorrência
|
||||
static SemaphoreHandle_t lb_mutex = NULL;
|
||||
|
||||
// Estrutura unificada para master e slaves
|
||||
typedef struct
|
||||
{
|
||||
@@ -45,9 +61,12 @@ typedef struct
|
||||
bool charging;
|
||||
float hw_max_current;
|
||||
float runtime_current;
|
||||
int64_t timestamp; // microssegundos
|
||||
int64_t timestamp; // microssegundos (última métrica EVSE/slave)
|
||||
bool online;
|
||||
float assigned;
|
||||
float assigned; // limite calculado pelo LB
|
||||
int64_t started_us; // início da sessão de carregamento (para prioridade)
|
||||
uint16_t last_limit; // último max_current enviado
|
||||
bool suspended_by_lb; // flag de suspensão por LB (para histerese)
|
||||
} evse_connector_t;
|
||||
|
||||
static evse_connector_t connectors[CONNECTOR_COUNT];
|
||||
@@ -66,7 +85,11 @@ static void init_connectors(void)
|
||||
.runtime_current = 0,
|
||||
.timestamp = 0,
|
||||
.online = false,
|
||||
.assigned = 0.0f};
|
||||
.assigned = 0.0f,
|
||||
.started_us = 0,
|
||||
.last_limit = 0,
|
||||
.suspended_by_lb = false};
|
||||
|
||||
// slaves em 1..CONNECTOR_COUNT-1
|
||||
for (int i = 1; i < CONNECTOR_COUNT; i++)
|
||||
{
|
||||
@@ -78,7 +101,10 @@ static void init_connectors(void)
|
||||
.runtime_current = 0.0f,
|
||||
.timestamp = 0,
|
||||
.online = false,
|
||||
.assigned = 0.0f};
|
||||
.assigned = 0.0f,
|
||||
.started_us = 0,
|
||||
.last_limit = 0,
|
||||
.suspended_by_lb = false};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,12 +126,30 @@ static void on_slave_status(void *handler_arg, esp_event_base_t base, int32_t id
|
||||
}
|
||||
|
||||
int idx = status->slave_id + 1; // slaves começam no índice 1
|
||||
|
||||
bool was_charging;
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
was_charging = connectors[idx].charging;
|
||||
|
||||
connectors[idx].charging = status->charging;
|
||||
connectors[idx].hw_max_current = status->hw_max_current;
|
||||
connectors[idx].runtime_current = status->runtime_current;
|
||||
connectors[idx].timestamp = esp_timer_get_time();
|
||||
connectors[idx].online = true;
|
||||
|
||||
// Se começou agora a carregar, marca início da sessão
|
||||
if (status->charging && !was_charging)
|
||||
{
|
||||
connectors[idx].started_us = connectors[idx].timestamp;
|
||||
connectors[idx].suspended_by_lb = false; // reset
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
|
||||
ESP_LOGI(TAG,
|
||||
"Slave %d status: charging=%d hw_max_current=%.1fA runtime_current=%.2fA",
|
||||
status->slave_id, status->charging,
|
||||
@@ -120,33 +164,62 @@ static void on_evse_config_event(void *handler_arg,
|
||||
const evse_config_event_data_t *evt = (const evse_config_event_data_t *)event_data;
|
||||
|
||||
int idx = 0; // MASTER INDICE 0
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
connectors[idx].charging = evt->charging;
|
||||
connectors[idx].hw_max_current = evt->hw_max_current;
|
||||
connectors[idx].runtime_current = evt->runtime_current;
|
||||
connectors[idx].timestamp = esp_timer_get_time();
|
||||
connectors[idx].online = true;
|
||||
|
||||
if (!evt->charging)
|
||||
{
|
||||
connectors[idx].suspended_by_lb = false;
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
|
||||
ESP_LOGI(TAG, "EVSE config updated: charging=%d hw_max_current=%.1f runtime_current=%.1f",
|
||||
evt->charging, evt->hw_max_current, evt->runtime_current);
|
||||
}
|
||||
|
||||
// --- Handlers de eventos externos ---
|
||||
static void loadbalancer_meter_event_handler(void *handler_arg,
|
||||
esp_event_base_t base,
|
||||
int32_t id,
|
||||
void *event_data)
|
||||
static void loadbalancer_meter_event_handler(void *handler_arg, esp_event_base_t base, int32_t id, void *event_data)
|
||||
{
|
||||
if (id != METER_EVENT_DATA_READY || event_data == NULL)
|
||||
return;
|
||||
|
||||
const meter_event_data_t *evt = (const meter_event_data_t *)event_data;
|
||||
float max_irms = evt->irms[0];
|
||||
for (int i = 1; i < 3; ++i)
|
||||
{
|
||||
if (evt->irms[i] > max_irms)
|
||||
{
|
||||
max_irms = evt->irms[i];
|
||||
}
|
||||
}
|
||||
|
||||
float max_vrms = evt->vrms[0];
|
||||
for (int i = 1; i < 3; ++i)
|
||||
{
|
||||
if (evt->vrms[i] > max_vrms)
|
||||
{
|
||||
max_vrms = evt->vrms[i];
|
||||
}
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
if (evt->source && strcmp(evt->source, "GRID") == 0)
|
||||
{
|
||||
grid_current = input_filter_update(&grid_filter, max_irms);
|
||||
last_grid_timestamp_us = esp_timer_get_time();
|
||||
ESP_LOGI(TAG, "GRID IRMS (filtered): %.2f A", grid_current);
|
||||
ESP_LOGI(TAG, "GRID VRMS: %.2f V", max_vrms);
|
||||
}
|
||||
else if (evt->source && strcmp(evt->source, "EVSE") == 0)
|
||||
{
|
||||
@@ -157,6 +230,9 @@ static void loadbalancer_meter_event_handler(void *handler_arg,
|
||||
{
|
||||
ESP_LOGW(TAG, "Unknown meter event source: %s", evt->source);
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
}
|
||||
|
||||
static void loadbalancer_evse_event_handler(void *handler_arg,
|
||||
@@ -166,6 +242,9 @@ static void loadbalancer_evse_event_handler(void *handler_arg,
|
||||
{
|
||||
const evse_state_event_data_t *evt = (const evse_state_event_data_t *)event_data;
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
switch (evt->state)
|
||||
{
|
||||
case EVSE_STATE_EVENT_IDLE:
|
||||
@@ -175,29 +254,45 @@ static void loadbalancer_evse_event_handler(void *handler_arg,
|
||||
evt->state == EVSE_STATE_EVENT_IDLE ? "dis" : "");
|
||||
connectors[0].charging = false;
|
||||
connectors[0].online = true; // master está sempre online
|
||||
connectors[0].suspended_by_lb = false;
|
||||
break;
|
||||
|
||||
case EVSE_STATE_EVENT_CHARGING:
|
||||
{
|
||||
ESP_LOGI(TAG, "Local EVSE is CHARGING - resetting filters");
|
||||
grid_current = 0.0f;
|
||||
evse_current = 0.0f;
|
||||
input_filter_reset(&grid_filter);
|
||||
input_filter_reset(&evse_filter);
|
||||
|
||||
bool was_charging = connectors[0].charging;
|
||||
|
||||
connectors[0].charging = true;
|
||||
connectors[0].online = true;
|
||||
connectors[0].timestamp = esp_timer_get_time();
|
||||
|
||||
if (!was_charging)
|
||||
{
|
||||
connectors[0].started_us = connectors[0].timestamp;
|
||||
connectors[0].suspended_by_lb = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case EVSE_STATE_EVENT_FAULT:
|
||||
ESP_LOGW(TAG, "Local EVSE is in FAULT state - disabling load balancing temporarily");
|
||||
connectors[0].charging = false;
|
||||
connectors[0].online = true; // EVSE está online mas com falha
|
||||
connectors[0].suspended_by_lb = false;
|
||||
break;
|
||||
|
||||
default:
|
||||
ESP_LOGW(TAG, "Unknown EVSE state: %d", evt->state);
|
||||
break;
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
}
|
||||
|
||||
// --- Config persistência ---
|
||||
@@ -207,8 +302,10 @@ static esp_err_t loadbalancer_load_config()
|
||||
esp_err_t err = nvs_open("loadbalancing", NVS_READWRITE, &handle);
|
||||
if (err != ESP_OK)
|
||||
return err;
|
||||
|
||||
bool needs_commit = false;
|
||||
uint8_t temp_u8;
|
||||
|
||||
err = nvs_get_u8(handle, "max_grid_curr", &temp_u8);
|
||||
if (err == ESP_OK && temp_u8 >= MIN_GRID_CURRENT_LIMIT && temp_u8 <= MAX_GRID_CURRENT_LIMIT)
|
||||
max_grid_current = temp_u8;
|
||||
@@ -218,6 +315,7 @@ static esp_err_t loadbalancer_load_config()
|
||||
nvs_set_u8(handle, "max_grid_curr", max_grid_current);
|
||||
needs_commit = true;
|
||||
}
|
||||
|
||||
err = nvs_get_u8(handle, "enabled", &temp_u8);
|
||||
if (err == ESP_OK && temp_u8 <= 1)
|
||||
loadbalancer_enabled = (temp_u8 != 0);
|
||||
@@ -227,6 +325,7 @@ static esp_err_t loadbalancer_load_config()
|
||||
nvs_set_u8(handle, "enabled", 0);
|
||||
needs_commit = true;
|
||||
}
|
||||
|
||||
if (needs_commit)
|
||||
nvs_commit(handle);
|
||||
nvs_close(handle);
|
||||
@@ -280,7 +379,7 @@ void loadbalancer_task(void *param)
|
||||
{
|
||||
if (!loadbalancer_is_enabled())
|
||||
{
|
||||
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||
vTaskDelay(pdMS_TO_TICKS(30000));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -289,9 +388,11 @@ void loadbalancer_task(void *param)
|
||||
int64_t now = esp_timer_get_time();
|
||||
|
||||
// --- Atualiza estado online e conta ativos ---
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
for (int i = 0; i < CONNECTOR_COUNT; i++)
|
||||
{
|
||||
|
||||
// --- Master nunca pode ficar offline ---
|
||||
if (connectors[i].is_master)
|
||||
{
|
||||
@@ -334,79 +435,312 @@ void loadbalancer_task(void *param)
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot de grid_current e last_grid_timestamp sob mutex
|
||||
float grid_snapshot = grid_current;
|
||||
int64_t last_grid_ts_snapshot = last_grid_timestamp_us;
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
|
||||
ESP_LOGI(TAG, "Active connectors: %d", active_cnt);
|
||||
|
||||
// --- Calcula corrente disponível ---
|
||||
float available = max_grid_current - grid_current;
|
||||
if (available < MIN_CHARGING_CURRENT_LIMIT)
|
||||
if (active_cnt == 0)
|
||||
{
|
||||
available = MIN_CHARGING_CURRENT_LIMIT;
|
||||
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||
continue;
|
||||
}
|
||||
else if (available > max_grid_current)
|
||||
{
|
||||
available = max_grid_current;
|
||||
}
|
||||
ESP_LOGI(TAG, "LB Calc: available=%.1fA, active_connectors=%d", available, active_cnt);
|
||||
|
||||
// --- Ordena conectores por hw_max_current (bubble sort simples) ---
|
||||
for (int a = 0; a < active_cnt - 1; a++)
|
||||
// --- Verifica timeout de medição de GRID (fail-safe) ---
|
||||
bool meter_timeout = (last_grid_ts_snapshot == 0 ||
|
||||
(now - last_grid_ts_snapshot) > GRID_METER_TIMEOUT_US);
|
||||
|
||||
if (meter_timeout)
|
||||
{
|
||||
for (int b = 0; b < active_cnt - 1 - a; b++)
|
||||
ESP_LOGW(TAG,
|
||||
"GRID meter timeout (last update=%lld us ago). Applying fail-safe limits (<=%dA).",
|
||||
(long long)(now - last_grid_ts_snapshot), MIN_CHARGING_CURRENT_LIMIT);
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
// Fail-safe: limitar cada EV ao mínimo permitido (6A) ou menos, nunca aumentar
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
if (connectors[idxs[b]].hw_max_current > connectors[idxs[b + 1]].hw_max_current)
|
||||
int i = idxs[k];
|
||||
float cur = connectors[i].runtime_current;
|
||||
if (cur > MIN_CHARGING_CURRENT_LIMIT)
|
||||
connectors[i].assigned = (float)MIN_CHARGING_CURRENT_LIMIT;
|
||||
else
|
||||
connectors[i].assigned = cur;
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
}
|
||||
|
||||
// --- Calcula corrente disponível (headroom global) ---
|
||||
float available = (float)max_grid_current - grid_snapshot;
|
||||
ESP_LOGI(TAG, "LB raw headroom: max_grid=%uA, grid_current=%.1fA, available=%.2fA",
|
||||
max_grid_current, grid_snapshot, available);
|
||||
|
||||
// ==========================
|
||||
// ZONA A: overload significativo -> reduzir correntes (throttling)
|
||||
// ==========================
|
||||
if (available < -AVAILABLE_EPS)
|
||||
{
|
||||
ESP_LOGW(TAG, "Overload: grid=%.1fA, max=%.1fA (available=%.2fA) -> throttling",
|
||||
grid_snapshot, (float)max_grid_current, available);
|
||||
|
||||
float factor = ((float)max_grid_current) / grid_snapshot;
|
||||
if (factor < 0.0f)
|
||||
factor = 0.0f;
|
||||
if (factor > 1.0f)
|
||||
factor = 1.0f;
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
connectors[i].assigned = connectors[i].runtime_current * factor;
|
||||
ESP_LOGI(TAG,
|
||||
"Connector[%d] overload throttling: runtime=%.1fA -> assigned=%.1fA",
|
||||
i, connectors[i].runtime_current, connectors[i].assigned);
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
}
|
||||
// ==========================
|
||||
// ZONA B: sem margem prática -> manter correntes atuais como limites
|
||||
// ==========================
|
||||
else if (fabsf(available) <= AVAILABLE_EPS)
|
||||
{
|
||||
ESP_LOGI(TAG,
|
||||
"No effective headroom: grid=%.1fA, max=%.1fA (available=%.2fA). Keeping current as limit.",
|
||||
grid_snapshot, (float)max_grid_current, available);
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
connectors[i].assigned = connectors[i].runtime_current;
|
||||
ESP_LOGI(TAG,
|
||||
"Connector[%d] keep runtime as limit: assigned=%.1fA",
|
||||
i, connectors[i].assigned);
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
}
|
||||
// ==========================
|
||||
// ZONA C: há margem positiva -> garantir mínimo e depois water-filling SOBRE assigned
|
||||
// ==========================
|
||||
else // available > AVAILABLE_EPS
|
||||
{
|
||||
if (available > max_grid_current)
|
||||
{
|
||||
available = (float)max_grid_current;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "LB Calc (zone C): available=%.1fA, active_connectors=%d",
|
||||
available, active_cnt);
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
// 1) Ordenar conectores ativos por started_us (mais antigos primeiro)
|
||||
for (int a = 0; a < active_cnt - 1; a++)
|
||||
{
|
||||
for (int b = 0; b < active_cnt - 1 - a; b++)
|
||||
{
|
||||
int tmp = idxs[b];
|
||||
idxs[b] = idxs[b + 1];
|
||||
idxs[b + 1] = tmp;
|
||||
int i1 = idxs[b];
|
||||
int i2 = idxs[b + 1];
|
||||
if (connectors[i1].started_us > connectors[i2].started_us)
|
||||
{
|
||||
int tmp = idxs[b];
|
||||
idxs[b] = idxs[b + 1];
|
||||
idxs[b + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inicialmente: assigned = runtime_current
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
connectors[i].assigned = connectors[i].runtime_current;
|
||||
}
|
||||
|
||||
float remaining = available; // margem extra total
|
||||
|
||||
// 2) FASE 1: tentar garantir pelo menos 6A (ou hw_max, se menor) aos mais antigos
|
||||
for (int k = 0; k < active_cnt && remaining > 0.0f; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
|
||||
float current = connectors[i].runtime_current;
|
||||
float hw_max = connectors[i].hw_max_current;
|
||||
|
||||
float target_min = (float)MIN_CHARGING_CURRENT_LIMIT;
|
||||
if (hw_max < target_min)
|
||||
target_min = hw_max;
|
||||
|
||||
if (current >= target_min)
|
||||
{
|
||||
connectors[i].assigned = current;
|
||||
continue;
|
||||
}
|
||||
|
||||
float delta = target_min - current;
|
||||
if (delta <= remaining)
|
||||
{
|
||||
connectors[i].assigned = current + delta;
|
||||
remaining -= delta;
|
||||
}
|
||||
else
|
||||
{
|
||||
connectors[i].assigned = current;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) FASE 2: "last in, first cut" -> cortar quem ficou abaixo do mínimo começando pelos mais recentes
|
||||
for (int k = active_cnt - 1; k >= 0; k--)
|
||||
{
|
||||
int i = idxs[k];
|
||||
if (connectors[i].assigned >= MIN_CHARGING_CURRENT_LIMIT)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Connector[%d] below min after phase1 (assigned=%.1fA) -> suspending (0A)",
|
||||
i, connectors[i].assigned);
|
||||
connectors[i].assigned = 0.0f;
|
||||
connectors[i].suspended_by_lb = true;
|
||||
}
|
||||
|
||||
// 4) FASE 3: se ainda sobrar margem, distribuir extra por cima dos que ficaram ON (assigned > 0)
|
||||
if (remaining > AVAILABLE_EPS)
|
||||
{
|
||||
int on_cnt = 0;
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
if (connectors[i].assigned > 0.0f)
|
||||
on_cnt++;
|
||||
}
|
||||
|
||||
float extra_remaining = remaining;
|
||||
int extra_cnt = on_cnt;
|
||||
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
|
||||
if (connectors[i].assigned <= 0.0f)
|
||||
continue;
|
||||
|
||||
if (extra_cnt <= 0 || extra_remaining <= 0.0f)
|
||||
break;
|
||||
|
||||
float headroom = connectors[i].hw_max_current - connectors[i].assigned;
|
||||
if (headroom <= 0.0f)
|
||||
{
|
||||
extra_cnt--;
|
||||
continue;
|
||||
}
|
||||
|
||||
float share = extra_remaining / (float)extra_cnt;
|
||||
|
||||
if (share >= headroom)
|
||||
{
|
||||
connectors[i].assigned += headroom;
|
||||
extra_remaining -= headroom;
|
||||
extra_cnt--;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int m = k; m < active_cnt; m++)
|
||||
{
|
||||
int j = idxs[m];
|
||||
|
||||
if (connectors[j].assigned <= 0.0f)
|
||||
continue;
|
||||
|
||||
float headroom_j = connectors[j].hw_max_current - connectors[j].assigned;
|
||||
if (headroom_j <= 0.0f)
|
||||
continue;
|
||||
|
||||
float inc = MIN(share, headroom_j);
|
||||
connectors[j].assigned += inc;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
}
|
||||
|
||||
// --- Distribui corrente (water-filling) ---
|
||||
float remaining = available;
|
||||
int remaining_cnt = active_cnt;
|
||||
// --- Publicação de limites / suspensão com histerese ---
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
float share = remaining / remaining_cnt;
|
||||
if (share >= connectors[i].hw_max_current)
|
||||
float assigned = connectors[i].assigned;
|
||||
float effective = assigned;
|
||||
|
||||
// Histerese de suspensão / retoma
|
||||
if (connectors[i].suspended_by_lb)
|
||||
{
|
||||
connectors[i].assigned = connectors[i].hw_max_current;
|
||||
remaining -= connectors[i].assigned;
|
||||
remaining_cnt--;
|
||||
// Está suspenso: só retoma se limite calculado for >= limiar de retoma
|
||||
if (assigned >= LB_RESUME_THRESHOLD)
|
||||
{
|
||||
effective = assigned;
|
||||
connectors[i].suspended_by_lb = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
effective = 0.0f;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int m = k; m < active_cnt; m++)
|
||||
// Ainda não está suspenso: só suspende se ficar claramente abaixo do limiar
|
||||
if (assigned > 0.0f && assigned < LB_SUSPEND_THRESHOLD)
|
||||
{
|
||||
connectors[idxs[m]].assigned = share;
|
||||
effective = 0.0f;
|
||||
connectors[i].suspended_by_lb = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Aplica piso mínimo ---
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
if (connectors[i].assigned < MIN_CHARGING_CURRENT_LIMIT)
|
||||
uint16_t max_cur;
|
||||
if (effective <= 0.0f)
|
||||
{
|
||||
connectors[i].assigned = MIN_CHARGING_CURRENT_LIMIT;
|
||||
max_cur = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
max_cur = (uint16_t)MIN(effective, (float)MAX_CHARGING_CURRENT_LIMIT);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Publica limites de corrente ---
|
||||
for (int k = 0; k < active_cnt; k++)
|
||||
{
|
||||
int i = idxs[k];
|
||||
uint16_t max_cur = (uint16_t)MIN(connectors[i].assigned, MAX_CHARGING_CURRENT_LIMIT);
|
||||
uint16_t current_rounded = (uint16_t)roundf(connectors[i].runtime_current);
|
||||
|
||||
if (current_rounded == max_cur)
|
||||
// Evita flapping de comandos: só envia se o limite mudou
|
||||
if (connectors[i].last_limit == max_cur)
|
||||
{
|
||||
continue; // sem alteração
|
||||
}
|
||||
|
||||
connectors[i].last_limit = max_cur;
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
|
||||
if (connectors[i].is_master)
|
||||
{
|
||||
loadbalancer_master_limit_event_t master_evt = {
|
||||
@@ -415,8 +749,8 @@ void loadbalancer_task(void *param)
|
||||
.timestamp_us = now};
|
||||
esp_event_post(LOADBALANCER_EVENTS, LOADBALANCER_EVENT_MASTER_CURRENT_LIMIT,
|
||||
&master_evt, sizeof(master_evt), portMAX_DELAY);
|
||||
ESP_LOGI(TAG, "Master limit changed -> %.1f A (runtime=%.1f A)",
|
||||
(float)max_cur, connectors[i].runtime_current);
|
||||
ESP_LOGI(TAG, "Master limit changed -> %.1f A (assigned=%.2f A)",
|
||||
(float)max_cur, assigned);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -426,11 +760,17 @@ void loadbalancer_task(void *param)
|
||||
.timestamp_us = now};
|
||||
esp_event_post(LOADBALANCER_EVENTS, LOADBALANCER_EVENT_SLAVE_CURRENT_LIMIT,
|
||||
&slave_evt, sizeof(slave_evt), portMAX_DELAY);
|
||||
ESP_LOGI(TAG, "Slave %d limit changed -> %.1f A (runtime=%.1f A)",
|
||||
connectors[i].id, (float)max_cur, connectors[i].runtime_current);
|
||||
ESP_LOGI(TAG, "Slave %d limit changed -> %.1f A (assigned=%.2f A)",
|
||||
connectors[i].id, (float)max_cur, assigned);
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreTake(lb_mutex, portMAX_DELAY);
|
||||
}
|
||||
|
||||
if (lb_mutex)
|
||||
xSemaphoreGive(lb_mutex);
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||
}
|
||||
}
|
||||
@@ -441,6 +781,12 @@ void loadbalancer_init(void)
|
||||
if (loadbalancer_load_config() != ESP_OK)
|
||||
ESP_LOGW(TAG, "Failed to load/init config. Using defaults.");
|
||||
|
||||
lb_mutex = xSemaphoreCreateMutex();
|
||||
if (lb_mutex == NULL)
|
||||
{
|
||||
ESP_LOGE(TAG, "Failed to create loadbalancer mutex");
|
||||
}
|
||||
|
||||
init_connectors();
|
||||
input_filter_init(&grid_filter, 0.3f);
|
||||
input_filter_init(&evse_filter, 0.3f);
|
||||
@@ -461,4 +807,4 @@ void loadbalancer_init(void)
|
||||
|
||||
ESP_ERROR_CHECK(esp_event_handler_register(LOADBALANCER_EVENTS, LOADBALANCER_EVENT_SLAVE_STATUS,
|
||||
&on_slave_status, NULL));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user