refactor
This commit is contained in:
parent
bbfc1af66f
commit
f4a66aedec
@ -620,7 +620,6 @@
|
|||||||
drawGauge();
|
drawGauge();
|
||||||
}
|
}
|
||||||
|
|
||||||
// инициализация событий
|
|
||||||
function initEvents() {
|
function initEvents() {
|
||||||
minSlider.addEventListener('input', () => {
|
minSlider.addEventListener('input', () => {
|
||||||
let val = parseFloat(minSlider.value);
|
let val = parseFloat(minSlider.value);
|
||||||
@ -655,7 +654,39 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// инициализация
|
// function controlGPIO(state) {
|
||||||
|
// fetch('/gpio?state=' + state)
|
||||||
|
// .then(response => response.json())
|
||||||
|
// .then(data => {
|
||||||
|
// const indicator = document.getElementById('ledIndicator');
|
||||||
|
// if(data.status === 'on') {
|
||||||
|
// indicator.className = 'led-status led-on';
|
||||||
|
// } else {
|
||||||
|
// indicator.className = 'led-status led-off';
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// function getSensorData() {
|
||||||
|
// fetch('/sensor')
|
||||||
|
// .then(response => response.json())
|
||||||
|
// .then(data => {
|
||||||
|
// document.getElementById('sensorData').innerHTML =
|
||||||
|
// '📊 Значение: ' + data.value + '<br>' +
|
||||||
|
// '📝 Сообщение: ' + data.message;
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// function updateStats() {
|
||||||
|
// fetch('/stats')
|
||||||
|
// .then(response => response.json())
|
||||||
|
// .then(data => {
|
||||||
|
// document.getElementById('heap').innerText = data.free_heap;
|
||||||
|
// document.getElementById('uptime').innerText = data.uptime;
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// setInterval(updateStats, 2000);
|
||||||
|
// getSensorData();
|
||||||
|
|
||||||
|
|
||||||
function init() {
|
function init() {
|
||||||
canvasWidth = canvas.width;
|
canvasWidth = canvas.width;
|
||||||
canvasHeight = canvas.height;
|
canvasHeight = canvas.height;
|
||||||
|
|||||||
231
main/main.c
231
main/main.c
@ -24,9 +24,8 @@
|
|||||||
#include <cJSON.h>
|
#include <cJSON.h>
|
||||||
#include "sdkconfig.h"
|
#include "sdkconfig.h"
|
||||||
|
|
||||||
// ==================== НАСТРОЙКИ ТОЧКИ ДОСТУПА ====================
|
#define AP_MAX_CONN 4
|
||||||
#define AP_MAX_CONN 4 // Максимум клиентов
|
#define AP_CHANNEL 6
|
||||||
#define AP_CHANNEL 6 // Wi-Fi канал
|
|
||||||
|
|
||||||
#define ADC_CHAN0 ADC_CHANNEL_4
|
#define ADC_CHAN0 ADC_CHANNEL_4
|
||||||
#define ADC_CHAN1 ADC_CHANNEL_5
|
#define ADC_CHAN1 ADC_CHANNEL_5
|
||||||
@ -34,6 +33,7 @@
|
|||||||
|
|
||||||
#define THRESHOLD_UP_NVS_NAME "threshold_up"
|
#define THRESHOLD_UP_NVS_NAME "threshold_up"
|
||||||
#define THRESHOLD_LOW_NVS_NAME "threshold_low"
|
#define THRESHOLD_LOW_NVS_NAME "threshold_low"
|
||||||
|
#define NVS_PARTITION "nvs"
|
||||||
|
|
||||||
#define SENSOR_ADC_CHAN 0
|
#define SENSOR_ADC_CHAN 0
|
||||||
|
|
||||||
@ -46,18 +46,14 @@ static atomic_int g_threshold_up = 0;
|
|||||||
|
|
||||||
static atomic_int g_current_pressure = 0;
|
static atomic_int g_current_pressure = 0;
|
||||||
|
|
||||||
|
#define TAG "Pump Controller"
|
||||||
|
|
||||||
static const char *TAG = "ESP32_AP_SERVER";
|
esp_err_t adc_init(void) {
|
||||||
|
|
||||||
esp_err_t adc_init(void)
|
|
||||||
{
|
|
||||||
// Инициализация ADC
|
|
||||||
adc_oneshot_unit_init_cfg_t init_config = {
|
adc_oneshot_unit_init_cfg_t init_config = {
|
||||||
.unit_id = ADC_UNIT_1,
|
.unit_id = ADC_UNIT_1,
|
||||||
};
|
};
|
||||||
ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc_handle));
|
ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc_handle));
|
||||||
|
|
||||||
// Конфигурация каналов
|
|
||||||
adc_oneshot_chan_cfg_t config = {
|
adc_oneshot_chan_cfg_t config = {
|
||||||
.atten = ADC_ATTEN_DB,
|
.atten = ADC_ATTEN_DB,
|
||||||
.bitwidth = ADC_BITWIDTH_DEFAULT,
|
.bitwidth = ADC_BITWIDTH_DEFAULT,
|
||||||
@ -65,7 +61,6 @@ esp_err_t adc_init(void)
|
|||||||
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, ADC_CHAN0, &config));
|
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, ADC_CHAN0, &config));
|
||||||
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, ADC_CHAN1, &config));
|
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, ADC_CHAN1, &config));
|
||||||
|
|
||||||
// Калибровка для ESP32 (Line Fitting)
|
|
||||||
adc_cali_line_fitting_config_t cali_config = {
|
adc_cali_line_fitting_config_t cali_config = {
|
||||||
.unit_id = ADC_UNIT_1,
|
.unit_id = ADC_UNIT_1,
|
||||||
.atten = ADC_ATTEN_DB,
|
.atten = ADC_ATTEN_DB,
|
||||||
@ -75,11 +70,11 @@ esp_err_t adc_init(void)
|
|||||||
esp_err_t ret = adc_cali_create_scheme_line_fitting(&cali_config, &cali_handle);
|
esp_err_t ret = adc_cali_create_scheme_line_fitting(&cali_config, &cali_handle);
|
||||||
if (ret == ESP_OK) {
|
if (ret == ESP_OK) {
|
||||||
is_calibrated = true;
|
is_calibrated = true;
|
||||||
ESP_LOGI(TAG, "ADC калибровка успешна");
|
ESP_LOGI(TAG, "ADC success calibration");
|
||||||
} else if (ret == ESP_ERR_NOT_SUPPORTED) {
|
} else if (ret == ESP_ERR_NOT_SUPPORTED) {
|
||||||
ESP_LOGW(TAG, "Калибровка не доступна (eFuse не записан)");
|
ESP_LOGW(TAG, "Calibrating not avalaible (eFuse doesnt written)");
|
||||||
} else {
|
} else {
|
||||||
ESP_LOGE(TAG, "Ошибка калибровки");
|
ESP_LOGE(TAG, "Error calibrating");
|
||||||
}
|
}
|
||||||
|
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
@ -106,13 +101,13 @@ int adc_read_raw(uint8_t channel)
|
|||||||
} else if (channel == 1) {
|
} else if (channel == 1) {
|
||||||
adc_channel = ADC_CHAN1;
|
adc_channel = ADC_CHAN1;
|
||||||
} else {
|
} else {
|
||||||
ESP_LOGE(TAG, "Неверный канал: %d", channel);
|
ESP_LOGE(TAG, "Wrong ADC channel: %d", channel);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
esp_err_t ret = adc_oneshot_read(adc_handle, adc_channel, &raw_value);
|
esp_err_t ret = adc_oneshot_read(adc_handle, adc_channel, &raw_value);
|
||||||
if (ret != ESP_OK) {
|
if (ret != ESP_OK) {
|
||||||
ESP_LOGE(TAG, "Ошибка чтения ADC");
|
ESP_LOGE(TAG, "Error reading ADC");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
return raw_value;
|
return raw_value;
|
||||||
@ -126,7 +121,7 @@ int adc_read_voltage(uint8_t channel) {
|
|||||||
int voltage_mv = 0;
|
int voltage_mv = 0;
|
||||||
esp_err_t ret = adc_cali_raw_to_voltage(cali_handle, raw_value, &voltage_mv);
|
esp_err_t ret = adc_cali_raw_to_voltage(cali_handle, raw_value, &voltage_mv);
|
||||||
if (ret != ESP_OK) {
|
if (ret != ESP_OK) {
|
||||||
ESP_LOGE(TAG, "Ошибка конвертации в напряжение");
|
ESP_LOGE(TAG, "Error convert to voltage");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
return voltage_mv;
|
return voltage_mv;
|
||||||
@ -138,135 +133,6 @@ int adc_read_voltage(uint8_t channel) {
|
|||||||
|
|
||||||
|
|
||||||
static esp_err_t root_get_handler(httpd_req_t *req) {
|
static esp_err_t root_get_handler(httpd_req_t *req) {
|
||||||
const char* response =
|
|
||||||
"<!DOCTYPE html>"
|
|
||||||
"<html>"
|
|
||||||
"<head>"
|
|
||||||
" <title>ESP32 Access Point Server</title>"
|
|
||||||
" <meta charset='utf-8'>"
|
|
||||||
" <meta name='viewport' content='width=device-width, initial-scale=1'>"
|
|
||||||
" <style>"
|
|
||||||
" * { margin: 0; padding: 0; box-sizing: border-box; }"
|
|
||||||
" body {"
|
|
||||||
" font-family: 'Segoe UI', Arial, sans-serif;"
|
|
||||||
" background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);"
|
|
||||||
" min-height: 100vh;"
|
|
||||||
" padding: 20px;"
|
|
||||||
" }"
|
|
||||||
" .container {"
|
|
||||||
" max-width: 800px;"
|
|
||||||
" margin: 0 auto;"
|
|
||||||
" background: white;"
|
|
||||||
" border-radius: 20px;"
|
|
||||||
" padding: 30px;"
|
|
||||||
" box-shadow: 0 20px 60px rgba(0,0,0,0.3);"
|
|
||||||
" }"
|
|
||||||
" h1 {"
|
|
||||||
" color: #667eea;"
|
|
||||||
" margin-bottom: 20px;"
|
|
||||||
" text-align: center;"
|
|
||||||
" }"
|
|
||||||
" .status-card {"
|
|
||||||
" background: #f0f0f0;"
|
|
||||||
" border-radius: 10px;"
|
|
||||||
" padding: 20px;"
|
|
||||||
" margin: 20px 0;"
|
|
||||||
" }"
|
|
||||||
" .info {"
|
|
||||||
" margin: 10px 0;"
|
|
||||||
" padding: 10px;"
|
|
||||||
" background: #e8f5e9;"
|
|
||||||
" border-left: 4px solid #4CAF50;"
|
|
||||||
" }"
|
|
||||||
" .button {"
|
|
||||||
" background: #667eea;"
|
|
||||||
" color: white;"
|
|
||||||
" border: none;"
|
|
||||||
" padding: 12px 24px;"
|
|
||||||
" border-radius: 8px;"
|
|
||||||
" cursor: pointer;"
|
|
||||||
" font-size: 16px;"
|
|
||||||
" margin: 5px;"
|
|
||||||
" transition: transform 0.2s;"
|
|
||||||
" }"
|
|
||||||
" .button:hover {"
|
|
||||||
" transform: scale(1.05);"
|
|
||||||
" }"
|
|
||||||
" .gpio-control {"
|
|
||||||
" margin: 20px 0;"
|
|
||||||
" padding: 15px;"
|
|
||||||
" background: #fff3e0;"
|
|
||||||
" border-radius: 10px;"
|
|
||||||
" }"
|
|
||||||
" .led-status {"
|
|
||||||
" display: inline-block;"
|
|
||||||
" width: 20px;"
|
|
||||||
" height: 20px;"
|
|
||||||
" border-radius: 50%;"
|
|
||||||
" margin-left: 10px;"
|
|
||||||
" }"
|
|
||||||
" .led-on { background: #4CAF50; box-shadow: 0 0 10px #4CAF50; }"
|
|
||||||
" .led-off { background: #f44336; }"
|
|
||||||
" </style>"
|
|
||||||
"</head>"
|
|
||||||
"<body>"
|
|
||||||
" <div class='container'>"
|
|
||||||
" <h1>🎯 ESP32 Точка Доступа</h1>"
|
|
||||||
" <div class='status-card'>"
|
|
||||||
" <h3>📡 Информация о сервере</h3>"
|
|
||||||
" <div class='info'>✅ HTTP сервер работает</div>"
|
|
||||||
" <div class='info'>🌐 IP адрес: 192.168.4.1</div>"
|
|
||||||
" <div class='info'>💾 Свободно памяти: <span id='heap'>0</span> байт</div>"
|
|
||||||
" <div class='info'>🕐 Время работы: <span id='uptime'>0</span> сек</div>"
|
|
||||||
" </div>"
|
|
||||||
" <div class='gpio-control'>"
|
|
||||||
" <h3>💡 Управление GPIO2 (встроенный LED)</h3>"
|
|
||||||
" <button class='button' onclick='controlGPIO(1)'>🔆 ВКЛ</button>"
|
|
||||||
" <button class='button' onclick='controlGPIO(0)'>💡 ВЫКЛ</button>"
|
|
||||||
" <span id='ledIndicator' class='led-status led-off'></span>"
|
|
||||||
" </div>"
|
|
||||||
" <div class='gpio-control'>"
|
|
||||||
" <h3>📊 Получить данные с датчика</h3>"
|
|
||||||
" <button class='button' onclick='getSensorData()'>📈 Обновить</button>"
|
|
||||||
" <div id='sensorData' class='info' style='margin-top:10px;'>Данные не загружены</div>"
|
|
||||||
" </div>"
|
|
||||||
" </div>"
|
|
||||||
" <script>"
|
|
||||||
" function controlGPIO(state) {"
|
|
||||||
" fetch('/gpio?state=' + state)"
|
|
||||||
" .then(response => response.json())"
|
|
||||||
" .then(data => {"
|
|
||||||
" const indicator = document.getElementById('ledIndicator');"
|
|
||||||
" if(data.status === 'on') {"
|
|
||||||
" indicator.className = 'led-status led-on';"
|
|
||||||
" } else {"
|
|
||||||
" indicator.className = 'led-status led-off';"
|
|
||||||
" }"
|
|
||||||
" });"
|
|
||||||
" }"
|
|
||||||
" function getSensorData() {"
|
|
||||||
" fetch('/sensor')"
|
|
||||||
" .then(response => response.json())"
|
|
||||||
" .then(data => {"
|
|
||||||
" document.getElementById('sensorData').innerHTML = "
|
|
||||||
" '📊 Значение: ' + data.value + '<br>' +"
|
|
||||||
" '📝 Сообщение: ' + data.message;"
|
|
||||||
" });"
|
|
||||||
" }"
|
|
||||||
" function updateStats() {"
|
|
||||||
" fetch('/stats')"
|
|
||||||
" .then(response => response.json())"
|
|
||||||
" .then(data => {"
|
|
||||||
" document.getElementById('heap').innerText = data.free_heap;"
|
|
||||||
" document.getElementById('uptime').innerText = data.uptime;"
|
|
||||||
" });"
|
|
||||||
" }"
|
|
||||||
" setInterval(updateStats, 2000);"
|
|
||||||
" getSensorData();"
|
|
||||||
" </script>"
|
|
||||||
"</body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
httpd_resp_set_type(req, "text/html; charset=utf-8");
|
httpd_resp_set_type(req, "text/html; charset=utf-8");
|
||||||
httpd_resp_send(req, (const char*)assets_index_html, HTTPD_RESP_USE_STRLEN);
|
httpd_resp_send(req, (const char*)assets_index_html, HTTPD_RESP_USE_STRLEN);
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
@ -289,29 +155,25 @@ static esp_err_t save_thresholds_handler(httpd_req_t *req) {
|
|||||||
char *content = NULL;
|
char *content = NULL;
|
||||||
size_t content_len = req->content_len;
|
size_t content_len = req->content_len;
|
||||||
|
|
||||||
// Проверка длины содержимого
|
if (content_len > 512) {
|
||||||
if (content_len > 512) { // Ограничение размера для безопасности
|
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too large");
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too large");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Выделение памяти под содержимое запроса
|
|
||||||
content = malloc(content_len + 1);
|
content = malloc(content_len + 1);
|
||||||
if (!content) {
|
if (!content) {
|
||||||
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
|
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Чтение тела запроса
|
|
||||||
int ret = httpd_req_recv(req, content, content_len);
|
int ret = httpd_req_recv(req, content, content_len);
|
||||||
if (ret <= 0) {
|
if (ret <= 0) {
|
||||||
free(content);
|
free(content);
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Failed to receive data");
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Failed to receive data");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
content[content_len] = '\0'; // Null-terminator
|
content[content_len] = '\0';
|
||||||
|
|
||||||
// Парсинг JSON
|
|
||||||
cJSON *json = cJSON_Parse(content);
|
cJSON *json = cJSON_Parse(content);
|
||||||
free(content);
|
free(content);
|
||||||
|
|
||||||
@ -320,7 +182,6 @@ static esp_err_t save_thresholds_handler(httpd_req_t *req) {
|
|||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Извлечение параметров low и up
|
|
||||||
cJSON *low_item = cJSON_GetObjectItem(json, "low");
|
cJSON *low_item = cJSON_GetObjectItem(json, "low");
|
||||||
cJSON *up_item = cJSON_GetObjectItem(json, "up");
|
cJSON *up_item = cJSON_GetObjectItem(json, "up");
|
||||||
|
|
||||||
@ -347,7 +208,6 @@ static esp_err_t save_thresholds_handler(httpd_req_t *req) {
|
|||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Проверка значений (опционально)
|
|
||||||
if (low_value >= up_value) {
|
if (low_value >= up_value) {
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Low value must be less than up value");
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Low value must be less than up value");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
@ -356,10 +216,9 @@ static esp_err_t save_thresholds_handler(httpd_req_t *req) {
|
|||||||
nvs_handle_t my_handle;
|
nvs_handle_t my_handle;
|
||||||
esp_err_t err;
|
esp_err_t err;
|
||||||
|
|
||||||
// 1. Открываем раздел "nvs" и пространство имен "storage" на запись/чтение
|
err = nvs_open(NVS_PARTITION, NVS_READWRITE, &my_handle);
|
||||||
err = nvs_open("storage", NVS_READWRITE, &my_handle);
|
|
||||||
if (err != ESP_OK) {
|
if (err != ESP_OK) {
|
||||||
ESP_LOGE("TAG", "Error opening NVS");
|
ESP_LOGE(TAG, "Error opening NVS");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -369,14 +228,11 @@ static esp_err_t save_thresholds_handler(httpd_req_t *req) {
|
|||||||
err = nvs_set_i32(my_handle, THRESHOLD_UP_NVS_NAME, up_value);
|
err = nvs_set_i32(my_handle, THRESHOLD_UP_NVS_NAME, up_value);
|
||||||
ESP_ERROR_CHECK(err);
|
ESP_ERROR_CHECK(err);
|
||||||
|
|
||||||
// 4. Сохраняем изменения во flash
|
|
||||||
err = nvs_commit(my_handle);
|
err = nvs_commit(my_handle);
|
||||||
ESP_ERROR_CHECK(err);
|
ESP_ERROR_CHECK(err);
|
||||||
|
|
||||||
// 5. Закрываем хендл
|
|
||||||
nvs_close(my_handle);
|
nvs_close(my_handle);
|
||||||
|
|
||||||
// Формирование успешного ответа
|
|
||||||
snprintf(response, sizeof(response), "{\"success\":true,\"low\":%d,\"up\":%d}", low_value, up_value);
|
snprintf(response, sizeof(response), "{\"success\":true,\"low\":%d,\"up\":%d}", low_value, up_value);
|
||||||
|
|
||||||
httpd_resp_set_type(req, "application/json");
|
httpd_resp_set_type(req, "application/json");
|
||||||
@ -390,20 +246,17 @@ static esp_err_t set_thresholds_handler(httpd_req_t *req) {
|
|||||||
char *content = NULL;
|
char *content = NULL;
|
||||||
size_t content_len = req->content_len;
|
size_t content_len = req->content_len;
|
||||||
|
|
||||||
// Проверка длины содержимого
|
if (content_len > 512) {
|
||||||
if (content_len > 512) { // Ограничение размера для безопасности
|
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too large");
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too large");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Выделение памяти под содержимое запроса
|
|
||||||
content = malloc(content_len + 1);
|
content = malloc(content_len + 1);
|
||||||
if (!content) {
|
if (!content) {
|
||||||
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
|
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Memory allocation failed");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Чтение тела запроса
|
|
||||||
int ret = httpd_req_recv(req, content, content_len);
|
int ret = httpd_req_recv(req, content, content_len);
|
||||||
if (ret <= 0) {
|
if (ret <= 0) {
|
||||||
free(content);
|
free(content);
|
||||||
@ -421,7 +274,6 @@ static esp_err_t set_thresholds_handler(httpd_req_t *req) {
|
|||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Извлечение параметров low и up
|
|
||||||
cJSON *low_item = cJSON_GetObjectItem(json, "low");
|
cJSON *low_item = cJSON_GetObjectItem(json, "low");
|
||||||
cJSON *up_item = cJSON_GetObjectItem(json, "up");
|
cJSON *up_item = cJSON_GetObjectItem(json, "up");
|
||||||
|
|
||||||
@ -448,7 +300,6 @@ static esp_err_t set_thresholds_handler(httpd_req_t *req) {
|
|||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Проверка значений (опционально)
|
|
||||||
if (low_value >= up_value) {
|
if (low_value >= up_value) {
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Low value must be less than up value");
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Low value must be less than up value");
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
@ -457,7 +308,6 @@ static esp_err_t set_thresholds_handler(httpd_req_t *req) {
|
|||||||
atomic_store(&g_threshold_low, low_value);
|
atomic_store(&g_threshold_low, low_value);
|
||||||
atomic_store(&g_threshold_up, up_value);
|
atomic_store(&g_threshold_up, up_value);
|
||||||
|
|
||||||
// Формирование успешного ответа
|
|
||||||
snprintf(response, sizeof(response), "{\"success\":true,\"low\":%d,\"up\":%d}", low_value, up_value);
|
snprintf(response, sizeof(response), "{\"success\":true,\"low\":%d,\"up\":%d}", low_value, up_value);
|
||||||
|
|
||||||
httpd_resp_set_type(req, "application/json");
|
httpd_resp_set_type(req, "application/json");
|
||||||
@ -467,16 +317,13 @@ static esp_err_t set_thresholds_handler(httpd_req_t *req) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void wifi_init_softap(void) {
|
void wifi_init_softap(void) {
|
||||||
// Инициализация сетевого интерфейса
|
|
||||||
ESP_ERROR_CHECK(esp_netif_init());
|
ESP_ERROR_CHECK(esp_netif_init());
|
||||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||||
esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
|
esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
|
||||||
|
|
||||||
// Инициализация Wi-Fi
|
|
||||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||||
|
|
||||||
// Настройка точки доступа
|
|
||||||
wifi_config_t wifi_config = {
|
wifi_config_t wifi_config = {
|
||||||
.ap = {
|
.ap = {
|
||||||
.ssid = CONFIG_AP_WIFI_SSID,
|
.ssid = CONFIG_AP_WIFI_SSID,
|
||||||
@ -502,19 +349,12 @@ void wifi_init_softap(void) {
|
|||||||
ip_info.gw.addr = ipaddr_addr(CONFIG_AP_GATEWAY);
|
ip_info.gw.addr = ipaddr_addr(CONFIG_AP_GATEWAY);
|
||||||
ip_info.netmask.addr = ipaddr_addr(CONFIG_AP_NETMASK);
|
ip_info.netmask.addr = ipaddr_addr(CONFIG_AP_NETMASK);
|
||||||
|
|
||||||
// Останавливаем DHCP сервер, который автоматически запустился
|
|
||||||
ESP_ERROR_CHECK(esp_netif_dhcps_stop(ap_netif));
|
ESP_ERROR_CHECK(esp_netif_dhcps_stop(ap_netif));
|
||||||
|
|
||||||
// Устанавливаем наши настройки IP
|
|
||||||
ESP_ERROR_CHECK(esp_netif_set_ip_info(ap_netif, &ip_info));
|
ESP_ERROR_CHECK(esp_netif_set_ip_info(ap_netif, &ip_info));
|
||||||
|
|
||||||
ESP_ERROR_CHECK(esp_netif_dhcps_start(ap_netif));
|
ESP_ERROR_CHECK(esp_netif_dhcps_start(ap_netif));
|
||||||
|
|
||||||
ESP_LOGI(TAG, "=========================================");
|
|
||||||
ESP_LOGI(TAG, "📶 Wifi name (SSID): %s", CONFIG_AP_WIFI_SSID);
|
|
||||||
ESP_LOGI(TAG, "🔑 Password: %s", strlen(CONFIG_AP_WIFI_PASS) ? CONFIG_AP_WIFI_PASS : "Open network");
|
|
||||||
ESP_LOGI(TAG, "🌐 Webinterface IP address: %s:%s", CONFIG_AP_IP, CONFIG_WEBINTERFACE_PORT);
|
|
||||||
ESP_LOGI(TAG, "=========================================");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void disablePump(void) {
|
static void disablePump(void) {
|
||||||
@ -525,7 +365,7 @@ static void enablePump(void) {
|
|||||||
gpio_set_level(CONFIG_PUMP_PIN, true);
|
gpio_set_level(CONFIG_PUMP_PIN, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void vPumpControllTask(void *pvParameters) {
|
static void vPumpControlTask(void *pvParameters) {
|
||||||
while (1) {
|
while (1) {
|
||||||
int current_pressure = atomic_load(&g_current_pressure);
|
int current_pressure = atomic_load(&g_current_pressure);
|
||||||
int low_treshhold = atomic_load(&g_threshold_low);
|
int low_treshhold = atomic_load(&g_threshold_low);
|
||||||
@ -533,8 +373,10 @@ static void vPumpControllTask(void *pvParameters) {
|
|||||||
|
|
||||||
if (current_pressure < low_treshhold) {
|
if (current_pressure < low_treshhold) {
|
||||||
enablePump();
|
enablePump();
|
||||||
|
ESP_LOGI(TAG, "Pump enabled");
|
||||||
} else if (current_pressure >= up_treshhold) {
|
} else if (current_pressure >= up_treshhold) {
|
||||||
disablePump();
|
disablePump();
|
||||||
|
ESP_LOGI(TAG, "Pump disabled");
|
||||||
}
|
}
|
||||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
}
|
}
|
||||||
@ -555,11 +397,9 @@ static void vHttpServerTask(void *pvParameters) {
|
|||||||
config.max_uri_handlers = 10;
|
config.max_uri_handlers = 10;
|
||||||
config.stack_size = 8192;
|
config.stack_size = 8192;
|
||||||
|
|
||||||
// Запуск HTTP сервера
|
|
||||||
if (httpd_start(&server, &config) == ESP_OK) {
|
if (httpd_start(&server, &config) == ESP_OK) {
|
||||||
ESP_LOGI(TAG, "🚀 HTTP сервер запущен на порту %d", config.server_port);
|
ESP_LOGI(TAG, "🚀 HTTP server run on port %d", config.server_port);
|
||||||
|
|
||||||
// Регистрация URI обработчиков
|
|
||||||
httpd_uri_t root = {
|
httpd_uri_t root = {
|
||||||
.uri = "/",
|
.uri = "/",
|
||||||
.method = HTTP_GET,
|
.method = HTTP_GET,
|
||||||
@ -592,7 +432,7 @@ static void vHttpServerTask(void *pvParameters) {
|
|||||||
};
|
};
|
||||||
httpd_register_uri_handler(server, &save_thresholds);
|
httpd_register_uri_handler(server, &save_thresholds);
|
||||||
} else {
|
} else {
|
||||||
ESP_LOGE(TAG, "❌ Ошибка запуска HTTP сервера");
|
ESP_LOGE(TAG, "❌Error HTTP server running");
|
||||||
}
|
}
|
||||||
|
|
||||||
while (1) {
|
while (1) {
|
||||||
@ -610,14 +450,12 @@ void app_main(void) {
|
|||||||
|
|
||||||
nvs_handle_t my_handle;
|
nvs_handle_t my_handle;
|
||||||
esp_err_t err;
|
esp_err_t err;
|
||||||
// 1. Открываем раздел "nvs" и пространство имен "storage" на запись/чтение
|
err = nvs_open(NVS_PARTITION, NVS_READWRITE, &my_handle);
|
||||||
err = nvs_open("storage", NVS_READWRITE, &my_handle);
|
|
||||||
if (err != ESP_OK) {
|
if (err != ESP_OK) {
|
||||||
ESP_LOGE("TAG", "Error opening NVS");
|
ESP_LOGE(TAG, "Error opening NVS");
|
||||||
}
|
}
|
||||||
|
|
||||||
int32_t threshold_up, threshold_low = 0;
|
int32_t threshold_low = 0;
|
||||||
|
|
||||||
err = nvs_get_i32(my_handle, THRESHOLD_LOW_NVS_NAME, &threshold_low);
|
err = nvs_get_i32(my_handle, THRESHOLD_LOW_NVS_NAME, &threshold_low);
|
||||||
if (err == ESP_OK) {
|
if (err == ESP_OK) {
|
||||||
atomic_store(&g_threshold_low, threshold_low);
|
atomic_store(&g_threshold_low, threshold_low);
|
||||||
@ -627,6 +465,7 @@ void app_main(void) {
|
|||||||
ESP_ERROR_CHECK(err);
|
ESP_ERROR_CHECK(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int32_t threshold_up = 0;
|
||||||
err = nvs_get_i32(my_handle, THRESHOLD_UP_NVS_NAME, &threshold_up);
|
err = nvs_get_i32(my_handle, THRESHOLD_UP_NVS_NAME, &threshold_up);
|
||||||
if (err == ESP_OK) {
|
if (err == ESP_OK) {
|
||||||
atomic_store(&g_threshold_up, threshold_up);
|
atomic_store(&g_threshold_up, threshold_up);
|
||||||
@ -639,23 +478,20 @@ void app_main(void) {
|
|||||||
|
|
||||||
adc_init();
|
adc_init();
|
||||||
pump_init();
|
pump_init();
|
||||||
|
|
||||||
ESP_LOGI(TAG, "=========================================");
|
|
||||||
ESP_LOGI(TAG, "ESP32 Точка Доступа + HTTP Сервер");
|
|
||||||
ESP_LOGI(TAG, "=========================================");
|
|
||||||
|
|
||||||
|
|
||||||
wifi_init_softap();
|
wifi_init_softap();
|
||||||
|
|
||||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
|
|
||||||
xTaskCreate(vHttpServerTask, "http_server", 8192, NULL, 5, NULL);
|
xTaskCreate(vHttpServerTask, "http_server", 8192, NULL, 5, NULL);
|
||||||
xTaskCreate(vPumpControllTask, "pump_controll", 8192, NULL, 5, NULL);
|
xTaskCreate(vPumpControlTask, "pump_controll", 8192, NULL, 5, NULL);
|
||||||
xTaskCreate(vReadSensorTask, "read_sensor", 8192, NULL, 5, NULL);
|
xTaskCreate(vReadSensorTask, "read_sensor", 8192, NULL, 5, NULL);
|
||||||
|
|
||||||
ESP_LOGI(TAG, "✅ Система готова к работе");
|
ESP_LOGI(TAG, "=========================================");
|
||||||
ESP_LOGI(TAG, "📱 Подключитесь к Wi-Fi: %s", CONFIG_AP_WIFI_SSID);
|
ESP_LOGI(TAG, "✅ Ready to work");
|
||||||
ESP_LOGI(TAG, "🌐 Откройте браузер: http://192.168.4.1");
|
ESP_LOGI(TAG, "📱 Connect to Wi-Fi: %s", CONFIG_AP_WIFI_SSID);
|
||||||
|
ESP_LOGI(TAG, "🔑 Wi-Fi Password: %s", strlen(CONFIG_AP_WIFI_PASS) ? CONFIG_AP_WIFI_PASS : "Open network");
|
||||||
|
ESP_LOGI(TAG, "🌐 Open browser: http://%s:%d", CONFIG_AP_IP, CONFIG_WEBINTERFACE_PORT);
|
||||||
|
ESP_LOGI(TAG, "=========================================");
|
||||||
|
|
||||||
while (1) {
|
while (1) {
|
||||||
vTaskDelay(pdMS_TO_TICKS(10000));
|
vTaskDelay(pdMS_TO_TICKS(10000));
|
||||||
@ -664,7 +500,6 @@ void app_main(void) {
|
|||||||
memset(&sta_list, 0, sizeof(sta_list));
|
memset(&sta_list, 0, sizeof(sta_list));
|
||||||
esp_wifi_ap_get_sta_list(&sta_list);
|
esp_wifi_ap_get_sta_list(&sta_list);
|
||||||
|
|
||||||
ESP_LOGI(TAG, "📊 Подключено клиентов: %d", sta_list.num);
|
ESP_LOGI(TAG, "📊 Wi-Fi Clients connected: %d", sta_list.num);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user