fix evse_link

This commit is contained in:
2026-01-24 16:56:51 +00:00
parent 023644a887
commit 286028b6a8
54 changed files with 4456 additions and 2632 deletions

View File

@@ -1,108 +1,216 @@
#include "loadbalancing_settings_api.h"
#include "loadbalancer.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_http_server.h"
#include "cJSON.h"
#include <stdlib.h>
#include <string.h>
static const char *TAG = "loadbalancing_settings_api";
// GET Handler: Retorna configurações atuais de load balancing
static esp_err_t loadbalancing_config_get_handler(httpd_req_t *req) {
bool enabled = loadbalancer_is_enabled();
uint8_t currentLimit = load_balancing_get_max_grid_current();
// limites simples
#define MIN_GRID_A 6
#define MAX_GRID_A 100
ESP_LOGD(TAG, "Fetching load balancing settings: enabled = %d, currentLimit = %u", enabled, currentLimit);
#define MIN_PV_W 0
#define MAX_PV_W 100000 // ajusta se quiseres
static esp_err_t send_json(httpd_req_t *req, cJSON *root)
{
httpd_resp_set_type(req, "application/json");
cJSON *config = cJSON_CreateObject();
cJSON_AddBoolToObject(config, "loadBalancingEnabled", enabled);
cJSON_AddNumberToObject(config, "loadBalancingCurrentLimit", currentLimit);
char *json_str = cJSON_PrintUnformatted(root);
if (!json_str)
{
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "JSON encode failed");
return ESP_FAIL;
}
const char *json_str = cJSON_Print(config);
httpd_resp_sendstr(req, json_str);
esp_err_t err = httpd_resp_sendstr(req, json_str);
free(json_str);
return err;
}
ESP_LOGD(TAG, "Returned config: %s", json_str);
// GET -> payload novo
static esp_err_t loadbalancing_config_get_handler(httpd_req_t *req)
{
cJSON *root = cJSON_CreateObject();
if (!root)
{
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "No mem");
return ESP_FAIL;
}
free((void *)json_str);
cJSON_Delete(config);
cJSON_AddBoolToObject(root, "enabled", loadbalancer_is_enabled());
cJSON *grid = cJSON_CreateObject();
cJSON_AddItemToObject(root, "gridLimit", grid);
cJSON_AddBoolToObject(grid, "enabled", loadbalancer_grid_is_enabled());
cJSON_AddNumberToObject(grid, "maxImportA", loadbalancer_grid_get_max_import_a());
cJSON *pv = cJSON_CreateObject();
cJSON_AddItemToObject(root, "pv", pv);
cJSON_AddBoolToObject(pv, "enabled", loadbalancer_pv_is_enabled());
cJSON_AddNumberToObject(pv, "maxImportW", loadbalancer_pv_get_max_import_w());
esp_err_t err = send_json(req, root);
cJSON_Delete(root);
return err;
}
// lê body de forma robusta (httpd_req_recv pode devolver parcial)
static esp_err_t read_body(httpd_req_t *req, char *buf, size_t buf_sz)
{
if (req->content_len <= 0)
return ESP_FAIL;
if ((size_t)req->content_len >= buf_sz)
return ESP_ERR_NO_MEM;
int remaining = req->content_len;
int off = 0;
while (remaining > 0)
{
int r = httpd_req_recv(req, buf + off, remaining);
if (r <= 0)
return ESP_FAIL;
off += r;
remaining -= r;
}
buf[off] = '\0';
return ESP_OK;
}
// POST Handler: Atualiza configurações de load balancing
static esp_err_t loadbalancing_config_post_handler(httpd_req_t *req) {
char buf[512];
int len = httpd_req_recv(req, buf, sizeof(buf) - 1);
if (len <= 0) {
ESP_LOGE(TAG, "Received empty POST body");
// POST -> updates parciais aceites
static esp_err_t loadbalancing_config_post_handler(httpd_req_t *req)
{
if (req->content_len <= 0)
{
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Empty body");
return ESP_FAIL;
}
buf[len] = '\0';
ESP_LOGD(TAG, "Received POST data: %s", buf);
if (req->content_len >= 512)
{
httpd_resp_send_err(req, HTTPD_413_CONTENT_TOO_LARGE, "Body too large");
return ESP_FAIL;
}
char buf[512];
esp_err_t rb = read_body(req, buf, sizeof(buf));
if (rb == ESP_ERR_NO_MEM)
{
httpd_resp_send_err(req, HTTPD_413_CONTENT_TOO_LARGE, "Body too large");
return ESP_FAIL;
}
if (rb != ESP_OK)
{
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Failed to read body");
return ESP_FAIL;
}
ESP_LOGD(TAG, "POST: %s", buf);
cJSON *json = cJSON_Parse(buf);
if (!json) {
ESP_LOGE(TAG, "Invalid JSON");
if (!json)
{
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
return ESP_FAIL;
}
// Atualizar estado habilitado
cJSON *enabled_item = cJSON_GetObjectItem(json, "loadBalancingEnabled");
if (enabled_item && cJSON_IsBool(enabled_item)) {
bool isEnabled = cJSON_IsTrue(enabled_item);
loadbalancer_set_enabled(isEnabled);
ESP_LOGD(TAG, "Updated loadBalancingEnabled to: %d", isEnabled);
// enabled (top-level)
cJSON *enabled_item = cJSON_GetObjectItem(json, "enabled");
if (enabled_item && cJSON_IsBool(enabled_item))
{
loadbalancer_set_enabled(cJSON_IsTrue(enabled_item));
}
// Atualizar limite de corrente
cJSON *limit_item = cJSON_GetObjectItem(json, "loadBalancingCurrentLimit");
if (limit_item && cJSON_IsNumber(limit_item)) {
uint8_t currentLimit = (uint8_t)limit_item->valuedouble;
// Validar intervalo
if (currentLimit < 6 || currentLimit > 100) {
ESP_LOGW(TAG, "Rejected invalid currentLimit: %d", currentLimit);
cJSON_Delete(json);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid currentLimit (must be 6-100)");
return ESP_FAIL;
// gridLimit
cJSON *grid = cJSON_GetObjectItem(json, "gridLimit");
if (grid && cJSON_IsObject(grid))
{
cJSON *g_en = cJSON_GetObjectItem(grid, "enabled");
if (g_en && cJSON_IsBool(g_en))
{
loadbalancer_grid_set_enabled(cJSON_IsTrue(g_en));
}
esp_err_t err = load_balancing_set_max_grid_current(currentLimit);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to save currentLimit: %s", esp_err_to_name(err));
cJSON_Delete(json);
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to save setting");
return ESP_FAIL;
cJSON *g_maxA = cJSON_GetObjectItem(grid, "maxImportA");
if (g_maxA && cJSON_IsNumber(g_maxA))
{
int maxA = (int)g_maxA->valuedouble;
if (maxA < MIN_GRID_A || maxA > MAX_GRID_A)
{
cJSON_Delete(json);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "gridLimit.maxImportA must be 6-100");
return ESP_FAIL;
}
esp_err_t e = loadbalancer_grid_set_max_import_a((uint8_t)maxA);
if (e != ESP_OK)
{
cJSON_Delete(json);
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to set gridLimit.maxImportA");
return ESP_FAIL;
}
}
}
// pv
cJSON *pv = cJSON_GetObjectItem(json, "pv");
if (pv && cJSON_IsObject(pv))
{
cJSON *p_en = cJSON_GetObjectItem(pv, "enabled");
if (p_en && cJSON_IsBool(p_en))
{
loadbalancer_pv_set_enabled(cJSON_IsTrue(p_en));
}
ESP_LOGD(TAG, "Updated loadBalancingCurrentLimit to: %d", currentLimit);
cJSON *p_maxW = cJSON_GetObjectItem(pv, "maxImportW");
if (p_maxW && cJSON_IsNumber(p_maxW))
{
int32_t maxW = (int32_t)p_maxW->valuedouble;
if (maxW < MIN_PV_W || maxW > MAX_PV_W)
{
cJSON_Delete(json);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "pv.maxImportW out of range");
return ESP_FAIL;
}
esp_err_t e = loadbalancer_pv_set_max_import_w(maxW);
if (e != ESP_OK)
{
cJSON_Delete(json);
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to set pv.maxImportW");
return ESP_FAIL;
}
}
}
cJSON_Delete(json);
httpd_resp_sendstr(req, "Load balancing settings updated successfully");
httpd_resp_sendstr(req, "OK");
return ESP_OK;
}
// Registro dos handlers na API HTTP
void register_loadbalancing_settings_handlers(httpd_handle_t server, void *ctx) {
// GET
void register_loadbalancing_settings_handlers(httpd_handle_t server, void *ctx)
{
httpd_uri_t get_uri = {
.uri = "/api/v1/config/loadbalancing",
.method = HTTP_GET,
.handler = loadbalancing_config_get_handler,
.user_ctx = ctx
};
.user_ctx = ctx};
httpd_register_uri_handler(server, &get_uri);
// POST
httpd_uri_t post_uri = {
.uri = "/api/v1/config/loadbalancing",
.method = HTTP_POST,
.handler = loadbalancing_config_post_handler,
.user_ctx = ctx
};
.user_ctx = ctx};
httpd_register_uri_handler(server, &post_uri);
}

View File

@@ -8,16 +8,20 @@
#include "network.h"
#include "mqtt.h"
#include <string.h>
#include <stdlib.h>
static const char *TAG = "network_api";
typedef struct {
typedef struct
{
bool enabled;
char ssid[33];
char password[65];
} wifi_task_data_t;
static void wifi_apply_config_task(void *param) {
static void wifi_apply_config_task(void *param)
{
wifi_task_data_t *data = (wifi_task_data_t *)param;
ESP_LOGD("wifi_task", "Applying Wi-Fi config in background task");
wifi_set_config(data->enabled, data->ssid, data->password);
@@ -25,12 +29,12 @@ static void wifi_apply_config_task(void *param) {
vTaskDelete(NULL);
}
static esp_err_t wifi_get_handler(httpd_req_t *req) {
static esp_err_t wifi_get_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "Handling GET /api/v1/config/wifi");
httpd_resp_set_type(req, "application/json");
// Obter dados da NVS via wifi.c
bool enabled = wifi_get_enabled();
char ssid[33] = {0};
char password[65] = {0};
@@ -38,78 +42,82 @@ static esp_err_t wifi_get_handler(httpd_req_t *req) {
wifi_get_ssid(ssid);
wifi_get_password(password);
// Criar JSON
cJSON *json = cJSON_CreateObject();
cJSON_AddBoolToObject(json, "enabled", enabled);
cJSON_AddStringToObject(json, "ssid", ssid);
cJSON_AddStringToObject(json, "password", password);
// Enviar resposta
char *response = cJSON_Print(json);
httpd_resp_sendstr(req, response);
// Limpeza
free(response);
cJSON_Delete(json);
return ESP_OK;
}
static esp_err_t wifi_post_handler(httpd_req_t *req) {
static esp_err_t wifi_post_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "Handling POST /api/v1/config/wifi");
char buf[512];
int len = httpd_req_recv(req, buf, sizeof(buf) - 1);
if (len <= 0) return ESP_FAIL;
if (len <= 0)
return ESP_FAIL;
buf[len] = '\0';
cJSON *json = cJSON_Parse(buf);
if (!json) return ESP_FAIL;
if (!json)
return ESP_FAIL;
// Valores padrão
bool enabled = false;
const char *ssid = NULL;
const char *password = NULL;
cJSON *j_enabled = cJSON_GetObjectItem(json, "enabled");
if (cJSON_IsBool(j_enabled)) enabled = j_enabled->valueint;
if (cJSON_IsBool(j_enabled))
enabled = j_enabled->valueint;
cJSON *j_ssid = cJSON_GetObjectItem(json, "ssid");
if (cJSON_IsString(j_ssid)) ssid = j_ssid->valuestring;
if (cJSON_IsString(j_ssid))
ssid = j_ssid->valuestring;
cJSON *j_password = cJSON_GetObjectItem(json, "password");
if (cJSON_IsString(j_password)) password = j_password->valuestring;
if (cJSON_IsString(j_password))
password = j_password->valuestring;
// Enviar resposta antes de alterar Wi-Fi
// Resposta imediata
httpd_resp_sendstr(req, "Wi-Fi config atualizada com sucesso");
// Alocar struct para passar para a task
wifi_task_data_t *task_data = malloc(sizeof(wifi_task_data_t));
if (!task_data) {
wifi_task_data_t *task_data = (wifi_task_data_t *)malloc(sizeof(wifi_task_data_t));
if (!task_data)
{
cJSON_Delete(json);
ESP_LOGE(TAG, "Memory allocation failed for Wi-Fi task");
return ESP_ERR_NO_MEM;
}
task_data->enabled = enabled;
strncpy(task_data->ssid, ssid ? ssid : "", sizeof(task_data->ssid));
strncpy(task_data->password, password ? password : "", sizeof(task_data->password));
// Criar task normal com função C
// Copias seguras (garante null-termination)
strncpy(task_data->ssid, ssid ? ssid : "", sizeof(task_data->ssid) - 1);
task_data->ssid[sizeof(task_data->ssid) - 1] = '\0';
strncpy(task_data->password, password ? password : "", sizeof(task_data->password) - 1);
task_data->password[sizeof(task_data->password) - 1] = '\0';
xTaskCreate(
wifi_apply_config_task,
"wifi_config_task",
4096,
task_data,
3,
NULL
);
NULL);
cJSON_Delete(json);
return ESP_OK;
}
static esp_err_t config_mqtt_get_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "Handling GET /api/v1/config/mqtt");
@@ -139,28 +147,28 @@ static esp_err_t config_mqtt_get_handler(httpd_req_t *req)
cJSON *config = cJSON_CreateObject();
cJSON_AddBoolToObject(config, "enabled", enabled);
cJSON_AddStringToObject(config, "host", server);
cJSON_AddNumberToObject(config, "port", 1883);
cJSON_AddNumberToObject(config, "port", 1883); // fixo (se não usas no mqtt_set_config)
cJSON_AddStringToObject(config, "username", username);
cJSON_AddStringToObject(config, "password", password);
cJSON_AddStringToObject(config, "topic", base_topic);
cJSON_AddNumberToObject(config, "periodicity", periodicity);
const char *config_str = cJSON_Print(config);
char *config_str = cJSON_Print(config);
httpd_resp_sendstr(req, config_str);
free((void *)config_str);
free(config_str);
cJSON_Delete(config);
return ESP_OK;
}
static esp_err_t config_mqtt_post_handler(httpd_req_t *req)
{
ESP_LOGD(TAG, "Handling POST /api/v1/config/mqtt");
char buf[512];
int len = httpd_req_recv(req, buf, sizeof(buf) - 1);
if (len <= 0) {
if (len <= 0)
{
ESP_LOGE(TAG, "Failed to read request body");
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid request body");
return ESP_FAIL;
@@ -169,33 +177,75 @@ static esp_err_t config_mqtt_post_handler(httpd_req_t *req)
ESP_LOGD(TAG, "Received JSON: %s", buf);
cJSON *json = cJSON_Parse(buf);
if (!json) {
if (!json)
{
ESP_LOGE(TAG, "Invalid JSON format");
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
return ESP_FAIL;
}
bool enabled = false;
const char *host = NULL, *topic = NULL, *username = NULL, *password = NULL;
int periodicity = 30;
// --- Ler config atual (para permitir "partial update" e evitar strings vazias)
bool current_enabled = mqtt_get_enabled();
char current_host[64] = {0};
char current_topic[32] = {0};
char current_user[32] = {0};
char current_pass[64] = {0};
uint16_t current_periodicity = mqtt_get_periodicity();
if (cJSON_IsBool(cJSON_GetObjectItem(json, "enabled")))
enabled = cJSON_GetObjectItem(json, "enabled")->valueint;
mqtt_get_server(current_host);
mqtt_get_base_topic(current_topic);
mqtt_get_user(current_user);
mqtt_get_password(current_pass);
bool enabled = current_enabled;
const char *host_in = NULL, *topic_in = NULL, *user_in = NULL, *pass_in = NULL;
int periodicity = (int)current_periodicity;
cJSON *j_enabled = cJSON_GetObjectItem(json, "enabled");
if (cJSON_IsBool(j_enabled))
enabled = j_enabled->valueint;
cJSON *j_host = cJSON_GetObjectItem(json, "host");
if (cJSON_IsString(j_host)) host = j_host->valuestring;
if (cJSON_IsString(j_host))
host_in = j_host->valuestring;
cJSON *j_topic = cJSON_GetObjectItem(json, "topic");
if (cJSON_IsString(j_topic)) topic = j_topic->valuestring;
if (cJSON_IsString(j_topic))
topic_in = j_topic->valuestring;
cJSON *j_user = cJSON_GetObjectItem(json, "username");
if (cJSON_IsString(j_user)) username = j_user->valuestring;
if (cJSON_IsString(j_user))
user_in = j_user->valuestring;
cJSON *j_pass = cJSON_GetObjectItem(json, "password");
if (cJSON_IsString(j_pass)) password = j_pass->valuestring;
if (cJSON_IsString(j_pass))
pass_in = j_pass->valuestring;
cJSON *j_periodicity = cJSON_GetObjectItem(json, "periodicity");
if (cJSON_IsNumber(j_periodicity)) periodicity = j_periodicity->valueint;
if (cJSON_IsNumber(j_periodicity))
periodicity = j_periodicity->valueint;
// --- Regras: se vier NULL ou "" mantém o atual; se atual também estiver vazio, usa default
const char *host =
(host_in && host_in[0] != '\0') ? host_in : (current_host[0] != '\0') ? current_host
: "mqtt.plixin.com";
const char *topic =
(topic_in && topic_in[0] != '\0') ? topic_in : (current_topic[0] != '\0') ? current_topic
: "";
const char *username =
(user_in && user_in[0] != '\0') ? user_in : (current_user[0] != '\0') ? current_user
: "";
const char *password =
(pass_in && pass_in[0] != '\0') ? pass_in : (current_pass[0] != '\0') ? current_pass
: "";
if (periodicity <= 0)
periodicity = (int)current_periodicity;
if (periodicity <= 0)
periodicity = 30;
ESP_LOGD(TAG, "Applying MQTT config:");
ESP_LOGD(TAG, " Enabled: %s", enabled ? "true" : "false");
@@ -206,7 +256,8 @@ static esp_err_t config_mqtt_post_handler(httpd_req_t *req)
ESP_LOGD(TAG, " Periodicity: %d", periodicity);
esp_err_t err = mqtt_set_config(enabled, host, topic, username, password, periodicity);
if (err != ESP_OK) {
if (err != ESP_OK)
{
ESP_LOGE(TAG, "Failed to apply MQTT config (code %d)", err);
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to apply config");
cJSON_Delete(json);
@@ -218,40 +269,33 @@ static esp_err_t config_mqtt_post_handler(httpd_req_t *req)
return ESP_OK;
}
void register_network_handlers(httpd_handle_t server, void *ctx) {
void register_network_handlers(httpd_handle_t server, void *ctx)
{
httpd_uri_t wifi_get = {
.uri = "/api/v1/config/wifi",
.method = HTTP_GET,
.handler = wifi_get_handler,
.user_ctx = ctx
};
.user_ctx = ctx};
httpd_register_uri_handler(server, &wifi_get);
httpd_uri_t wifi_post = {
.uri = "/api/v1/config/wifi",
.method = HTTP_POST,
.handler = wifi_post_handler,
.user_ctx = ctx
};
.user_ctx = ctx};
httpd_register_uri_handler(server, &wifi_post);
// URI handler for getting MQTT config
httpd_uri_t config_mqtt_get_uri = {
.uri = "/api/v1/config/mqtt",
.method = HTTP_GET,
.handler = config_mqtt_get_handler,
.user_ctx = ctx
};
.user_ctx = ctx};
httpd_register_uri_handler(server, &config_mqtt_get_uri);
// URI handler for posting MQTT config
httpd_uri_t config_mqtt_post_uri = {
.uri = "/api/v1/config/mqtt",
.method = HTTP_POST,
.handler = config_mqtt_post_handler,
.user_ctx = ctx
};
.user_ctx = ctx};
httpd_register_uri_handler(server, &config_mqtt_post_uri);
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -13,8 +13,8 @@
}
</style>
<title>ChargeFlow</title>
<script type="module" crossorigin src="/assets/index-CH8H7Z_T.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-SX00HfRO.css">
<script type="module" crossorigin src="/assets/index-0q0tbwk5.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BIZ-rt0x.css">
</head>
<body>
<div id="root"></div>