Compare commits
17 Commits
873ccc91c5
...
v1.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
| 69f7471953 | |||
| e1f232eace | |||
| 274b70dbbe | |||
| 3e7d3cabfe | |||
| 40fd0a667a | |||
| 89e17efcfc | |||
| fb2ab88bc9 | |||
| e07aad2d7d | |||
| 358090db5d | |||
| bfc2b17ed4 | |||
| 6be0512146 | |||
| 6606be456b | |||
| 7f6308bb6f | |||
| 23c72790ef | |||
| a484db06c9 | |||
| 9e00fc1135 | |||
| 44a739a0bd |
@@ -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}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
#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)
|
||||||
{
|
{
|
||||||
@@ -30,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,6 +42,8 @@ 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.
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
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_ */
|
||||||
@@ -28,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
|
||||||
@@ -50,6 +52,8 @@ struct default_value const default_values[] = {
|
|||||||
{VIN_CURRENT_LIMIT, "4.0"},
|
{VIN_CURRENT_LIMIT, "4.0"},
|
||||||
{MAIN_CURRENT_LIMIT, "3.0"},
|
{MAIN_CURRENT_LIMIT, "3.0"},
|
||||||
{USB_CURRENT_LIMIT, "3.0"},
|
{USB_CURRENT_LIMIT, "3.0"},
|
||||||
|
{PAGE_USERNAME, "admin"},
|
||||||
|
{PAGE_PASSWORD, "password"},
|
||||||
};
|
};
|
||||||
|
|
||||||
esp_err_t init_nconfig()
|
esp_err_t init_nconfig()
|
||||||
|
|||||||
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_ */
|
|
||||||
182
main/service/dbg_console.c
Normal file
182
main/service/dbg_console.c
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
#include "dbg_console.h"
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include "argtable3/argtable3.h"
|
||||||
|
#include "esp_console.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#include "wifi.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* 'wifi_scan' command */
|
||||||
|
static int wifi_scan_handler(int argc, char** argv)
|
||||||
|
{
|
||||||
|
printf("Scanning for Wi-Fi networks...\n");
|
||||||
|
|
||||||
|
wifi_ap_record_t* ap_records;
|
||||||
|
uint16_t count = 0;
|
||||||
|
|
||||||
|
wifi_scan_aps(&ap_records, &count);
|
||||||
|
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
printf("No APs found.\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Found %d APs:\n", count);
|
||||||
|
printf(" %-32s %-4s %s\n", "SSID", "RSSI", "Auth Mode");
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
printf(" %-32s %-4d %s\n", ap_records[i].ssid, ap_records[i].rssi, auth_mode_str(ap_records[i].authmode));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count > 0)
|
||||||
|
{
|
||||||
|
free(ap_records);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void register_wifi_scan(void)
|
||||||
|
{
|
||||||
|
const esp_console_cmd_t cmd = {
|
||||||
|
.command = "wifi_scan",
|
||||||
|
.help = "Scan for available Wi-Fi networks",
|
||||||
|
.hint = NULL,
|
||||||
|
.func = &wifi_scan_handler,
|
||||||
|
};
|
||||||
|
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||||
|
}
|
||||||
|
|
||||||
|
static struct
|
||||||
|
{
|
||||||
|
struct arg_str* ssid;
|
||||||
|
struct arg_str* password;
|
||||||
|
struct arg_end* end;
|
||||||
|
} wifi_connect_args;
|
||||||
|
|
||||||
|
static int wifi_connect_handler(int argc, char** argv)
|
||||||
|
{
|
||||||
|
int nerrors = arg_parse(argc, argv, (void**)&wifi_connect_args);
|
||||||
|
if (nerrors != 0)
|
||||||
|
{
|
||||||
|
arg_print_errors(stderr, wifi_connect_args.end, argv[0]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* ssid = wifi_connect_args.ssid->sval[0];
|
||||||
|
char password[64] = "";
|
||||||
|
|
||||||
|
if (wifi_connect_args.password->count != 0)
|
||||||
|
strncpy(password, wifi_connect_args.password->sval[0], sizeof(password));
|
||||||
|
|
||||||
|
printf("Attempting to connect to SSID: %s\n", ssid);
|
||||||
|
|
||||||
|
esp_err_t err = wifi_sta_set_ap(ssid, password);
|
||||||
|
|
||||||
|
if (err == ESP_OK)
|
||||||
|
{
|
||||||
|
printf("Wi-Fi credentials set. The device will attempt to connect.\n");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Failed to set Wi-Fi credentials.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void register_wifi_connect(void)
|
||||||
|
{
|
||||||
|
wifi_connect_args.ssid = arg_str1(NULL, NULL, "<ssid>", "SSID of the network to connect to");
|
||||||
|
wifi_connect_args.password = arg_str0(NULL, NULL, "<password>", "Password of the network");
|
||||||
|
wifi_connect_args.end = arg_end(2);
|
||||||
|
|
||||||
|
const esp_console_cmd_t cmd = {.command = "wifi_connect",
|
||||||
|
.help = "Connect to a Wi-Fi network",
|
||||||
|
.hint = NULL,
|
||||||
|
.func = &wifi_connect_handler,
|
||||||
|
.argtable = &wifi_connect_args};
|
||||||
|
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 'wifi_status' command */
|
||||||
|
static int wifi_status_handler(int argc, char** argv)
|
||||||
|
{
|
||||||
|
wifi_ap_record_t ap_info;
|
||||||
|
esp_err_t err = wifi_get_current_ap_info(&ap_info);
|
||||||
|
|
||||||
|
if (err == ESP_OK)
|
||||||
|
{
|
||||||
|
printf("Connected to AP:\n");
|
||||||
|
printf(" SSID: %s\n", (char*)ap_info.ssid);
|
||||||
|
printf(" RSSI: %d\n", ap_info.rssi);
|
||||||
|
|
||||||
|
esp_netif_ip_info_t ip_info;
|
||||||
|
err = wifi_get_current_ip_info(&ip_info);
|
||||||
|
|
||||||
|
if (err == ESP_OK)
|
||||||
|
{
|
||||||
|
char ip_str[16];
|
||||||
|
esp_ip4addr_ntoa(&ip_info.ip, ip_str, sizeof(ip_str));
|
||||||
|
printf(" IP Address: %s\n", ip_str);
|
||||||
|
|
||||||
|
esp_ip4addr_ntoa(&ip_info.gw, ip_str, sizeof(ip_str));
|
||||||
|
printf(" Gateway: %s\n", ip_str);
|
||||||
|
|
||||||
|
esp_ip4addr_ntoa(&ip_info.netmask, ip_str, sizeof(ip_str));
|
||||||
|
printf(" Subnet Mask: %s\n", ip_str);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf(" Could not get IP information: %s\n", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printf("Not connected to any AP.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void register_wifi_status(void)
|
||||||
|
{
|
||||||
|
const esp_console_cmd_t cmd = {
|
||||||
|
.command = "wifi_status",
|
||||||
|
.help = "Get current Wi-Fi connection status and IP information",
|
||||||
|
.hint = NULL,
|
||||||
|
.func = &wifi_status_handler,
|
||||||
|
};
|
||||||
|
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t initialize_dbg_console(void)
|
||||||
|
{
|
||||||
|
esp_console_repl_t* repl = NULL;
|
||||||
|
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
|
||||||
|
|
||||||
|
repl_config.prompt = "powermate >";
|
||||||
|
repl_config.max_cmdline_length = 512;
|
||||||
|
|
||||||
|
esp_console_dev_usb_serial_jtag_config_t hw_config = ESP_CONSOLE_DEV_USB_SERIAL_JTAG_CONFIG_DEFAULT();
|
||||||
|
ESP_ERROR_CHECK(esp_console_new_repl_usb_serial_jtag(&hw_config, &repl_config, &repl));
|
||||||
|
|
||||||
|
esp_console_register_help_command();
|
||||||
|
register_wifi_scan();
|
||||||
|
register_wifi_connect();
|
||||||
|
register_wifi_status();
|
||||||
|
|
||||||
|
printf("Debug console initialized.\n");
|
||||||
|
|
||||||
|
esp_console_start_repl(repl);
|
||||||
|
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
13
main/service/dbg_console.h
Normal file
13
main/service/dbg_console.h
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
#ifndef ODROID_POWER_MATE_DBG_CONSOLE_H
|
||||||
|
#define ODROID_POWER_MATE_DBG_CONSOLE_H
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialize the debug console.
|
||||||
|
*
|
||||||
|
* @return ESP_OK on success, or an error code on failure.
|
||||||
|
*/
|
||||||
|
esp_err_t initialize_dbg_console(void);
|
||||||
|
|
||||||
|
#endif // ODROID_POWER_MATE_DBG_CONSOLE_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"
|
||||||
@@ -94,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;
|
||||||
@@ -115,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;
|
||||||
@@ -282,19 +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,
|
const esp_timer_create_args_t long_press_timer_args = {.callback = &long_press_timer_callback,
|
||||||
.name = "long_press_timer"};
|
.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));
|
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));
|
||||||
@@ -80,6 +87,12 @@ void register_reboot_endpoint(httpd_handle_t server)
|
|||||||
|
|
||||||
static esp_err_t version_get_handler(httpd_req_t* req)
|
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");
|
httpd_resp_set_type(req, "application/json");
|
||||||
char buf[100];
|
char buf[100];
|
||||||
sprintf(buf, "{\"version\": \"%s-%s\"}", VERSION_TAG, VERSION_HASH);
|
sprintf(buf, "{\"version\": \"%s-%s\"}", VERSION_TAG, VERSION_HASH);
|
||||||
@@ -92,4 +105,4 @@ void register_version_endpoint(httpd_handle_t server)
|
|||||||
httpd_uri_t post_uri = {
|
httpd_uri_t post_uri = {
|
||||||
.uri = "/api/version", .method = HTTP_GET, .handler = version_get_handler, .user_ctx = NULL};
|
.uri = "/api/version", .method = HTTP_GET, .handler = version_get_handler, .user_ctx = NULL};
|
||||||
httpd_register_uri_handler(server, &post_uri);
|
httpd_register_uri_handler(server, &post_uri);
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
#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 "dbg_console.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 +24,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,9 +183,9 @@ 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);
|
||||||
@@ -90,4 +194,6 @@ void start_webserver(void)
|
|||||||
register_version_endpoint(server);
|
register_version_endpoint(server);
|
||||||
|
|
||||||
init_status_monitor();
|
init_status_monitor();
|
||||||
|
|
||||||
|
initialize_dbg_console();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
uart_write_bytes(UART_NUM, (const char*)ws_pkt.payload, ws_pkt.len);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
@@ -275,4 +353,4 @@ void push_data_to_ws(const uint8_t* data, size_t len)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
esp_err_t change_baud_rate(int baud_rate) { return uart_set_baudrate(UART_NUM, baud_rate); }
|
esp_err_t change_baud_rate(int baud_rate) { return uart_set_baudrate(UART_NUM, baud_rate); }
|
||||||
@@ -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">
|
||||||
@@ -27,7 +53,10 @@
|
|||||||
<span id="power-display" class="text-primary">--.-- W</span>
|
<span id="power-display" class="text-primary">--.-- W</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<h1 class="text-primary text-center order-md-2 mx-auto">ODROID Power Mate</h1>
|
<div class="text-center order-md-2 mx-auto">
|
||||||
|
<h1 class="text-primary mb-0">ODROID Power Mate</h1>
|
||||||
|
<small class="text-muted" id="version-info"></small>
|
||||||
|
</div>
|
||||||
<div class="d-flex align-items-center justify-content-end order-md-3 header-controls" style="flex: 1;">
|
<div class="d-flex align-items-center justify-content-end order-md-3 header-controls" style="flex: 1;">
|
||||||
<div class="form-check form-switch">
|
<div class="form-check form-switch">
|
||||||
<input class="form-check-input" type="checkbox" role="switch" id="theme-toggle">
|
<input class="form-check-input" type="checkbox" role="switch" id="theme-toggle">
|
||||||
@@ -37,6 +66,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,12 +162,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="bg-body-tertiary text-center p-3 position-relative">
|
<footer class="bg-body-tertiary text-center p-3">
|
||||||
<a href="https://www.hardkernel.com/" target="_blank" class="link-secondary text-decoration-none">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 text-decoration-none">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 -->
|
||||||
@@ -168,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
|
||||||
@@ -302,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>
|
||||||
@@ -349,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">
|
||||||
|
|||||||
139
page/src/api.js
139
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,11 +151,13 @@ 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -117,7 +166,27 @@ export async function postControlCommand(command) {
|
|||||||
* @throws {Error} Throws an error if the network request fails.
|
* @throws {Error} Throws an error if the network request fails.
|
||||||
*/
|
*/
|
||||||
export async function fetchVersion() {
|
export async function fetchVersion() {
|
||||||
const response = await fetch('/api/version');
|
const response = await fetch('/api/version', {
|
||||||
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.");
|
|
||||||
}
|
}
|
||||||
|
|||||||
172
page/src/main.js
172
page/src/main.js
@@ -31,20 +31,36 @@ 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() {
|
||||||
updateWebsocketStatus(true);
|
updateWebsocketStatus(true);
|
||||||
if (term) {
|
console.log('Connected to WebSocket Server');
|
||||||
term.write('\x1b[32mConnected to WebSocket Server\x1b[0m\r\n');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onWsClose() {
|
function onWsClose() {
|
||||||
updateWebsocketStatus(false);
|
updateWebsocketStatus(false);
|
||||||
if (term) {
|
console.warn('Connection closed. Reconnecting...');
|
||||||
term.write('\r\n\x1b[31mConnection closed. Reconnecting...\x1b[0m\r\n');
|
|
||||||
}
|
|
||||||
setTimeout(connect, 2000);
|
setTimeout(connect, 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,6 +127,112 @@ 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 ---
|
||||||
|
|
||||||
@@ -131,17 +253,41 @@ function connect() {
|
|||||||
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();
|
initializeVersion();
|
||||||
|
setupEventListeners(); // Attach main app event listeners
|
||||||
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
logoutButton.addEventListener('click', handleLogout); // Attach logout listener
|
||||||
applyTheme(savedTheme);
|
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,11 @@ CONFIG_ESPTOOLPY_FLASHMODE_QIO=y
|
|||||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
CONFIG_UART_ISR_IN_IRAM=y
|
CONFIG_UART_ISR_IN_IRAM=y
|
||||||
|
CONFIG_HTTPD_MAX_REQ_HDR_LEN=2048
|
||||||
|
CONFIG_HTTPD_MAX_URI_LEN=1024
|
||||||
CONFIG_HTTPD_WS_SUPPORT=y
|
CONFIG_HTTPD_WS_SUPPORT=y
|
||||||
|
CONFIG_ESP_HTTPS_SERVER_ENABLE=y
|
||||||
|
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=20
|
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=20
|
||||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=40
|
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=40
|
||||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=40
|
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=40
|
||||||
|
|||||||
Reference in New Issue
Block a user