Compare commits
23 Commits
5e0eb8b9db
...
v1.0.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 3e7d3cabfe | |||
| 40fd0a667a | |||
| 89e17efcfc | |||
| fb2ab88bc9 | |||
| e07aad2d7d | |||
| 358090db5d | |||
| bfc2b17ed4 | |||
| 6be0512146 | |||
| 6606be456b | |||
| 7f6308bb6f | |||
| 23c72790ef | |||
| a484db06c9 | |||
| 9e00fc1135 | |||
| 44a739a0bd | |||
| 873ccc91c5 | |||
| 39ca2d205a | |||
| 4bbf1339f1 | |||
| ae62a7c8e1 | |||
| 46b0ea7bda | |||
| 26773507d5 | |||
| 0c2b4ac07e | |||
| 557646916d | |||
| 6d83ec1b16 |
@@ -12,8 +12,8 @@
|
|||||||
|
|
||||||
The device boots in APSTA mode by default and services the following AP.
|
The device boots in APSTA mode by default and services the following AP.
|
||||||
|
|
||||||
- SSID: odroid-pm
|
- SSID: powermate
|
||||||
- Password: powermate
|
- Password: hardkernel
|
||||||
|
|
||||||
After connecting to the above AP using a smartphone, etc., you can configure the device by accessing the
|
After connecting to the above AP using a smartphone, etc., you can configure the device by accessing the
|
||||||
`http://192.168.4.1` address.
|
`http://192.168.4.1` address.
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ endif ()
|
|||||||
|
|
||||||
# Register the component. Now, CMake knows how GZ_OUTPUT_FILE is generated
|
# Register the component. Now, CMake knows how GZ_OUTPUT_FILE is generated
|
||||||
# and can correctly handle the dependency for embedding.
|
# and can correctly handle the dependency for embedding.
|
||||||
idf_component_register(SRC_DIRS "app" "nconfig" "wifi" "indicator" "system" "service" "proto"
|
idf_component_register(SRC_DIRS "app" "nconfig" "wifi" "indicator" "service" "proto"
|
||||||
INCLUDE_DIRS "include" "proto"
|
INCLUDE_DIRS "include" "proto"
|
||||||
EMBED_FILES ${GZ_OUTPUT_FILE}
|
EMBED_FILES ${GZ_OUTPUT_FILE}
|
||||||
)
|
)
|
||||||
@@ -69,3 +69,21 @@ add_custom_target(protobuf_generate ALL
|
|||||||
|
|
||||||
add_dependencies(${COMPONENT_LIB} build_web_app)
|
add_dependencies(${COMPONENT_LIB} build_web_app)
|
||||||
add_dependencies(${COMPONENT_LIB} protobuf_generate)
|
add_dependencies(${COMPONENT_LIB} protobuf_generate)
|
||||||
|
|
||||||
|
execute_process(
|
||||||
|
COMMAND git rev-parse --short HEAD
|
||||||
|
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||||
|
OUTPUT_VARIABLE GIT_HASH
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||||
|
)
|
||||||
|
|
||||||
|
add_compile_definitions(VERSION_HASH="${GIT_HASH}")
|
||||||
|
|
||||||
|
execute_process(
|
||||||
|
COMMAND git describe --tags --abbrev=0
|
||||||
|
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||||
|
OUTPUT_VARIABLE GIT_TAG
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||||
|
)
|
||||||
|
|
||||||
|
add_compile_definitions(VERSION_TAG="${GIT_TAG}")
|
||||||
@@ -11,11 +11,14 @@
|
|||||||
#include "nvs_flash.h"
|
#include "nvs_flash.h"
|
||||||
#include "system.h"
|
#include "system.h"
|
||||||
#include "wifi.h"
|
#include "wifi.h"
|
||||||
|
#include "storage.h"
|
||||||
|
|
||||||
void app_main(void)
|
void app_main(void)
|
||||||
{
|
{
|
||||||
|
printf("\n\n== ODROID POWER-MATE ===\n");
|
||||||
|
printf("Version: %s-%s\n\n", VERSION_TAG, VERSION_HASH);
|
||||||
|
|
||||||
ESP_ERROR_CHECK(i2cdev_init());
|
ESP_ERROR_CHECK(i2cdev_init());
|
||||||
;
|
|
||||||
init_led();
|
init_led();
|
||||||
led_set(LED_BLU, BLINK_TRIPLE);
|
led_set(LED_BLU, BLINK_TRIPLE);
|
||||||
led_off(LED_BLU);
|
led_off(LED_BLU);
|
||||||
@@ -28,6 +31,8 @@ void app_main(void)
|
|||||||
}
|
}
|
||||||
ESP_ERROR_CHECK(ret);
|
ESP_ERROR_CHECK(ret);
|
||||||
|
|
||||||
|
storage_init();
|
||||||
|
|
||||||
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());
|
||||||
|
|
||||||
|
|||||||
@@ -42,9 +42,16 @@ enum nconfig_type
|
|||||||
VIN_CURRENT_LIMIT, ///< The maximum current limit for the VIN.
|
VIN_CURRENT_LIMIT, ///< The maximum current limit for the VIN.
|
||||||
MAIN_CURRENT_LIMIT, ///< The maximum current limit for the MAIN out.
|
MAIN_CURRENT_LIMIT, ///< The maximum current limit for the MAIN out.
|
||||||
USB_CURRENT_LIMIT, ///< The maximum current limit for the USB out.
|
USB_CURRENT_LIMIT, ///< The maximum current limit for the USB out.
|
||||||
|
PAGE_USERNAME, ///< Webpage username
|
||||||
|
PAGE_PASSWORD, ///< Webpage password
|
||||||
NCONFIG_TYPE_MAX, ///< Sentinel for the maximum number of configuration types.
|
NCONFIG_TYPE_MAX, ///< Sentinel for the maximum number of configuration types.
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Erase all of nvs data and restart system
|
||||||
|
*/
|
||||||
|
void reset_nconfig();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Checks if a specific configuration value has been set.
|
* @brief Checks if a specific configuration value has been set.
|
||||||
*
|
*
|
||||||
|
|||||||
6
main/include/storage.h
Normal file
6
main/include/storage.h
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
#ifndef STORAGE_H_
|
||||||
|
#define STORAGE_H_
|
||||||
|
|
||||||
|
void storage_init(void);
|
||||||
|
|
||||||
|
#endif /* STORAGE_H_ */
|
||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
#include "nconfig.h"
|
#include "nconfig.h"
|
||||||
|
|
||||||
|
#include "indicator.h"
|
||||||
|
#include "system.h"
|
||||||
#include "esp_err.h"
|
#include "esp_err.h"
|
||||||
#include "nvs_flash.h"
|
#include "nvs_flash.h"
|
||||||
|
|
||||||
@@ -26,6 +28,8 @@ const static char* keys[NCONFIG_TYPE_MAX] = {
|
|||||||
[VIN_CURRENT_LIMIT] = "vin_climit",
|
[VIN_CURRENT_LIMIT] = "vin_climit",
|
||||||
[MAIN_CURRENT_LIMIT] = "main_climit",
|
[MAIN_CURRENT_LIMIT] = "main_climit",
|
||||||
[USB_CURRENT_LIMIT] = "usb_climit",
|
[USB_CURRENT_LIMIT] = "usb_climit",
|
||||||
|
[PAGE_USERNAME] = "username",
|
||||||
|
[PAGE_PASSWORD] = "password",
|
||||||
};
|
};
|
||||||
|
|
||||||
struct default_value
|
struct default_value
|
||||||
@@ -43,11 +47,13 @@ struct default_value const default_values[] = {
|
|||||||
{NETIF_DNS1, "8.8.8.8"},
|
{NETIF_DNS1, "8.8.8.8"},
|
||||||
{NETIF_DNS2, "8.8.4.4"},
|
{NETIF_DNS2, "8.8.4.4"},
|
||||||
{WIFI_MODE, "apsta"},
|
{WIFI_MODE, "apsta"},
|
||||||
{AP_SSID, "odroid-pm"},
|
{AP_SSID, "powermate"},
|
||||||
{AP_PASSWORD, "powermate"},
|
{AP_PASSWORD, "hardkernel"},
|
||||||
{VIN_CURRENT_LIMIT, "8.0"},
|
{VIN_CURRENT_LIMIT, "4.0"},
|
||||||
{MAIN_CURRENT_LIMIT, "7.0"},
|
{MAIN_CURRENT_LIMIT, "3.0"},
|
||||||
{USB_CURRENT_LIMIT, "5.0"},
|
{USB_CURRENT_LIMIT, "3.0"},
|
||||||
|
{PAGE_USERNAME, "admin"},
|
||||||
|
{PAGE_PASSWORD, "password"},
|
||||||
};
|
};
|
||||||
|
|
||||||
esp_err_t init_nconfig()
|
esp_err_t init_nconfig()
|
||||||
@@ -70,6 +76,13 @@ esp_err_t init_nconfig()
|
|||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void reset_nconfig()
|
||||||
|
{
|
||||||
|
nvs_erase_all(handle);
|
||||||
|
led_set(LED_RED, BLINK_FAST);
|
||||||
|
start_reboot_timer(1);
|
||||||
|
}
|
||||||
|
|
||||||
bool nconfig_value_is_not_set(enum nconfig_type type)
|
bool nconfig_value_is_not_set(enum nconfig_type type)
|
||||||
{
|
{
|
||||||
size_t len = 0;
|
size_t len = 0;
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ typedef struct _WifiStatus {
|
|||||||
bool connected;
|
bool connected;
|
||||||
pb_callback_t ssid;
|
pb_callback_t ssid;
|
||||||
int32_t rssi;
|
int32_t rssi;
|
||||||
|
pb_callback_t ip_address;
|
||||||
} WifiStatus;
|
} WifiStatus;
|
||||||
|
|
||||||
/* Contains raw UART data */
|
/* Contains raw UART data */
|
||||||
@@ -66,13 +67,13 @@ extern "C" {
|
|||||||
/* Initializer values for message structs */
|
/* Initializer values for message structs */
|
||||||
#define SensorChannelData_init_default {0, 0, 0}
|
#define SensorChannelData_init_default {0, 0, 0}
|
||||||
#define SensorData_init_default {false, SensorChannelData_init_default, false, SensorChannelData_init_default, false, SensorChannelData_init_default, 0, 0}
|
#define SensorData_init_default {false, SensorChannelData_init_default, false, SensorChannelData_init_default, false, SensorChannelData_init_default, 0, 0}
|
||||||
#define WifiStatus_init_default {0, {{NULL}, NULL}, 0}
|
#define WifiStatus_init_default {0, {{NULL}, NULL}, 0, {{NULL}, NULL}}
|
||||||
#define UartData_init_default {{{NULL}, NULL}}
|
#define UartData_init_default {{{NULL}, NULL}}
|
||||||
#define LoadSwStatus_init_default {0, 0}
|
#define LoadSwStatus_init_default {0, 0}
|
||||||
#define StatusMessage_init_default {0, {SensorData_init_default}}
|
#define StatusMessage_init_default {0, {SensorData_init_default}}
|
||||||
#define SensorChannelData_init_zero {0, 0, 0}
|
#define SensorChannelData_init_zero {0, 0, 0}
|
||||||
#define SensorData_init_zero {false, SensorChannelData_init_zero, false, SensorChannelData_init_zero, false, SensorChannelData_init_zero, 0, 0}
|
#define SensorData_init_zero {false, SensorChannelData_init_zero, false, SensorChannelData_init_zero, false, SensorChannelData_init_zero, 0, 0}
|
||||||
#define WifiStatus_init_zero {0, {{NULL}, NULL}, 0}
|
#define WifiStatus_init_zero {0, {{NULL}, NULL}, 0, {{NULL}, NULL}}
|
||||||
#define UartData_init_zero {{{NULL}, NULL}}
|
#define UartData_init_zero {{{NULL}, NULL}}
|
||||||
#define LoadSwStatus_init_zero {0, 0}
|
#define LoadSwStatus_init_zero {0, 0}
|
||||||
#define StatusMessage_init_zero {0, {SensorData_init_zero}}
|
#define StatusMessage_init_zero {0, {SensorData_init_zero}}
|
||||||
@@ -89,6 +90,7 @@ extern "C" {
|
|||||||
#define WifiStatus_connected_tag 1
|
#define WifiStatus_connected_tag 1
|
||||||
#define WifiStatus_ssid_tag 2
|
#define WifiStatus_ssid_tag 2
|
||||||
#define WifiStatus_rssi_tag 3
|
#define WifiStatus_rssi_tag 3
|
||||||
|
#define WifiStatus_ip_address_tag 4
|
||||||
#define UartData_data_tag 1
|
#define UartData_data_tag 1
|
||||||
#define LoadSwStatus_main_tag 1
|
#define LoadSwStatus_main_tag 1
|
||||||
#define LoadSwStatus_usb_tag 2
|
#define LoadSwStatus_usb_tag 2
|
||||||
@@ -120,7 +122,8 @@ X(a, STATIC, SINGULAR, UINT32, uptime_sec, 5)
|
|||||||
#define WifiStatus_FIELDLIST(X, a) \
|
#define WifiStatus_FIELDLIST(X, a) \
|
||||||
X(a, STATIC, SINGULAR, BOOL, connected, 1) \
|
X(a, STATIC, SINGULAR, BOOL, connected, 1) \
|
||||||
X(a, CALLBACK, SINGULAR, STRING, ssid, 2) \
|
X(a, CALLBACK, SINGULAR, STRING, ssid, 2) \
|
||||||
X(a, STATIC, SINGULAR, INT32, rssi, 3)
|
X(a, STATIC, SINGULAR, INT32, rssi, 3) \
|
||||||
|
X(a, CALLBACK, SINGULAR, STRING, ip_address, 4)
|
||||||
#define WifiStatus_CALLBACK pb_default_field_callback
|
#define WifiStatus_CALLBACK pb_default_field_callback
|
||||||
#define WifiStatus_DEFAULT NULL
|
#define WifiStatus_DEFAULT NULL
|
||||||
|
|
||||||
|
|||||||
222
main/service/auth.c
Normal file
222
main/service/auth.c
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
#include "auth.h"
|
||||||
|
|
||||||
|
#include <esp_http_server.h>
|
||||||
|
#include <esp_random.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
|
||||||
|
static const char* TAG = "AUTH";
|
||||||
|
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
char token[TOKEN_LENGTH];
|
||||||
|
bool active;
|
||||||
|
time_t creation_time;
|
||||||
|
} auth_token_t;
|
||||||
|
|
||||||
|
static auth_token_t s_tokens[MAX_TOKENS];
|
||||||
|
static SemaphoreHandle_t s_token_mutex;
|
||||||
|
|
||||||
|
void auth_init(void)
|
||||||
|
{
|
||||||
|
s_token_mutex = xSemaphoreCreateMutex();
|
||||||
|
if (s_token_mutex == NULL)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to create token mutex");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < MAX_TOKENS; i++)
|
||||||
|
{
|
||||||
|
s_tokens[i].active = false;
|
||||||
|
s_tokens[i].token[0] = '\0';
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Auth module initialized.");
|
||||||
|
}
|
||||||
|
|
||||||
|
char* auth_generate_token(void)
|
||||||
|
{
|
||||||
|
if (xSemaphoreTake(s_token_mutex, portMAX_DELAY) != pdTRUE)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to take token mutex");
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
int free_slot = -1;
|
||||||
|
for (int i = 0; i < MAX_TOKENS; i++)
|
||||||
|
{
|
||||||
|
if (!s_tokens[i].active)
|
||||||
|
{
|
||||||
|
free_slot = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (free_slot == -1)
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "No free token slots available. Invalidating oldest token.");
|
||||||
|
time_t oldest_time = time(NULL);
|
||||||
|
int oldest_idx = -1;
|
||||||
|
for (int i = 0; i < MAX_TOKENS; i++)
|
||||||
|
{
|
||||||
|
if (s_tokens[i].active && s_tokens[i].creation_time < oldest_time)
|
||||||
|
{
|
||||||
|
oldest_time = s_tokens[i].creation_time;
|
||||||
|
oldest_idx = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (oldest_idx != -1)
|
||||||
|
{
|
||||||
|
s_tokens[oldest_idx].active = false;
|
||||||
|
free_slot = oldest_idx;
|
||||||
|
ESP_LOGI(TAG, "Oldest token at index %d invalidated.", oldest_idx);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Could not find an oldest token to invalidate. This should not happen if all are active.");
|
||||||
|
xSemaphoreGive(s_token_mutex);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||||
|
char* new_token = (char*)malloc(TOKEN_LENGTH);
|
||||||
|
if (new_token == NULL)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to allocate memory for new token");
|
||||||
|
xSemaphoreGive(s_token_mutex);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < TOKEN_LENGTH - 1; i++)
|
||||||
|
{
|
||||||
|
new_token[i] = charset[esp_random() % (sizeof(charset) - 1)];
|
||||||
|
}
|
||||||
|
new_token[TOKEN_LENGTH - 1] = '\0';
|
||||||
|
|
||||||
|
strncpy(s_tokens[free_slot].token, new_token, TOKEN_LENGTH);
|
||||||
|
s_tokens[free_slot].active = true;
|
||||||
|
s_tokens[free_slot].creation_time = time(NULL);
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "Generated new token at slot %d: %s", free_slot, new_token);
|
||||||
|
|
||||||
|
xSemaphoreGive(s_token_mutex);
|
||||||
|
return new_token;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool auth_validate_token(const char* token)
|
||||||
|
{
|
||||||
|
if (token == NULL)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (xSemaphoreTake(s_token_mutex, portMAX_DELAY) != pdTRUE)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to take token mutex");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool valid = false;
|
||||||
|
for (int i = 0; i < MAX_TOKENS; i++)
|
||||||
|
{
|
||||||
|
if (s_tokens[i].active && strcmp(s_tokens[i].token, token) == 0)
|
||||||
|
{
|
||||||
|
valid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
xSemaphoreGive(s_token_mutex);
|
||||||
|
return valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
void auth_invalidate_token(const char* token)
|
||||||
|
{
|
||||||
|
if (token == NULL)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (xSemaphoreTake(s_token_mutex, portMAX_DELAY) != pdTRUE)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to take token mutex");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < MAX_TOKENS; i++)
|
||||||
|
{
|
||||||
|
if (s_tokens[i].active && strcmp(s_tokens[i].token, token) == 0)
|
||||||
|
{
|
||||||
|
s_tokens[i].active = false;
|
||||||
|
s_tokens[i].token[0] = '\0'; // Clear token string
|
||||||
|
ESP_LOGI(TAG, "Token at slot %d invalidated.", i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
xSemaphoreGive(s_token_mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
void auth_cleanup_expired_tokens(void) { ESP_LOGD(TAG, "auth_cleanup_expired_tokens called (no-op for now)."); }
|
||||||
|
|
||||||
|
static const char* get_token_from_header(httpd_req_t* req)
|
||||||
|
{
|
||||||
|
char* auth_header = NULL;
|
||||||
|
size_t buf_len;
|
||||||
|
|
||||||
|
if (httpd_req_get_hdr_value_len(req, "Authorization") == 0)
|
||||||
|
{
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
|
||||||
|
auth_header = (char*)malloc(buf_len);
|
||||||
|
if (auth_header == NULL)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to allocate memory for auth header");
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (httpd_req_get_hdr_value_str(req, "Authorization", auth_header, buf_len) != ESP_OK)
|
||||||
|
{
|
||||||
|
free(auth_header);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (strncmp(auth_header, "Bearer ", 7) == 0)
|
||||||
|
{
|
||||||
|
const char* token = auth_header + 7;
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
free(auth_header);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t api_auth_check(httpd_req_t* req)
|
||||||
|
{
|
||||||
|
const char* token = get_token_from_header(req);
|
||||||
|
|
||||||
|
if (token == NULL)
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "API access attempt without token for URI: %s", req->uri);
|
||||||
|
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Authorization token required");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!auth_validate_token(token))
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "API access attempt with invalid token for URI: %s", req->uri);
|
||||||
|
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid or expired token");
|
||||||
|
free((void*)token - 7);
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGD(TAG, "Token validated for URI: %s", req->uri);
|
||||||
|
free((void*)token - 7);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
28
main/service/auth.h
Normal file
28
main/service/auth.h
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
#ifndef AUTH_H
|
||||||
|
#define AUTH_H
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_http_server.h"
|
||||||
|
|
||||||
|
#define MAX_TOKENS 4
|
||||||
|
#define TOKEN_LENGTH 33 // 32 characters + null terminator
|
||||||
|
|
||||||
|
// Function to initialize the authentication module
|
||||||
|
void auth_init(void);
|
||||||
|
|
||||||
|
// Function to generate a new token
|
||||||
|
char* auth_generate_token(void);
|
||||||
|
|
||||||
|
// Function to validate a token
|
||||||
|
bool auth_validate_token(const char* token);
|
||||||
|
|
||||||
|
// Function to invalidate a token (e.g., on logout)
|
||||||
|
void auth_invalidate_token(const char* token);
|
||||||
|
|
||||||
|
// Function to clean up expired tokens (if any)
|
||||||
|
void auth_cleanup_expired_tokens(void);
|
||||||
|
|
||||||
|
esp_err_t api_auth_check(httpd_req_t* req);
|
||||||
|
|
||||||
|
#endif // AUTH_H
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#include "auth.h"
|
||||||
#include "cJSON.h"
|
#include "cJSON.h"
|
||||||
#include "driver/gpio.h"
|
#include "driver/gpio.h"
|
||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
@@ -8,6 +9,12 @@
|
|||||||
|
|
||||||
static esp_err_t control_get_handler(httpd_req_t* req)
|
static esp_err_t control_get_handler(httpd_req_t* req)
|
||||||
{
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
cJSON* root = cJSON_CreateObject();
|
cJSON* root = cJSON_CreateObject();
|
||||||
|
|
||||||
cJSON_AddBoolToObject(root, "load_12v_on", get_main_load_switch());
|
cJSON_AddBoolToObject(root, "load_12v_on", get_main_load_switch());
|
||||||
@@ -25,6 +32,12 @@ static esp_err_t control_get_handler(httpd_req_t* req)
|
|||||||
|
|
||||||
static esp_err_t control_post_handler(httpd_req_t* req)
|
static esp_err_t control_post_handler(httpd_req_t* req)
|
||||||
{
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
char buf[128];
|
char buf[128];
|
||||||
int ret, remaining = req->content_len;
|
int ret, remaining = req->content_len;
|
||||||
|
|
||||||
|
|||||||
@@ -1,157 +0,0 @@
|
|||||||
#include "datalog.h"
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
#include "esp_littlefs.h"
|
|
||||||
#include "esp_log.h"
|
|
||||||
|
|
||||||
static const char* TAG = "datalog";
|
|
||||||
static const char* LOG_FILE_PATH = "/littlefs/datalog.csv";
|
|
||||||
|
|
||||||
#define MAX_LOG_SIZE (700 * 1024)
|
|
||||||
|
|
||||||
void datalog_init(void)
|
|
||||||
{
|
|
||||||
ESP_LOGI(TAG, "Initializing DataLog with LittleFS");
|
|
||||||
|
|
||||||
esp_vfs_littlefs_conf_t conf = {
|
|
||||||
.base_path = "/littlefs",
|
|
||||||
.partition_label = "littlefs",
|
|
||||||
.format_if_mount_failed = true,
|
|
||||||
.dont_mount = false,
|
|
||||||
};
|
|
||||||
|
|
||||||
esp_err_t ret = esp_vfs_littlefs_register(&conf);
|
|
||||||
|
|
||||||
if (ret != ESP_OK)
|
|
||||||
{
|
|
||||||
if (ret == ESP_FAIL)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to mount or format filesystem");
|
|
||||||
}
|
|
||||||
else if (ret == ESP_ERR_NOT_FOUND)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to find LittleFS partition");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to initialize LittleFS (%s)", esp_err_to_name(ret));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t total = 0, used = 0;
|
|
||||||
ret = esp_littlefs_info(conf.partition_label, &total, &used);
|
|
||||||
if (ret != ESP_OK)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to get LittleFS partition information (%s)", esp_err_to_name(ret));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if file exists
|
|
||||||
FILE* f = fopen(LOG_FILE_PATH, "r");
|
|
||||||
if (f == NULL)
|
|
||||||
{
|
|
||||||
ESP_LOGI(TAG, "Log file not found, creating new one.");
|
|
||||||
FILE* f_write = fopen(LOG_FILE_PATH, "w");
|
|
||||||
if (f_write == NULL)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to create log file.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Add header for 3 channels
|
|
||||||
fprintf(f_write,
|
|
||||||
"timestamp,usb_voltage,usb_current,usb_power,main_voltage,main_current,main_power,vin_voltage,vin_"
|
|
||||||
"current,vin_power\n");
|
|
||||||
fclose(f_write);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Here we could check if the header is correct, but for now we assume it is.
|
|
||||||
ESP_LOGI(TAG, "Log file found.");
|
|
||||||
fclose(f);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void datalog_add(uint32_t timestamp, const channel_data_t* channel_data)
|
|
||||||
{
|
|
||||||
struct stat st;
|
|
||||||
if (stat(LOG_FILE_PATH, &st) == 0)
|
|
||||||
{
|
|
||||||
if (st.st_size >= MAX_LOG_SIZE)
|
|
||||||
{
|
|
||||||
ESP_LOGI(TAG, "Log file size (%ld) >= MAX_LOG_SIZE (%d). Truncating.", st.st_size, MAX_LOG_SIZE);
|
|
||||||
|
|
||||||
const char* temp_path = "/littlefs/datalog.tmp";
|
|
||||||
FILE* f_read = fopen(LOG_FILE_PATH, "r");
|
|
||||||
FILE* f_write = fopen(temp_path, "w");
|
|
||||||
|
|
||||||
if (f_read == NULL || f_write == NULL)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to open files for truncation.");
|
|
||||||
if (f_read)
|
|
||||||
fclose(f_read);
|
|
||||||
if (f_write)
|
|
||||||
fclose(f_write);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
char line[256];
|
|
||||||
// Copy header
|
|
||||||
if (fgets(line, sizeof(line), f_read) != NULL)
|
|
||||||
{
|
|
||||||
fputs(line, f_write);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip the oldest data line
|
|
||||||
if (fgets(line, sizeof(line), f_read) == NULL)
|
|
||||||
{
|
|
||||||
// No data lines to skip, something is wrong if we are truncating
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy the rest of the lines
|
|
||||||
while (fgets(line, sizeof(line), f_read) != NULL)
|
|
||||||
{
|
|
||||||
fputs(line, f_write);
|
|
||||||
}
|
|
||||||
|
|
||||||
fclose(f_read);
|
|
||||||
fclose(f_write);
|
|
||||||
|
|
||||||
// Replace the old log with the new one
|
|
||||||
if (remove(LOG_FILE_PATH) != 0)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to remove old log file.");
|
|
||||||
}
|
|
||||||
if (rename(temp_path, LOG_FILE_PATH) != 0)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to rename temp file.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
FILE* f = fopen(LOG_FILE_PATH, "a");
|
|
||||||
if (f == NULL)
|
|
||||||
{
|
|
||||||
ESP_LOGE(TAG, "Failed to open log file for appending.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
fprintf(f, "%lu", timestamp);
|
|
||||||
for (int i = 0; i < 3; ++i)
|
|
||||||
{
|
|
||||||
fprintf(f, ",%.3f,%.3f,%.3f", channel_data[i].voltage, channel_data[i].current, channel_data[i].power);
|
|
||||||
}
|
|
||||||
fprintf(f, "\n");
|
|
||||||
fclose(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* datalog_get_path(void) { return LOG_FILE_PATH; }
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
#ifndef MAIN_SERVICE_DATALOG_H_
|
|
||||||
#define MAIN_SERVICE_DATALOG_H_
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
|
|
||||||
#define NUM_CHANNELS 3
|
|
||||||
|
|
||||||
typedef struct
|
|
||||||
{
|
|
||||||
float voltage;
|
|
||||||
float current;
|
|
||||||
float power;
|
|
||||||
} channel_data_t;
|
|
||||||
|
|
||||||
void datalog_init(void);
|
|
||||||
void datalog_add(uint32_t timestamp, const channel_data_t* channel_data);
|
|
||||||
const char* datalog_get_path(void);
|
|
||||||
|
|
||||||
#endif /* MAIN_SERVICE_DATALOG_H_ */
|
|
||||||
@@ -6,7 +6,6 @@
|
|||||||
#include <nconfig.h>
|
#include <nconfig.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include "climit.h"
|
#include "climit.h"
|
||||||
#include "datalog.h"
|
|
||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
#include "esp_netif.h"
|
#include "esp_netif.h"
|
||||||
#include "esp_timer.h"
|
#include "esp_timer.h"
|
||||||
@@ -37,6 +36,7 @@ static const char* TAG = "monitor";
|
|||||||
|
|
||||||
static esp_timer_handle_t sensor_timer;
|
static esp_timer_handle_t sensor_timer;
|
||||||
static esp_timer_handle_t wifi_status_timer;
|
static esp_timer_handle_t wifi_status_timer;
|
||||||
|
static esp_timer_handle_t long_press_timer;
|
||||||
// static esp_timer_handle_t shutdown_load_sw; // No longer needed
|
// static esp_timer_handle_t shutdown_load_sw; // No longer needed
|
||||||
|
|
||||||
static TaskHandle_t shutdown_task_handle = NULL; // Global task handle
|
static TaskHandle_t shutdown_task_handle = NULL; // Global task handle
|
||||||
@@ -93,8 +93,6 @@ static void sensor_timer_callback(void* arg)
|
|||||||
uint32_t uptime_sec = (uint32_t)(uptime_us / 1000000);
|
uint32_t uptime_sec = (uint32_t)(uptime_us / 1000000);
|
||||||
uint32_t timestamp = (uint32_t)time(NULL);
|
uint32_t timestamp = (uint32_t)time(NULL);
|
||||||
|
|
||||||
channel_data_t channel_data_log[NUM_CHANNELS];
|
|
||||||
|
|
||||||
StatusMessage message = StatusMessage_init_zero;
|
StatusMessage message = StatusMessage_init_zero;
|
||||||
message.which_payload = StatusMessage_sensor_data_tag;
|
message.which_payload = StatusMessage_sensor_data_tag;
|
||||||
SensorData* sensor_data = &message.payload.sensor_data;
|
SensorData* sensor_data = &message.payload.sensor_data;
|
||||||
@@ -114,9 +112,6 @@ static void sensor_timer_callback(void* arg)
|
|||||||
current /= 1000.0f; // mA to A
|
current /= 1000.0f; // mA to A
|
||||||
power = voltage * current;
|
power = voltage * current;
|
||||||
|
|
||||||
// For datalog
|
|
||||||
channel_data_log[i] = (channel_data_t){.voltage = voltage, .current = current, .power = power};
|
|
||||||
|
|
||||||
// For protobuf
|
// For protobuf
|
||||||
channels[i]->voltage = voltage;
|
channels[i]->voltage = voltage;
|
||||||
channels[i]->current = current;
|
channels[i]->current = current;
|
||||||
@@ -137,6 +132,8 @@ static void status_wifi_callback(void* arg)
|
|||||||
StatusMessage message = StatusMessage_init_zero;
|
StatusMessage message = StatusMessage_init_zero;
|
||||||
message.which_payload = StatusMessage_wifi_status_tag;
|
message.which_payload = StatusMessage_wifi_status_tag;
|
||||||
WifiStatus* wifi_status = &message.payload.wifi_status;
|
WifiStatus* wifi_status = &message.payload.wifi_status;
|
||||||
|
char ip_str[16];
|
||||||
|
esp_netif_ip_info_t ip_info;
|
||||||
|
|
||||||
if (wifi_get_current_ap_info(&ap_info) == ESP_OK)
|
if (wifi_get_current_ap_info(&ap_info) == ESP_OK)
|
||||||
{
|
{
|
||||||
@@ -152,9 +149,36 @@ static void status_wifi_callback(void* arg)
|
|||||||
wifi_status->rssi = 0;
|
wifi_status->rssi = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (wifi_get_current_ip_info(&ip_info) == ESP_OK)
|
||||||
|
{
|
||||||
|
esp_ip4addr_ntoa(&ip_info.ip, ip_str, sizeof(ip_str));
|
||||||
|
wifi_status->ip_address.funcs.encode = &encode_string;
|
||||||
|
wifi_status->ip_address.arg = ip_str;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
wifi_status->ip_address.arg = ""; // Empty string
|
||||||
|
}
|
||||||
|
|
||||||
send_pb_message(StatusMessage_fields, &message);
|
send_pb_message(StatusMessage_fields, &message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Placeholder for long press action
|
||||||
|
static void handle_critical_long_press(void)
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "Config reset triggered...");
|
||||||
|
reset_nconfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Timer callback for long press detection
|
||||||
|
static void long_press_timer_callback(void* arg)
|
||||||
|
{
|
||||||
|
if (gpio_get_level(PM_INT_CRITICAL) == 0)
|
||||||
|
{
|
||||||
|
handle_critical_long_press();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// New FreeRTOS task for shutdown logic
|
// New FreeRTOS task for shutdown logic
|
||||||
static void shutdown_load_sw_task(void* pvParameters)
|
static void shutdown_load_sw_task(void* pvParameters)
|
||||||
{
|
{
|
||||||
@@ -168,23 +192,34 @@ static void shutdown_load_sw_task(void* pvParameters)
|
|||||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||||
gpio_set_level(PM_EXPANDER_RST, 1);
|
gpio_set_level(PM_EXPANDER_RST, 1);
|
||||||
config_sw();
|
config_sw();
|
||||||
|
|
||||||
|
// Start a 5-second timer to check for long press
|
||||||
|
esp_timer_start_once(long_press_timer, 5000000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void IRAM_ATTR critical_isr_handler(void* arg)
|
static void IRAM_ATTR critical_isr_handler(void* arg)
|
||||||
{
|
{
|
||||||
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
|
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
|
||||||
|
if (gpio_get_level(PM_INT_CRITICAL) == 0) // Falling edge
|
||||||
|
{
|
||||||
if (shutdown_task_handle != NULL)
|
if (shutdown_task_handle != NULL)
|
||||||
{
|
{
|
||||||
vTaskNotifyGiveFromISR(shutdown_task_handle, &xHigherPriorityTaskWoken);
|
vTaskNotifyGiveFromISR(shutdown_task_handle, &xHigherPriorityTaskWoken);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
else // Rising edge
|
||||||
|
{
|
||||||
|
// Stop the timer if the button is released
|
||||||
|
esp_timer_stop(long_press_timer);
|
||||||
|
}
|
||||||
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
|
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void gpio_init()
|
static void gpio_init()
|
||||||
{
|
{
|
||||||
// critical int
|
// critical int
|
||||||
gpio_set_intr_type(PM_INT_CRITICAL, GPIO_INTR_NEGEDGE);
|
gpio_set_intr_type(PM_INT_CRITICAL, GPIO_INTR_ANYEDGE);
|
||||||
gpio_set_direction(PM_INT_CRITICAL, GPIO_MODE_INPUT);
|
gpio_set_direction(PM_INT_CRITICAL, GPIO_MODE_INPUT);
|
||||||
gpio_install_isr_service(0);
|
gpio_install_isr_service(0);
|
||||||
gpio_isr_handler_add(PM_INT_CRITICAL, critical_isr_handler, (void*)PM_INT_CRITICAL);
|
gpio_isr_handler_add(PM_INT_CRITICAL, critical_isr_handler, (void*)PM_INT_CRITICAL);
|
||||||
@@ -241,16 +276,18 @@ void init_status_monitor()
|
|||||||
lim = atof(buf);
|
lim = atof(buf);
|
||||||
climit_set_usb(lim);
|
climit_set_usb(lim);
|
||||||
|
|
||||||
datalog_init();
|
|
||||||
|
|
||||||
const esp_timer_create_args_t sensor_timer_args = {.callback = &sensor_timer_callback,
|
const esp_timer_create_args_t sensor_timer_args = {.callback = &sensor_timer_callback,
|
||||||
.name = "sensor_reading_timer"};
|
.name = "sensor_reading_timer"};
|
||||||
const esp_timer_create_args_t wifi_timer_args = {.callback = &status_wifi_callback, .name = "wifi_status_timer"};
|
const esp_timer_create_args_t wifi_timer_args = {.callback = &status_wifi_callback, .name = "wifi_status_timer"};
|
||||||
|
const esp_timer_create_args_t long_press_timer_args = {.callback = &long_press_timer_callback,
|
||||||
|
.name = "long_press_timer"};
|
||||||
|
|
||||||
ESP_ERROR_CHECK(esp_timer_create(&sensor_timer_args, &sensor_timer));
|
ESP_ERROR_CHECK(esp_timer_create(&sensor_timer_args, &sensor_timer));
|
||||||
ESP_ERROR_CHECK(esp_timer_create(&wifi_timer_args, &wifi_status_timer));
|
ESP_ERROR_CHECK(esp_timer_create(&wifi_timer_args, &wifi_status_timer));
|
||||||
|
ESP_ERROR_CHECK(esp_timer_create(&long_press_timer_args, &long_press_timer));
|
||||||
|
|
||||||
xTaskCreate(shutdown_load_sw_task, "shutdown_sw_task", configMINIMAL_STACK_SIZE * 3, NULL, 15, &shutdown_task_handle);
|
xTaskCreate(shutdown_load_sw_task, "shutdown_sw_task", configMINIMAL_STACK_SIZE * 3, NULL, 15,
|
||||||
|
&shutdown_task_handle);
|
||||||
|
|
||||||
ESP_ERROR_CHECK(esp_timer_start_periodic(sensor_timer, 1000000));
|
ESP_ERROR_CHECK(esp_timer_start_periodic(sensor_timer, 1000000));
|
||||||
ESP_ERROR_CHECK(esp_timer_start_periodic(wifi_status_timer, 1000000 * 5));
|
ESP_ERROR_CHECK(esp_timer_start_periodic(wifi_status_timer, 1000000 * 5));
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include "auth.h"
|
||||||
#include "cJSON.h"
|
#include "cJSON.h"
|
||||||
#include "climit.h"
|
#include "climit.h"
|
||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
@@ -13,6 +14,12 @@ static const char* TAG = "webserver";
|
|||||||
|
|
||||||
static esp_err_t setting_get_handler(httpd_req_t* req)
|
static esp_err_t setting_get_handler(httpd_req_t* req)
|
||||||
{
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
wifi_ap_record_t ap_info;
|
wifi_ap_record_t ap_info;
|
||||||
cJSON* root = cJSON_CreateObject();
|
cJSON* root = cJSON_CreateObject();
|
||||||
|
|
||||||
@@ -103,6 +110,12 @@ static esp_err_t setting_get_handler(httpd_req_t* req)
|
|||||||
|
|
||||||
static esp_err_t wifi_scan(httpd_req_t* req)
|
static esp_err_t wifi_scan(httpd_req_t* req)
|
||||||
{
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
wifi_ap_record_t* ap_records;
|
wifi_ap_record_t* ap_records;
|
||||||
uint16_t count;
|
uint16_t count;
|
||||||
|
|
||||||
@@ -133,6 +146,12 @@ static esp_err_t wifi_scan(httpd_req_t* req)
|
|||||||
|
|
||||||
static esp_err_t setting_post_handler(httpd_req_t* req)
|
static esp_err_t setting_post_handler(httpd_req_t* req)
|
||||||
{
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
char buf[512];
|
char buf[512];
|
||||||
int received = httpd_req_recv(req, buf, sizeof(buf) - 1);
|
int received = httpd_req_recv(req, buf, sizeof(buf) - 1);
|
||||||
|
|
||||||
@@ -158,6 +177,8 @@ static esp_err_t setting_post_handler(httpd_req_t* req)
|
|||||||
cJSON* vin_climit_item = cJSON_GetObjectItem(root, "vin_current_limit");
|
cJSON* vin_climit_item = cJSON_GetObjectItem(root, "vin_current_limit");
|
||||||
cJSON* main_climit_item = cJSON_GetObjectItem(root, "main_current_limit");
|
cJSON* main_climit_item = cJSON_GetObjectItem(root, "main_current_limit");
|
||||||
cJSON* usb_climit_item = cJSON_GetObjectItem(root, "usb_current_limit");
|
cJSON* usb_climit_item = cJSON_GetObjectItem(root, "usb_current_limit");
|
||||||
|
cJSON* new_username_item = cJSON_GetObjectItem(root, "new_username");
|
||||||
|
cJSON* new_password_item = cJSON_GetObjectItem(root, "new_password");
|
||||||
|
|
||||||
if (mode_item && cJSON_IsString(mode_item))
|
if (mode_item && cJSON_IsString(mode_item))
|
||||||
{
|
{
|
||||||
@@ -303,6 +324,17 @@ static esp_err_t setting_post_handler(httpd_req_t* req)
|
|||||||
}
|
}
|
||||||
httpd_resp_sendstr(req, "{\"status\":\"current_limit_updated\"}");
|
httpd_resp_sendstr(req, "{\"status\":\"current_limit_updated\"}");
|
||||||
}
|
}
|
||||||
|
else if (new_username_item && cJSON_IsString(new_username_item) && new_password_item &&
|
||||||
|
cJSON_IsString(new_password_item))
|
||||||
|
{
|
||||||
|
const char* new_username = new_username_item->valuestring;
|
||||||
|
const char* new_password = new_password_item->valuestring;
|
||||||
|
|
||||||
|
nconfig_write(PAGE_USERNAME, new_username);
|
||||||
|
nconfig_write(PAGE_PASSWORD, new_password);
|
||||||
|
ESP_LOGI(TAG, "Username and password updated successfully.");
|
||||||
|
httpd_resp_sendstr(req, "{\"status\":\"user_credentials_updated\"}");
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid payload");
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid payload");
|
||||||
|
|||||||
53
main/service/storage.c
Normal file
53
main/service/storage.c
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
#include "storage.h"
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include "esp_littlefs.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
|
||||||
|
static const char* TAG = "datalog";
|
||||||
|
|
||||||
|
#define MAX_LOG_SIZE (700 * 1024)
|
||||||
|
|
||||||
|
void storage_init(void)
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "Initializing DataLog with LittleFS");
|
||||||
|
|
||||||
|
esp_vfs_littlefs_conf_t conf = {
|
||||||
|
.base_path = "/littlefs",
|
||||||
|
.partition_label = "littlefs",
|
||||||
|
.format_if_mount_failed = true,
|
||||||
|
.dont_mount = false,
|
||||||
|
};
|
||||||
|
|
||||||
|
esp_err_t ret = esp_vfs_littlefs_register(&conf);
|
||||||
|
|
||||||
|
if (ret != ESP_OK)
|
||||||
|
{
|
||||||
|
if (ret == ESP_FAIL)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to mount or format filesystem");
|
||||||
|
}
|
||||||
|
else if (ret == ESP_ERR_NOT_FOUND)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to find LittleFS partition");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to initialize LittleFS (%s)", esp_err_to_name(ret));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t total = 0, used = 0;
|
||||||
|
ret = esp_littlefs_info(conf.partition_label, &total, &used);
|
||||||
|
if (ret != ESP_OK)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to get LittleFS partition information (%s)", esp_err_to_name(ret));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
#include <esp_log.h>
|
#include <esp_log.h>
|
||||||
#include <esp_timer.h>
|
#include <esp_timer.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
#include "auth.h"
|
||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
#include "esp_system.h"
|
#include "esp_system.h"
|
||||||
|
|
||||||
@@ -50,6 +51,12 @@ void start_reboot_timer(int sec)
|
|||||||
|
|
||||||
static esp_err_t reboot_post_handler(httpd_req_t* req)
|
static esp_err_t reboot_post_handler(httpd_req_t* req)
|
||||||
{
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
httpd_resp_set_type(req, "application/json");
|
httpd_resp_set_type(req, "application/json");
|
||||||
const char* resp_str = "{\"status\": \"reboot timer started\"}";
|
const char* resp_str = "{\"status\": \"reboot timer started\"}";
|
||||||
httpd_resp_send(req, resp_str, strlen(resp_str));
|
httpd_resp_send(req, resp_str, strlen(resp_str));
|
||||||
@@ -77,3 +84,25 @@ void register_reboot_endpoint(httpd_handle_t server)
|
|||||||
.uri = "/api/reboot", .method = HTTP_POST, .handler = reboot_post_handler, .user_ctx = NULL};
|
.uri = "/api/reboot", .method = HTTP_POST, .handler = reboot_post_handler, .user_ctx = NULL};
|
||||||
httpd_register_uri_handler(server, &post_uri);
|
httpd_register_uri_handler(server, &post_uri);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static esp_err_t version_get_handler(httpd_req_t* req)
|
||||||
|
{
|
||||||
|
esp_err_t err = api_auth_check(req);
|
||||||
|
if (err != ESP_OK)
|
||||||
|
{
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
char buf[100];
|
||||||
|
sprintf(buf, "{\"version\": \"%s-%s\"}", VERSION_TAG, VERSION_HASH);
|
||||||
|
httpd_resp_send(req, buf, strlen(buf));
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
void register_version_endpoint(httpd_handle_t server)
|
||||||
|
{
|
||||||
|
httpd_uri_t post_uri = {
|
||||||
|
.uri = "/api/version", .method = HTTP_GET, .handler = version_get_handler, .user_ctx = NULL};
|
||||||
|
httpd_register_uri_handler(server, &post_uri);
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
#include "webserver.h"
|
#include "webserver.h"
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include "datalog.h"
|
#include "auth.h"
|
||||||
|
#include "cJSON.h"
|
||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
#include "esp_wifi.h"
|
#include "esp_wifi.h"
|
||||||
@@ -22,47 +23,149 @@ static esp_err_t index_handler(httpd_req_t* req)
|
|||||||
const size_t index_html_size = (index_html_end - index_html_start);
|
const size_t index_html_size = (index_html_end - index_html_start);
|
||||||
|
|
||||||
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
|
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
|
||||||
|
httpd_resp_set_hdr(req, "Cache-Control", "max-age=3600");
|
||||||
httpd_resp_set_type(req, "text/html");
|
httpd_resp_set_type(req, "text/html");
|
||||||
httpd_resp_send(req, (const char*)index_html_start, index_html_size);
|
|
||||||
|
|
||||||
return ESP_OK;
|
size_t remaining = index_html_size;
|
||||||
}
|
const char* ptr = (const char*)index_html_start;
|
||||||
|
while (remaining > 0)
|
||||||
static esp_err_t datalog_download_handler(httpd_req_t* req)
|
|
||||||
{
|
|
||||||
const char* filepath = datalog_get_path();
|
|
||||||
FILE* f = fopen(filepath, "r");
|
|
||||||
if (f == NULL)
|
|
||||||
{
|
{
|
||||||
ESP_LOGE(TAG, "Failed to open datalog file for reading");
|
size_t to_send = remaining < 2048 ? remaining : 2048;
|
||||||
httpd_resp_send_404(req);
|
if (httpd_resp_send_chunk(req, ptr, to_send) != ESP_OK)
|
||||||
return ESP_FAIL;
|
|
||||||
}
|
|
||||||
|
|
||||||
httpd_resp_set_type(req, "text/csv");
|
|
||||||
httpd_resp_set_hdr(req, "Content-Disposition", "attachment; filename=\"datalog.csv\"");
|
|
||||||
|
|
||||||
char buffer[1024];
|
|
||||||
size_t bytes_read;
|
|
||||||
while ((bytes_read = fread(buffer, 1, sizeof(buffer), f)) > 0)
|
|
||||||
{
|
|
||||||
if (httpd_resp_send_chunk(req, buffer, bytes_read) != ESP_OK)
|
|
||||||
{
|
{
|
||||||
ESP_LOGE(TAG, "File sending failed!");
|
ESP_LOGE(TAG, "File sending failed!");
|
||||||
fclose(f);
|
|
||||||
httpd_resp_send_chunk(req, NULL, 0);
|
httpd_resp_send_chunk(req, NULL, 0);
|
||||||
httpd_resp_send_500(req);
|
httpd_resp_send_500(req);
|
||||||
return ESP_FAIL;
|
return ESP_FAIL;
|
||||||
}
|
}
|
||||||
|
ptr += to_send;
|
||||||
|
remaining -= to_send;
|
||||||
}
|
}
|
||||||
|
|
||||||
fclose(f);
|
|
||||||
httpd_resp_send_chunk(req, NULL, 0);
|
httpd_resp_send_chunk(req, NULL, 0);
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static esp_err_t login_handler(httpd_req_t* req)
|
||||||
|
{
|
||||||
|
char content[100]; // Adjust size as needed for username/password
|
||||||
|
int ret = httpd_req_recv(req, content, sizeof(content) - 1); // -1 for null terminator
|
||||||
|
if (ret <= 0)
|
||||||
|
{ // 0 means connection closed, < 0 means error
|
||||||
|
if (ret == HTTPD_SOCK_ERR_TIMEOUT)
|
||||||
|
{
|
||||||
|
httpd_resp_send_408(req);
|
||||||
|
}
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
content[ret] = '\0'; // Null-terminate the received data
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "Received login request: %s", content);
|
||||||
|
|
||||||
|
cJSON* root = cJSON_Parse(content);
|
||||||
|
if (root == NULL)
|
||||||
|
{
|
||||||
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON* username_json = cJSON_GetObjectItemCaseSensitive(root, "username");
|
||||||
|
cJSON* password_json = cJSON_GetObjectItemCaseSensitive(root, "password");
|
||||||
|
|
||||||
|
if (!cJSON_IsString(username_json) || (username_json->valuestring == NULL) || !cJSON_IsString(password_json) ||
|
||||||
|
(password_json->valuestring == NULL))
|
||||||
|
{
|
||||||
|
cJSON_Delete(root);
|
||||||
|
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing username or password");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* received_username = username_json->valuestring;
|
||||||
|
const char* received_password = password_json->valuestring;
|
||||||
|
|
||||||
|
// Get stored username and password from nconfig
|
||||||
|
size_t stored_username_len = 0;
|
||||||
|
size_t stored_password_len = 0;
|
||||||
|
char* stored_username = NULL;
|
||||||
|
char* stored_password = NULL;
|
||||||
|
bool credentials_match = false;
|
||||||
|
|
||||||
|
if (nconfig_get_str_len(PAGE_USERNAME, &stored_username_len) == ESP_OK && stored_username_len > 1)
|
||||||
|
{
|
||||||
|
stored_username = (char*)malloc(stored_username_len);
|
||||||
|
if (stored_username)
|
||||||
|
{
|
||||||
|
if (nconfig_read(PAGE_USERNAME, stored_username, stored_username_len) != ESP_OK)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to read stored username from nconfig");
|
||||||
|
free(stored_username);
|
||||||
|
stored_username = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nconfig_get_str_len(PAGE_PASSWORD, &stored_password_len) == ESP_OK && stored_password_len > 1)
|
||||||
|
{
|
||||||
|
stored_password = (char*)malloc(stored_password_len);
|
||||||
|
if (stored_password)
|
||||||
|
{
|
||||||
|
if (nconfig_read(PAGE_PASSWORD, stored_password, stored_password_len) != ESP_OK)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to read stored password from nconfig");
|
||||||
|
free(stored_password);
|
||||||
|
stored_password = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stored_username && stored_password)
|
||||||
|
{
|
||||||
|
if (strcmp(received_username, stored_username) == 0 && strcmp(received_password, stored_password) == 0)
|
||||||
|
{
|
||||||
|
credentials_match = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stored_username)
|
||||||
|
free(stored_username);
|
||||||
|
if (stored_password)
|
||||||
|
free(stored_password);
|
||||||
|
|
||||||
|
if (credentials_match)
|
||||||
|
{
|
||||||
|
char* token = auth_generate_token();
|
||||||
|
if (token)
|
||||||
|
{
|
||||||
|
cJSON* response_root = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(response_root, "token", token);
|
||||||
|
char* json_response = cJSON_Print(response_root);
|
||||||
|
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
httpd_resp_sendstr(req, json_response);
|
||||||
|
|
||||||
|
free(token); // Free the token generated by auth_generate_token
|
||||||
|
free(json_response);
|
||||||
|
cJSON_Delete(response_root);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to generate token");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON_Delete(root);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void start_webserver(void)
|
void start_webserver(void)
|
||||||
{
|
{
|
||||||
|
auth_init();
|
||||||
|
|
||||||
httpd_handle_t server = NULL;
|
httpd_handle_t server = NULL;
|
||||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||||
config.stack_size = 1024 * 8;
|
config.stack_size = 1024 * 8;
|
||||||
@@ -79,13 +182,15 @@ void start_webserver(void)
|
|||||||
httpd_uri_t index = {.uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL};
|
httpd_uri_t index = {.uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL};
|
||||||
httpd_register_uri_handler(server, &index);
|
httpd_register_uri_handler(server, &index);
|
||||||
|
|
||||||
httpd_uri_t datalog_uri = {
|
// Login endpoint
|
||||||
.uri = "/datalog.csv", .method = HTTP_GET, .handler = datalog_download_handler, .user_ctx = NULL};
|
httpd_uri_t login = {.uri = "/login", .method = HTTP_POST, .handler = login_handler, .user_ctx = NULL};
|
||||||
httpd_register_uri_handler(server, &datalog_uri);
|
httpd_register_uri_handler(server, &login);
|
||||||
|
|
||||||
register_wifi_endpoint(server);
|
register_wifi_endpoint(server);
|
||||||
register_ws_endpoint(server);
|
register_ws_endpoint(server);
|
||||||
register_control_endpoint(server);
|
register_control_endpoint(server);
|
||||||
register_reboot_endpoint(server);
|
register_reboot_endpoint(server);
|
||||||
|
register_version_endpoint(server);
|
||||||
|
|
||||||
init_status_monitor();
|
init_status_monitor();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
#ifndef ODROID_REMOTE_HTTP_WEBSERVER_H
|
#ifndef ODROID_REMOTE_HTTP_WEBSERVER_H
|
||||||
#define ODROID_REMOTE_HTTP_WEBSERVER_H
|
#define ODROID_REMOTE_HTTP_WEBSERVER_H
|
||||||
|
|
||||||
#include "esp_http_server.h"
|
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
|
#include "esp_http_server.h"
|
||||||
|
|
||||||
void register_wifi_endpoint(httpd_handle_t server);
|
void register_wifi_endpoint(httpd_handle_t server);
|
||||||
void register_ws_endpoint(httpd_handle_t server);
|
void register_ws_endpoint(httpd_handle_t server);
|
||||||
@@ -15,5 +15,6 @@ void register_control_endpoint(httpd_handle_t server);
|
|||||||
void push_data_to_ws(const uint8_t* data, size_t len);
|
void push_data_to_ws(const uint8_t* data, size_t len);
|
||||||
void register_reboot_endpoint(httpd_handle_t server);
|
void register_reboot_endpoint(httpd_handle_t server);
|
||||||
esp_err_t change_baud_rate(int baud_rate);
|
esp_err_t change_baud_rate(int baud_rate);
|
||||||
|
void register_version_endpoint(httpd_handle_t server);
|
||||||
|
|
||||||
#endif // ODROID_REMOTE_HTTP_WEBSERVER_H
|
#endif // ODROID_REMOTE_HTTP_WEBSERVER_H
|
||||||
|
|||||||
@@ -2,15 +2,18 @@
|
|||||||
// Created by shinys on 25. 8. 18..
|
// Created by shinys on 25. 8. 18..
|
||||||
//
|
//
|
||||||
|
|
||||||
|
#include "auth.h"
|
||||||
#include "driver/uart.h"
|
#include "driver/uart.h"
|
||||||
#include "esp_err.h"
|
#include "esp_err.h"
|
||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
#include "freertos/semphr.h"
|
#include "freertos/semphr.h"
|
||||||
#include "nconfig.h"
|
#include "nconfig.h"
|
||||||
#include "pb.h"
|
#include "pb.h"
|
||||||
#include "pb_encode.h"
|
#include "pb_encode.h"
|
||||||
#include "status.pb.h"
|
#include "status.pb.h"
|
||||||
|
#include "string.h" // Added for strlen and strncmp
|
||||||
#include "webserver.h"
|
#include "webserver.h"
|
||||||
|
|
||||||
#define UART_NUM UART_NUM_1
|
#define UART_NUM UART_NUM_1
|
||||||
@@ -193,7 +196,6 @@ static void uart_event_task(void* arg)
|
|||||||
// Muting this event because it is too noisy
|
// Muting this event because it is too noisy
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
ESP_LOGI(TAG, "unhandled uart event type: %d", event.type);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,6 +207,57 @@ static esp_err_t ws_handler(httpd_req_t* req)
|
|||||||
{
|
{
|
||||||
if (req->method == HTTP_GET)
|
if (req->method == HTTP_GET)
|
||||||
{
|
{
|
||||||
|
ESP_LOGI(TAG, "WebSocket GET request received for URI: %s", req->uri);
|
||||||
|
|
||||||
|
char* query_str = NULL;
|
||||||
|
size_t query_len = httpd_req_get_url_query_len(req) + 1;
|
||||||
|
if (query_len > 1)
|
||||||
|
{
|
||||||
|
query_str = malloc(query_len);
|
||||||
|
if (query_str == NULL)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to allocate memory for query string");
|
||||||
|
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Internal Server Error");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
if (httpd_req_get_url_query_str(req, query_str, query_len) != ESP_OK)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "Failed to get query string from URI: %s", req->uri);
|
||||||
|
free(query_str);
|
||||||
|
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Internal Server Error");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Extracted query string: %s", query_str);
|
||||||
|
}
|
||||||
|
|
||||||
|
char token_str[TOKEN_LENGTH];
|
||||||
|
esp_err_t err = ESP_FAIL; // Default to fail
|
||||||
|
|
||||||
|
if (query_str)
|
||||||
|
{
|
||||||
|
err = httpd_query_key_value(query_str, "token", token_str, sizeof(token_str));
|
||||||
|
free(query_str); // Free allocated query string
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err == ESP_OK)
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "Token extracted from query string, value: %s", token_str);
|
||||||
|
if (!auth_validate_token(token_str))
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "WebSocket connection attempt with invalid token for URI: %s", req->uri);
|
||||||
|
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Invalid or expired token");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
ESP_LOGD(TAG, "WebSocket token validated for URI: %s", req->uri);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "Failed to extract token from query string or query string not found, error: %s",
|
||||||
|
esp_err_to_name(err));
|
||||||
|
httpd_resp_send_err(req, HTTPD_401_UNAUTHORIZED, "Authorization token required");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
|
||||||
ESP_LOGI(TAG, "Handshake done, the new connection was opened");
|
ESP_LOGI(TAG, "Handshake done, the new connection was opened");
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
@@ -212,7 +265,6 @@ static esp_err_t ws_handler(httpd_req_t* req)
|
|||||||
httpd_ws_frame_t ws_pkt = {0};
|
httpd_ws_frame_t ws_pkt = {0};
|
||||||
uint8_t buf[BUF_SIZE];
|
uint8_t buf[BUF_SIZE];
|
||||||
ws_pkt.payload = buf;
|
ws_pkt.payload = buf;
|
||||||
ws_pkt.type = HTTPD_WS_TYPE_BINARY;
|
|
||||||
|
|
||||||
esp_err_t ret = httpd_ws_recv_frame(req, &ws_pkt, BUF_SIZE);
|
esp_err_t ret = httpd_ws_recv_frame(req, &ws_pkt, BUF_SIZE);
|
||||||
if (ret != ESP_OK)
|
if (ret != ESP_OK)
|
||||||
@@ -221,7 +273,33 @@ static esp_err_t ws_handler(httpd_req_t* req)
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (ws_pkt.type == HTTPD_WS_TYPE_TEXT && ws_pkt.len == strlen("ping") &&
|
||||||
|
strncmp((const char*)ws_pkt.payload, "ping", ws_pkt.len) == 0)
|
||||||
|
{
|
||||||
|
ESP_LOGD(TAG, "Received application-level ping from client, sending pong.");
|
||||||
|
httpd_ws_frame_t pong_pkt = {
|
||||||
|
.payload = (uint8_t*)"pong", .len = strlen("pong"), .type = HTTPD_WS_TYPE_TEXT, .final = true};
|
||||||
|
return httpd_ws_send_frame(req, &pong_pkt);
|
||||||
|
}
|
||||||
|
else if (ws_pkt.type == HTTPD_WS_TYPE_CLOSE)
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "Client sent close frame, closing connection.");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
else if (ws_pkt.type == HTTPD_WS_TYPE_PING)
|
||||||
|
{
|
||||||
|
ESP_LOGD(TAG, "Received WebSocket PING control frame (handled by httpd).");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
else if (ws_pkt.type == HTTPD_WS_TYPE_PONG)
|
||||||
|
{
|
||||||
|
ESP_LOGD(TAG, "Received WebSocket PONG control frame.");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
uart_write_bytes(UART_NUM, (const char*)ws_pkt.payload, ws_pkt.len);
|
uart_write_bytes(UART_NUM, (const char*)ws_pkt.payload, ws_pkt.len);
|
||||||
|
}
|
||||||
|
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,33 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<main class="container">
|
<div id="login-container" class="d-flex flex-column justify-content-center align-items-center vh-100" style="display: none;">
|
||||||
|
<div class="card p-4 shadow-lg" style="width: 100%; max-width: 400px;">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 class="card-title text-center mb-4">Login to ODROID Power Mate</h2>
|
||||||
|
<div id="login-alert" class="alert alert-danger d-none" role="alert"></div>
|
||||||
|
<form id="login-form">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="username" class="form-label">Username</label>
|
||||||
|
<input type="text" class="form-control" id="username" required>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="password" class="form-label">Password</label>
|
||||||
|
<input type="password" class="form-control" id="password" required>
|
||||||
|
</div>
|
||||||
|
<div class="d-grid">
|
||||||
|
<button type="submit" class="btn btn-primary">Login</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div class="form-check form-switch d-flex justify-content-center mt-4">
|
||||||
|
<input class="form-check-input" type="checkbox" role="switch" id="theme-toggle-login">
|
||||||
|
<label class="form-check-label ms-2" for="theme-toggle-login"><i id="theme-icon-login" class="bi bi-moon-stars-fill"></i></label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<main class="container" style="display: none;">
|
||||||
<header class="d-flex justify-content-between align-items-center mb-3 main-header">
|
<header class="d-flex justify-content-between align-items-center mb-3 main-header">
|
||||||
<div class="order-md-1" style="flex: 1;">
|
<div class="order-md-1" style="flex: 1;">
|
||||||
<div class="d-flex align-items-center">
|
<div class="d-flex align-items-center">
|
||||||
@@ -37,6 +63,9 @@
|
|||||||
data-bs-target="#settingsModal">
|
data-bs-target="#settingsModal">
|
||||||
<i class="bi bi-gear"></i>
|
<i class="bi bi-gear"></i>
|
||||||
</button>
|
</button>
|
||||||
|
<button class="btn btn-outline-secondary ms-3" id="logout-button">
|
||||||
|
<i class="bi bi-box-arrow-right"></i>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -130,9 +159,12 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="bg-body-tertiary text-center p-3">
|
<footer class="bg-body-tertiary text-center p-3 position-relative">
|
||||||
<a href="https://www.hardkernel.com/" target="_blank" class="link-secondary">Hardkernel</a> |
|
<a href="https://www.hardkernel.com/" target="_blank" class="link-secondary text-decoration-none">Hardkernel</a> |
|
||||||
<a href="https://wiki.odroid.com/start" target="_blank" class="link-secondary">Wiki</a>
|
<a href="https://wiki.odroid.com/start" target="_blank" class="link-secondary text-decoration-none">Wiki</a>
|
||||||
|
<div class="position-absolute end-0 top-50 translate-middle-y pe-3">
|
||||||
|
<small class="text-muted" id="version-info"></small>
|
||||||
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<!-- Settings Modal -->
|
<!-- Settings Modal -->
|
||||||
@@ -165,6 +197,11 @@
|
|||||||
id="current-limit-settings-tab" role="tab" type="button">Current Limit
|
id="current-limit-settings-tab" role="tab" type="button">Current Limit
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link" data-bs-target="#user-settings-pane" data-bs-toggle="tab"
|
||||||
|
id="user-settings-tab" role="tab" type="button">User Settings
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link" id="device-settings-tab" data-bs-toggle="tab"
|
<button class="nav-link" id="device-settings-tab" data-bs-toggle="tab"
|
||||||
data-bs-target="#device-settings-pane" type="button" role="tab">Device
|
data-bs-target="#device-settings-pane" type="button" role="tab">Device
|
||||||
@@ -257,7 +294,7 @@
|
|||||||
<div id="ap-mode-config" style="display: none;">
|
<div id="ap-mode-config" style="display: none;">
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="ap-ssid" class="form-label">AP SSID</label>
|
<label for="ap-ssid" class="form-label">AP SSID</label>
|
||||||
<input type="text" class="form-control" id="ap-ssid" placeholder="odroid-pm">
|
<input type="text" class="form-control" id="ap-ssid" placeholder="powermate">
|
||||||
</div>
|
</div>
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="ap-password" class="form-label">AP Password</label>
|
<label for="ap-password" class="form-label">AP Password</label>
|
||||||
@@ -299,6 +336,28 @@
|
|||||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="tab-pane fade" id="user-settings-pane" role="tabpanel">
|
||||||
|
<form id="user-settings-form">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="new-username">New Username</label>
|
||||||
|
<input class="form-control" id="new-username" required type="text">
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="new-password">New Password</label>
|
||||||
|
<input class="form-control" id="new-password" required type="password">
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="confirm-password">Confirm New Password</label>
|
||||||
|
<input class="form-control" id="confirm-password" required type="password">
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-end pt-3 border-top mt-3">
|
||||||
|
<button class="btn btn-primary me-2" id="user-settings-apply-button" type="submit">
|
||||||
|
Apply
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-secondary" data-bs-dismiss="modal" type="button">Close</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
<div class="tab-pane fade" id="device-settings-pane" role="tabpanel">
|
<div class="tab-pane fade" id="device-settings-pane" role="tabpanel">
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="baud-rate-select" class="form-label">UART Baud Rate</label>
|
<label for="baud-rate-select" class="form-label">UART Baud Rate</label>
|
||||||
@@ -346,7 +405,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="wifi-password-connect" class="form-label">Password</label>
|
<label for="wifi-password-connect" class="form-label">Password</label>
|
||||||
<input type="password" class="form-control" id="wifi-password-connect">
|
<input type="password" class="form-control" id="wifi-password-connect" placeholder="Leave blank for open network">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
|
|||||||
144
page/src/api.js
144
page/src/api.js
@@ -4,15 +4,63 @@
|
|||||||
* It abstracts the fetch logic, error handling, and JSON parsing for network and control operations.
|
* It abstracts the fetch logic, error handling, and JSON parsing for network and control operations.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// Function to get authentication headers
|
||||||
|
export function getAuthHeaders() {
|
||||||
|
const token = localStorage.getItem('authToken');
|
||||||
|
if (token) {
|
||||||
|
return { 'Authorization': `Bearer ${token}` };
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Global error handler for unauthorized responses
|
||||||
|
export async function handleResponse(response) {
|
||||||
|
if (response.status === 401) {
|
||||||
|
// Unauthorized, log out the user
|
||||||
|
localStorage.removeItem('authToken');
|
||||||
|
// Redirect to login or trigger a logout event
|
||||||
|
// For now, we'll just reload the page, which will trigger the login screen
|
||||||
|
window.location.reload();
|
||||||
|
throw new Error('Unauthorized: Session expired or invalid token.');
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text();
|
||||||
|
throw new Error(errorText || `HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticates a user with the provided username and password.
|
||||||
|
* @param {string} username The user's username.
|
||||||
|
* @param {string} password The user's password.
|
||||||
|
* @returns {Promise<Object>} A promise that resolves to the server's JSON response containing a token.
|
||||||
|
* @throws {Error} Throws an error if the authentication fails.
|
||||||
|
*/
|
||||||
|
export async function login(username, password) {
|
||||||
|
const response = await fetch('/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
});
|
||||||
|
// Login function does not use handleResponse as it's for obtaining the token
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text();
|
||||||
|
throw new Error(errorText || `Login failed with status: ${response.status}`);
|
||||||
|
}
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetches the list of available Wi-Fi networks from the server.
|
* Fetches the list of available Wi-Fi networks from the server.
|
||||||
* @returns {Promise<Array<Object>>} A promise that resolves to an array of Wi-Fi access point objects.
|
* @returns {Promise<Array<Object>>} A promise that resolves to an array of Wi-Fi access point objects.
|
||||||
* @throws {Error} Throws an error if the network request fails.
|
* @throws {Error} Throws an error if the network request fails.
|
||||||
*/
|
*/
|
||||||
export async function fetchWifiScan() {
|
export async function fetchWifiScan() {
|
||||||
const response = await fetch('/api/wifi/scan');
|
const response = await fetch('/api/wifi/scan', {
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
headers: getAuthHeaders(),
|
||||||
return await response.json();
|
});
|
||||||
|
return await handleResponse(response).then(res => res.json());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,16 +71,15 @@ export async function fetchWifiScan() {
|
|||||||
* @throws {Error} Throws an error if the connection request fails.
|
* @throws {Error} Throws an error if the connection request fails.
|
||||||
*/
|
*/
|
||||||
export async function postWifiConnect(ssid, password) {
|
export async function postWifiConnect(ssid, password) {
|
||||||
const response = await fetch('/api/setting', { // Updated URL
|
const response = await fetch('/api/setting', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
|
},
|
||||||
body: JSON.stringify({ssid, password}),
|
body: JSON.stringify({ssid, password}),
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
return await handleResponse(response).then(res => res.json());
|
||||||
const errorText = await response.text();
|
|
||||||
throw new Error(errorText || `Connection failed with status: ${response.status}`);
|
|
||||||
}
|
|
||||||
return await response.json();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,16 +89,15 @@ export async function postWifiConnect(ssid, password) {
|
|||||||
* @throws {Error} Throws an error if the request fails.
|
* @throws {Error} Throws an error if the request fails.
|
||||||
*/
|
*/
|
||||||
export async function postNetworkSettings(payload) {
|
export async function postNetworkSettings(payload) {
|
||||||
const response = await fetch('/api/setting', { // Updated URL
|
const response = await fetch('/api/setting', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
|
},
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
return await handleResponse(response);
|
||||||
const errorText = await response.text();
|
|
||||||
throw new Error(errorText || `Failed to apply settings with status: ${response.status}`);
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -63,14 +109,13 @@ export async function postNetworkSettings(payload) {
|
|||||||
export async function postBaudRateSetting(baudrate) {
|
export async function postBaudRateSetting(baudrate) {
|
||||||
const response = await fetch('/api/setting', {
|
const response = await fetch('/api/setting', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
|
},
|
||||||
body: JSON.stringify({baudrate}),
|
body: JSON.stringify({baudrate}),
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
return await handleResponse(response);
|
||||||
const errorText = await response.text();
|
|
||||||
throw new Error(errorText || `Failed to apply baudrate with status: ${response.status}`);
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -79,9 +124,10 @@ export async function postBaudRateSetting(baudrate) {
|
|||||||
* @throws {Error} Throws an error if the network request fails.
|
* @throws {Error} Throws an error if the network request fails.
|
||||||
*/
|
*/
|
||||||
export async function fetchSettings() {
|
export async function fetchSettings() {
|
||||||
const response = await fetch('/api/setting'); // Updated URL
|
const response = await fetch('/api/setting', {
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
headers: getAuthHeaders(),
|
||||||
return await response.json();
|
});
|
||||||
|
return await handleResponse(response).then(res => res.json());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,9 +136,10 @@ export async function fetchSettings() {
|
|||||||
* @throws {Error} Throws an error if the network request fails.
|
* @throws {Error} Throws an error if the network request fails.
|
||||||
*/
|
*/
|
||||||
export async function fetchControlStatus() {
|
export async function fetchControlStatus() {
|
||||||
const response = await fetch('/api/control');
|
const response = await fetch('/api/control', {
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
headers: getAuthHeaders(),
|
||||||
return await response.json();
|
});
|
||||||
|
return await handleResponse(response).then(res => res.json());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -104,9 +151,42 @@ export async function fetchControlStatus() {
|
|||||||
export async function postControlCommand(command) {
|
export async function postControlCommand(command) {
|
||||||
const response = await fetch('/api/control', {
|
const response = await fetch('/api/control', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
|
},
|
||||||
body: JSON.stringify(command)
|
body: JSON.stringify(command)
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
return await handleResponse(response);
|
||||||
return response;
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the firmware version from the server.
|
||||||
|
* @returns {Promise<Object>} A promise that resolves to an object containing the version.
|
||||||
|
* @throws {Error} Throws an error if the network request fails.
|
||||||
|
*/
|
||||||
|
export async function fetchVersion() {
|
||||||
|
const response = await fetch('/api/version', {
|
||||||
|
headers: getAuthHeaders(),
|
||||||
|
});
|
||||||
|
return await handleResponse(response).then(res => res.json());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the user's username and password on the server.
|
||||||
|
* @param {string} newUsername The new username.
|
||||||
|
* @param {string} newPassword The new password.
|
||||||
|
* @returns {Promise<Object>} A promise that resolves to the server's JSON response.
|
||||||
|
* @throws {Error} Throws an error if the update fails.
|
||||||
|
*/
|
||||||
|
export async function updateUserSettings(newUsername, newPassword) {
|
||||||
|
const response = await fetch('/api/setting', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
|
},
|
||||||
|
body: JSON.stringify({new_username: newUsername, new_password: newPassword}),
|
||||||
|
});
|
||||||
|
return await handleResponse(response).then(res => res.json());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,3 +86,6 @@ export const mainValueSpan = document.getElementById('main-current-limit-value')
|
|||||||
export const usbSlider = document.getElementById('usb-current-limit-slider');
|
export const usbSlider = document.getElementById('usb-current-limit-slider');
|
||||||
export const usbValueSpan = document.getElementById('usb-current-limit-value');
|
export const usbValueSpan = document.getElementById('usb-current-limit-value');
|
||||||
export const currentLimitApplyButton = document.getElementById('current-limit-apply-button');
|
export const currentLimitApplyButton = document.getElementById('current-limit-apply-button');
|
||||||
|
|
||||||
|
// --- Footer ---
|
||||||
|
export const versionInfo = document.getElementById('version-info');
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
import * as dom from './dom.js';
|
import * as dom from './dom.js';
|
||||||
import * as api from './api.js';
|
import * as api from './api.js';
|
||||||
|
import {getAuthHeaders, handleResponse} from './api.js'; // Import auth functions
|
||||||
import * as ui from './ui.js';
|
import * as ui from './ui.js';
|
||||||
import {clearTerminal, downloadTerminalOutput, fitTerminal} from './terminal.js';
|
import {clearTerminal, downloadTerminalOutput, fitTerminal} from './terminal.js';
|
||||||
import {debounce, isMobile} from './utils.js';
|
import {debounce, isMobile} from './utils.js';
|
||||||
@@ -28,7 +29,10 @@ function updateSliderValue(slider, span) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function loadCurrentLimitSettings() {
|
function loadCurrentLimitSettings() {
|
||||||
fetch('/api/setting')
|
fetch('/api/setting', {
|
||||||
|
headers: getAuthHeaders(), // Add auth headers
|
||||||
|
})
|
||||||
|
.then(handleResponse) // Handle response for 401
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (data.vin_current_limit !== undefined) {
|
if (data.vin_current_limit !== undefined) {
|
||||||
@@ -56,14 +60,6 @@ export function setupEventListeners() {
|
|||||||
console.log("Event listeners already attached. Skipping.");
|
console.log("Event listeners already attached. Skipping.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.log("Attaching event listeners...");
|
|
||||||
|
|
||||||
// --- Theme Toggle ---
|
|
||||||
dom.themeToggle.addEventListener('change', () => {
|
|
||||||
const newTheme = dom.themeToggle.checked ? 'dark' : 'light';
|
|
||||||
localStorage.setItem('theme', newTheme);
|
|
||||||
ui.applyTheme(newTheme);
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- Terminal Controls ---
|
// --- Terminal Controls ---
|
||||||
dom.clearButton.addEventListener('click', clearTerminal);
|
dom.clearButton.addEventListener('click', clearTerminal);
|
||||||
@@ -86,8 +82,12 @@ export function setupEventListeners() {
|
|||||||
if (dom.rebootButton) {
|
if (dom.rebootButton) {
|
||||||
dom.rebootButton.addEventListener('click', () => {
|
dom.rebootButton.addEventListener('click', () => {
|
||||||
if (confirm('Are you sure you want to reboot the device?')) {
|
if (confirm('Are you sure you want to reboot the device?')) {
|
||||||
fetch('/api/reboot', {method: 'POST'})
|
fetch('/api/reboot', {
|
||||||
.then(response => response.ok ? response.json() : Promise.reject('Network response was not ok'))
|
method: 'POST',
|
||||||
|
headers: getAuthHeaders(), // Add auth headers
|
||||||
|
})
|
||||||
|
.then(handleResponse) // Handle response for 401
|
||||||
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
console.log('Reboot command sent:', data);
|
console.log('Reboot command sent:', data);
|
||||||
ui.hideSettingsModal();
|
ui.hideSettingsModal();
|
||||||
@@ -115,10 +115,14 @@ export function setupEventListeners() {
|
|||||||
|
|
||||||
fetch('/api/setting', {
|
fetch('/api/setting', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(), // Add auth headers
|
||||||
|
},
|
||||||
body: JSON.stringify(settings),
|
body: JSON.stringify(settings),
|
||||||
})
|
})
|
||||||
.then(response => response.ok ? response.json() : Promise.reject('Failed to apply settings'))
|
.then(handleResponse) // Handle response for 401
|
||||||
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
console.log('Current limit settings applied:', data);
|
console.log('Current limit settings applied:', data);
|
||||||
})
|
})
|
||||||
@@ -184,5 +188,4 @@ export function setupEventListeners() {
|
|||||||
window.addEventListener('resize', debounce(ui.handleResize, 150));
|
window.addEventListener('resize', debounce(ui.handleResize, 150));
|
||||||
|
|
||||||
listenersAttached = true;
|
listenersAttached = true;
|
||||||
console.log("Event listeners attached successfully.");
|
|
||||||
}
|
}
|
||||||
|
|||||||
179
page/src/main.js
179
page/src/main.js
@@ -12,6 +12,7 @@ import './style.css';
|
|||||||
|
|
||||||
// --- Module Imports -- -
|
// --- Module Imports -- -
|
||||||
import {StatusMessage} from './proto.js';
|
import {StatusMessage} from './proto.js';
|
||||||
|
import * as api from './api.js';
|
||||||
import {initWebSocket} from './websocket.js';
|
import {initWebSocket} from './websocket.js';
|
||||||
import {setupTerminal, term} from './terminal.js';
|
import {setupTerminal, term} from './terminal.js';
|
||||||
import {
|
import {
|
||||||
@@ -21,6 +22,7 @@ import {
|
|||||||
updateSensorUI,
|
updateSensorUI,
|
||||||
updateSwitchStatusUI,
|
updateSwitchStatusUI,
|
||||||
updateUptimeUI,
|
updateUptimeUI,
|
||||||
|
updateVersionUI,
|
||||||
updateWebsocketStatus,
|
updateWebsocketStatus,
|
||||||
updateWifiStatusUI
|
updateWifiStatusUI
|
||||||
} from './ui.js';
|
} from './ui.js';
|
||||||
@@ -29,6 +31,26 @@ import {setupEventListeners} from './events.js';
|
|||||||
// --- Globals ---
|
// --- Globals ---
|
||||||
// StatusMessage is imported directly from the generated proto.js file.
|
// StatusMessage is imported directly from the generated proto.js file.
|
||||||
|
|
||||||
|
// --- DOM Elements ---
|
||||||
|
const loginContainer = document.getElementById('login-container');
|
||||||
|
const mainContent = document.querySelector('main.container');
|
||||||
|
const loginForm = document.getElementById('login-form');
|
||||||
|
const usernameInput = document.getElementById('username');
|
||||||
|
const passwordInput = document.getElementById('password');
|
||||||
|
const loginAlert = document.getElementById('login-alert');
|
||||||
|
const logoutButton = document.getElementById('logout-button');
|
||||||
|
const themeToggleLogin = document.getElementById('theme-toggle-login');
|
||||||
|
const themeIconLogin = document.getElementById('theme-icon-login');
|
||||||
|
const themeToggleMain = document.getElementById('theme-toggle');
|
||||||
|
const themeIconMain = document.getElementById('theme-icon');
|
||||||
|
|
||||||
|
// User Settings DOM Elements
|
||||||
|
const userSettingsForm = document.getElementById('user-settings-form');
|
||||||
|
const newUsernameInput = document.getElementById('new-username');
|
||||||
|
const newPasswordInput = document.getElementById('new-password');
|
||||||
|
const confirmPasswordInput = document.getElementById('confirm-password');
|
||||||
|
|
||||||
|
|
||||||
// --- WebSocket Event Handlers ---
|
// --- WebSocket Event Handlers ---
|
||||||
|
|
||||||
function onWsOpen() {
|
function onWsOpen() {
|
||||||
@@ -109,24 +131,167 @@ function onWsMessage(event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Authentication Functions ---
|
||||||
|
|
||||||
|
function checkAuth() {
|
||||||
|
const token = localStorage.getItem('authToken');
|
||||||
|
if (token) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLogin(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const username = usernameInput.value;
|
||||||
|
const password = passwordInput.value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await api.login(username, password);
|
||||||
|
if (response && response.token) {
|
||||||
|
localStorage.setItem('authToken', response.token);
|
||||||
|
loginAlert.classList.add('d-none');
|
||||||
|
loginContainer.style.setProperty('display', 'none', 'important');
|
||||||
|
initializeMainAppContent(); // After successful login, initialize the main app
|
||||||
|
} else {
|
||||||
|
loginAlert.textContent = 'Login failed: No token received.';
|
||||||
|
loginAlert.classList.remove('d-none');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Login error:', error);
|
||||||
|
loginAlert.textContent = `Login failed: ${error.message}`;
|
||||||
|
loginAlert.classList.remove('d-none');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleLogout() {
|
||||||
|
localStorage.removeItem('authToken');
|
||||||
|
// Hide main content and show login form
|
||||||
|
loginContainer.style.setProperty('display', 'flex', 'important');
|
||||||
|
mainContent.style.setProperty('display', 'none', 'important');
|
||||||
|
// Optionally, disconnect WebSocket or perform other cleanup
|
||||||
|
// For now, just hide the main content.
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- User Settings Functions ---
|
||||||
|
async function handleUserSettingsSubmit(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
const newUsername = newUsernameInput.value;
|
||||||
|
const newPassword = newPasswordInput.value;
|
||||||
|
const confirmPassword = confirmPasswordInput.value;
|
||||||
|
|
||||||
|
if (!newUsername || !newPassword || !confirmPassword) {
|
||||||
|
alert('Please fill in all fields for username and password.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
alert('New password and confirm password do not match.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await api.updateUserSettings(newUsername, newPassword);
|
||||||
|
if (response && response.status === 'user_credentials_updated') {
|
||||||
|
alert('Username and password updated successfully. Please log in again with new credentials.');
|
||||||
|
handleLogout(); // Force logout to re-authenticate with new credentials
|
||||||
|
} else {
|
||||||
|
alert(`Failed to update credentials: ${response.message || 'Unknown error'}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating user settings:', error);
|
||||||
|
alert(`Error updating user settings: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Theme Toggle Functions ---
|
||||||
|
function setupThemeToggles() {
|
||||||
|
// Initialize theme for login page
|
||||||
|
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
||||||
|
applyTheme(savedTheme);
|
||||||
|
themeToggleLogin.checked = savedTheme === 'dark';
|
||||||
|
themeIconLogin.className = savedTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||||
|
|
||||||
|
// Sync main theme toggle with login theme toggle (initial state)
|
||||||
|
themeToggleMain.checked = savedTheme === 'dark';
|
||||||
|
themeIconMain.className = savedTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||||
|
|
||||||
|
themeToggleLogin.addEventListener('change', () => {
|
||||||
|
const newTheme = themeToggleLogin.checked ? 'dark' : 'light';
|
||||||
|
applyTheme(newTheme);
|
||||||
|
localStorage.setItem('theme', newTheme);
|
||||||
|
themeIconLogin.className = newTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||||
|
themeToggleMain.checked = themeToggleLogin.checked; // Keep main toggle in sync
|
||||||
|
themeIconMain.className = themeIconLogin.className; // Keep main icon in sync
|
||||||
|
});
|
||||||
|
|
||||||
|
themeToggleMain.addEventListener('change', () => {
|
||||||
|
const newTheme = themeToggleMain.checked ? 'dark' : 'light';
|
||||||
|
applyTheme(newTheme);
|
||||||
|
localStorage.setItem('theme', newTheme);
|
||||||
|
themeIconMain.className = newTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||||
|
themeToggleLogin.checked = themeToggleMain.checked; // Keep login toggle in sync
|
||||||
|
themeIconLogin.className = themeIconMain.className; // Keep login icon in sync
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// --- Application Initialization ---
|
// --- Application Initialization ---
|
||||||
|
|
||||||
|
async function initializeVersion() {
|
||||||
|
try {
|
||||||
|
const versionData = await api.fetchVersion();
|
||||||
|
if (versionData && versionData.version) {
|
||||||
|
updateVersionUI(versionData.version);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching version:', error);
|
||||||
|
updateVersionUI('N/A');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function connect() {
|
function connect() {
|
||||||
updateControlStatus();
|
updateControlStatus();
|
||||||
initWebSocket({ onOpen: onWsOpen, onClose: onWsClose, onMessage: onWsMessage });
|
initWebSocket({ onOpen: onWsOpen, onClose: onWsClose, onMessage: onWsMessage });
|
||||||
}
|
}
|
||||||
|
|
||||||
function initialize() {
|
// New function to initialize main app content after successful login or on initial load if authenticated
|
||||||
|
function initializeMainAppContent() {
|
||||||
|
loginContainer.style.setProperty('display', 'none', 'important');
|
||||||
|
mainContent.style.setProperty('display', 'block', 'important');
|
||||||
|
|
||||||
initUI();
|
initUI();
|
||||||
setupTerminal();
|
setupTerminal();
|
||||||
|
initializeVersion();
|
||||||
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
setupEventListeners(); // Attach main app event listeners
|
||||||
applyTheme(savedTheme);
|
logoutButton.addEventListener('click', handleLogout); // Attach logout listener
|
||||||
|
|
||||||
setupEventListeners();
|
|
||||||
|
|
||||||
connect();
|
connect();
|
||||||
|
|
||||||
|
// Attach user settings form listener
|
||||||
|
if (userSettingsForm) {
|
||||||
|
userSettingsForm.addEventListener('submit', handleUserSettingsSubmit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function initialize() {
|
||||||
|
setupThemeToggles(); // Setup theme toggles for both login and main (initial sync)
|
||||||
|
|
||||||
|
// Always attach login form listener
|
||||||
|
loginForm.addEventListener('submit', handleLogin);
|
||||||
|
|
||||||
|
if (!checkAuth()) { // If NOT authenticated
|
||||||
|
// Show login form
|
||||||
|
loginContainer.style.setProperty('display', 'flex', 'important');
|
||||||
|
mainContent.style.setProperty('display', 'none', 'important');
|
||||||
|
console.log('Not authenticated. Login form displayed. Main app content NOT initialized.');
|
||||||
|
return; // IMPORTANT: Stop execution here if not authenticated
|
||||||
|
}
|
||||||
|
|
||||||
|
// If authenticated, initialize main content
|
||||||
|
console.log('Authenticated. Initializing main app content.');
|
||||||
|
initializeMainAppContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Start Application ---
|
// --- Start Application ---
|
||||||
|
|||||||
@@ -114,6 +114,10 @@ footer a {
|
|||||||
|
|
||||||
/* Mobile Optimizations */
|
/* Mobile Optimizations */
|
||||||
@media (max-width: 767.98px) {
|
@media (max-width: 767.98px) {
|
||||||
|
#login-container {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
.main-header {
|
.main-header {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ export function updateSwitchStatusUI(swStatus) {
|
|||||||
*/
|
*/
|
||||||
export function updateWifiStatusUI(data) {
|
export function updateWifiStatusUI(data) {
|
||||||
if (data.connected) {
|
if (data.connected) {
|
||||||
|
// Update header status
|
||||||
dom.wifiSsidStatus.textContent = data.ssid;
|
dom.wifiSsidStatus.textContent = data.ssid;
|
||||||
dom.wifiStatus.title = `Signal Strength: ${data.rssi} dBm`;
|
dom.wifiStatus.title = `Signal Strength: ${data.rssi} dBm`;
|
||||||
let iconClass = 'bi me-2 ';
|
let iconClass = 'bi me-2 ';
|
||||||
@@ -91,12 +92,31 @@ export function updateWifiStatusUI(data) {
|
|||||||
dom.wifiIcon.className = iconClass;
|
dom.wifiIcon.className = iconClass;
|
||||||
dom.wifiStatus.classList.replace('text-muted', 'text-success');
|
dom.wifiStatus.classList.replace('text-muted', 'text-success');
|
||||||
dom.wifiStatus.classList.remove('text-danger');
|
dom.wifiStatus.classList.remove('text-danger');
|
||||||
|
|
||||||
|
// Update settings modal
|
||||||
|
dom.currentWifiSsid.textContent = data.ssid;
|
||||||
|
dom.currentWifiIp.textContent = `IP Address: ${data.ipAddress || 'N/A'}`;
|
||||||
} else {
|
} else {
|
||||||
|
// Update header status
|
||||||
dom.wifiSsidStatus.textContent = 'Disconnected';
|
dom.wifiSsidStatus.textContent = 'Disconnected';
|
||||||
dom.wifiStatus.title = '';
|
dom.wifiStatus.title = '';
|
||||||
dom.wifiIcon.className = 'bi bi-wifi-off me-2';
|
dom.wifiIcon.className = 'bi bi-wifi-off me-2';
|
||||||
dom.wifiStatus.classList.replace('text-success', 'text-muted');
|
dom.wifiStatus.classList.replace('text-success', 'text-muted');
|
||||||
dom.wifiStatus.classList.remove('text-danger');
|
dom.wifiStatus.classList.remove('text-danger');
|
||||||
|
|
||||||
|
// Update settings modal
|
||||||
|
dom.currentWifiSsid.textContent = 'Not Connected';
|
||||||
|
dom.currentWifiIp.textContent = 'IP Address: -';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the version information in the footer.
|
||||||
|
* @param {string} version - The firmware version string.
|
||||||
|
*/
|
||||||
|
export function updateVersionUI(version) {
|
||||||
|
if (version) {
|
||||||
|
dom.versionInfo.textContent = `${version}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,32 +2,116 @@
|
|||||||
* @file websocket.js
|
* @file websocket.js
|
||||||
* @description This module handles the WebSocket connection for real-time, two-way
|
* @description This module handles the WebSocket connection for real-time, two-way
|
||||||
* communication with the server. It provides functions to initialize the connection
|
* communication with the server. It provides functions to initialize the connection
|
||||||
* and send messages.
|
* and send messages, including a heartbeat mechanism to detect disconnections.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// The WebSocket instance, exported for potential direct access if needed.
|
// The WebSocket instance, exported for potential direct access if needed.
|
||||||
export let websocket;
|
export let websocket;
|
||||||
|
|
||||||
// The WebSocket server address, derived from the current page's host (hostname + port).
|
// The WebSocket server address, derived from the current page's host (hostname + port).
|
||||||
const gateway = `ws://${window.location.host}/ws`;
|
const baseGateway = `ws://${window.location.host}/ws`;
|
||||||
|
|
||||||
|
// Heartbeat related variables
|
||||||
|
let pingIntervalId = null;
|
||||||
|
let pongTimeoutId = null;
|
||||||
|
const HEARTBEAT_INTERVAL = 10000; // 10 seconds: How often to send a 'ping'
|
||||||
|
const HEARTBEAT_TIMEOUT = 5000; // 5 seconds: How long to wait for a 'pong' after sending a 'ping'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the WebSocket connection and sets up event handlers.
|
* Starts the heartbeat mechanism.
|
||||||
* @param {Object} callbacks - An object containing callback functions for WebSocket events.
|
* Sends a 'ping' message to the server at regular intervals and sets a timeout
|
||||||
* @param {function} callbacks.onOpen - Called when the connection is successfully opened.
|
* to detect if a 'pong' response is not received.
|
||||||
* @param {function} callbacks.onClose - Called when the connection is closed.
|
|
||||||
* @param {function} callbacks.onMessage - Called when a message is received from the server.
|
|
||||||
*/
|
*/
|
||||||
export function initWebSocket({onOpen, onClose, onMessage}) {
|
function startHeartbeat() {
|
||||||
|
stopHeartbeat(); // Ensure any previous heartbeat is stopped before starting a new one
|
||||||
|
|
||||||
|
pingIntervalId = setInterval(() => {
|
||||||
|
if (websocket && websocket.readyState === WebSocket.OPEN) {
|
||||||
|
websocket.send('ping');
|
||||||
|
|
||||||
|
// Set a timeout to check if a pong is received within HEARTBEAT_TIMEOUT
|
||||||
|
pongTimeoutId = setTimeout(() => {
|
||||||
|
console.warn('WebSocket: No pong received within timeout, closing connection.');
|
||||||
|
// If no pong is received, close the connection. This will trigger the onClose handler.
|
||||||
|
websocket.close();
|
||||||
|
}, HEARTBEAT_TIMEOUT);
|
||||||
|
}
|
||||||
|
}, HEARTBEAT_INTERVAL);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops the heartbeat mechanism by clearing the ping interval and pong timeout.
|
||||||
|
*/
|
||||||
|
function stopHeartbeat() {
|
||||||
|
if (pingIntervalId) {
|
||||||
|
clearInterval(pingIntervalId);
|
||||||
|
pingIntervalId = null;
|
||||||
|
}
|
||||||
|
if (pongTimeoutId) {
|
||||||
|
clearTimeout(pongTimeoutId);
|
||||||
|
pongTimeoutId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the WebSocket connection and sets up event handlers, including a heartbeat mechanism.
|
||||||
|
* @param {Object} callbacks - An object containing callback functions for WebSocket events.
|
||||||
|
* @param {function} [callbacks.onOpen] - Called when the connection is successfully opened.
|
||||||
|
* @param {function} [callbacks.onClose] - Called when the connection is closed.
|
||||||
|
* @param {function} [callbacks.onMessage] - Called when a message is received from the server (excluding 'pong' messages).
|
||||||
|
* @param {function} [callbacks.onError] - Called when an error occurs with the WebSocket connection.
|
||||||
|
*/
|
||||||
|
export function initWebSocket({onOpen, onClose, onMessage, onError}) {
|
||||||
|
const token = localStorage.getItem('authToken');
|
||||||
|
let gateway = baseGateway;
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
gateway = `${baseGateway}?token=${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`Trying to open a WebSocket connection to ${gateway}...`);
|
console.log(`Trying to open a WebSocket connection to ${gateway}...`);
|
||||||
websocket = new WebSocket(gateway);
|
websocket = new WebSocket(gateway);
|
||||||
// Set binary type to arraybuffer to handle raw binary data from the UART.
|
// Set binary type to arraybuffer to handle raw binary data from the UART.
|
||||||
websocket.binaryType = "arraybuffer";
|
websocket.binaryType = "arraybuffer";
|
||||||
|
|
||||||
// Assign event handlers from the provided callbacks
|
// Assign event handlers, wrapping user-provided callbacks to include heartbeat logic
|
||||||
if (onOpen) websocket.onopen = onOpen;
|
websocket.onopen = (event) => {
|
||||||
if (onClose) websocket.onclose = onClose;
|
console.log('WebSocket connection opened.');
|
||||||
if (onMessage) websocket.onmessage = onMessage;
|
startHeartbeat(); // Start heartbeat on successful connection
|
||||||
|
if (onOpen) {
|
||||||
|
onOpen(event);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
websocket.onclose = (event) => {
|
||||||
|
console.log('WebSocket connection closed:', event);
|
||||||
|
stopHeartbeat(); // Stop heartbeat when connection closes
|
||||||
|
if (onClose) {
|
||||||
|
onClose(event);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
websocket.onmessage = (event) => {
|
||||||
|
if (event.data === 'pong') {
|
||||||
|
// Clear the timeout as pong was received, resetting for the next ping
|
||||||
|
clearTimeout(pongTimeoutId);
|
||||||
|
pongTimeoutId = null;
|
||||||
|
} else {
|
||||||
|
// If it's not a pong message, pass it to the user's onMessage callback
|
||||||
|
if (onMessage) {
|
||||||
|
onMessage(event);
|
||||||
|
} else {
|
||||||
|
console.log('WebSocket message received:', event.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
websocket.onerror = (error) => {
|
||||||
|
console.error('WebSocket error:', error);
|
||||||
|
if (onError) {
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,5 +121,7 @@ export function initWebSocket({onOpen, onClose, onMessage}) {
|
|||||||
export function sendWebsocketMessage(data) {
|
export function sendWebsocketMessage(data) {
|
||||||
if (websocket && websocket.readyState === WebSocket.OPEN) {
|
if (websocket && websocket.readyState === WebSocket.OPEN) {
|
||||||
websocket.send(data);
|
websocket.send(data);
|
||||||
|
} else {
|
||||||
|
console.warn('WebSocket is not open. Message not sent:', data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,7 @@ message WifiStatus {
|
|||||||
bool connected = 1;
|
bool connected = 1;
|
||||||
string ssid = 2;
|
string ssid = 2;
|
||||||
int32 rssi = 3;
|
int32 rssi = 3;
|
||||||
|
string ip_address = 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Contains raw UART data
|
// Contains raw UART data
|
||||||
|
|||||||
Reference in New Issue
Block a user