7 Commits

Author SHA1 Message Date
e07aad2d7d Refactor
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-26 12:09:36 +09:00
358090db5d Fix login page for mobile
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-26 12:08:55 +09:00
bfc2b17ed4 Add token verify in websocket request
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-26 12:08:55 +09:00
6be0512146 Add login function
TODO ws request auth

Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-26 12:08:55 +09:00
6606be456b Move system.c to service dir
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-26 10:29:32 +09:00
7f6308bb6f Delete logger, Add littlefs init function
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-26 09:37:13 +09:00
23c72790ef Update optimized response index
Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
2025-09-24 15:10:28 +09:00
21 changed files with 759 additions and 273 deletions

View File

@@ -16,7 +16,7 @@ endif ()
# Register the component. Now, CMake knows how GZ_OUTPUT_FILE is generated
# 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"
EMBED_FILES ${GZ_OUTPUT_FILE}
)

View File

@@ -11,6 +11,7 @@
#include "nvs_flash.h"
#include "system.h"
#include "wifi.h"
#include "storage.h"
void app_main(void)
{
@@ -30,6 +31,8 @@ void app_main(void)
}
ESP_ERROR_CHECK(ret);
storage_init();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());

6
main/include/storage.h Normal file
View File

@@ -0,0 +1,6 @@
#ifndef STORAGE_H_
#define STORAGE_H_
void storage_init(void);
#endif /* STORAGE_H_ */

222
main/service/auth.c Normal file
View 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
View 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

View File

@@ -1,3 +1,4 @@
#include "auth.h"
#include "cJSON.h"
#include "driver/gpio.h"
#include "esp_http_server.h"
@@ -8,6 +9,12 @@
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_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)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK)
{
return err;
}
char buf[128];
int ret, remaining = req->content_len;

View File

@@ -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; }

View File

@@ -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_ */

View File

@@ -6,7 +6,6 @@
#include <nconfig.h>
#include <time.h>
#include "climit.h"
#include "datalog.h"
#include "esp_log.h"
#include "esp_netif.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 timestamp = (uint32_t)time(NULL);
channel_data_t channel_data_log[NUM_CHANNELS];
StatusMessage message = StatusMessage_init_zero;
message.which_payload = StatusMessage_sensor_data_tag;
SensorData* sensor_data = &message.payload.sensor_data;
@@ -115,9 +112,6 @@ static void sensor_timer_callback(void* arg)
current /= 1000.0f; // mA to A
power = voltage * current;
// For datalog
channel_data_log[i] = (channel_data_t){.voltage = voltage, .current = current, .power = power};
// For protobuf
channels[i]->voltage = voltage;
channels[i]->current = current;
@@ -282,19 +276,18 @@ void init_status_monitor()
lim = atof(buf);
climit_set_usb(lim);
datalog_init();
const esp_timer_create_args_t sensor_timer_args = {.callback = &sensor_timer_callback,
.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 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(&wifi_timer_args, &wifi_status_timer));
ESP_ERROR_CHECK(esp_timer_create(&long_press_timer_args, &long_press_timer));
xTaskCreate(shutdown_load_sw_task, "shutdown_sw_task", configMINIMAL_STACK_SIZE * 3, NULL, 15, &shutdown_task_handle);
xTaskCreate(shutdown_load_sw_task, "shutdown_sw_task", configMINIMAL_STACK_SIZE * 3, NULL, 15,
&shutdown_task_handle);
ESP_ERROR_CHECK(esp_timer_start_periodic(sensor_timer, 1000000));
ESP_ERROR_CHECK(esp_timer_start_periodic(wifi_status_timer, 1000000 * 5));

View File

@@ -1,4 +1,5 @@
#include <stdlib.h>
#include "auth.h"
#include "cJSON.h"
#include "climit.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)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK)
{
return err;
}
wifi_ap_record_t ap_info;
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)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK)
{
return err;
}
wifi_ap_record_t* ap_records;
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)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK)
{
return err;
}
char buf[512];
int received = httpd_req_recv(req, buf, sizeof(buf) - 1);

53
main/service/storage.c Normal file
View 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);
}
}

View File

@@ -7,6 +7,7 @@
#include <esp_log.h>
#include <esp_timer.h>
#include <string.h>
#include "auth.h"
#include "esp_http_server.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)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK)
{
return err;
}
httpd_resp_set_type(req, "application/json");
const char* resp_str = "{\"status\": \"reboot timer started\"}";
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)
{
esp_err_t err = api_auth_check(req);
if (err != ESP_OK)
{
return err;
}
httpd_resp_set_type(req, "application/json");
char buf[100];
sprintf(buf, "{\"version\": \"%s-%s\"}", VERSION_TAG, VERSION_HASH);
@@ -92,4 +105,4 @@ void register_version_endpoint(httpd_handle_t server)
httpd_uri_t post_uri = {
.uri = "/api/version", .method = HTTP_GET, .handler = version_get_handler, .user_ctx = NULL};
httpd_register_uri_handler(server, &post_uri);
}
}

View File

@@ -1,7 +1,8 @@
#include "webserver.h"
#include <stdio.h>
#include <string.h>
#include "datalog.h"
#include "auth.h"
#include "cJSON.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_wifi.h"
@@ -22,47 +23,103 @@ static esp_err_t index_handler(httpd_req_t* req)
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, "Cache-Control", "max-age=3600");
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, (const char*)index_html_start, index_html_size);
return ESP_OK;
}
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)
size_t remaining = index_html_size;
const char* ptr = (const char*)index_html_start;
while (remaining > 0)
{
ESP_LOGE(TAG, "Failed to open datalog file for reading");
httpd_resp_send_404(req);
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)
size_t to_send = remaining < 2048 ? remaining : 2048;
if (httpd_resp_send_chunk(req, ptr, to_send) != ESP_OK)
{
ESP_LOGE(TAG, "File sending failed!");
fclose(f);
httpd_resp_send_chunk(req, NULL, 0);
httpd_resp_send_500(req);
return ESP_FAIL;
}
ptr += to_send;
remaining -= to_send;
}
fclose(f);
httpd_resp_send_chunk(req, NULL, 0);
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* username = username_json->valuestring;
const char* password = password_json->valuestring;
// TODO: Implement actual credential validation
// For now, a simple hardcoded check
if (strcmp(username, "admin") == 0 && strcmp(password, "password") == 0)
{
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)
{
auth_init();
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.stack_size = 1024 * 8;
@@ -79,9 +136,9 @@ void start_webserver(void)
httpd_uri_t index = {.uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL};
httpd_register_uri_handler(server, &index);
httpd_uri_t datalog_uri = {
.uri = "/datalog.csv", .method = HTTP_GET, .handler = datalog_download_handler, .user_ctx = NULL};
httpd_register_uri_handler(server, &datalog_uri);
// Login endpoint
httpd_uri_t login = {.uri = "/login", .method = HTTP_POST, .handler = login_handler, .user_ctx = NULL};
httpd_register_uri_handler(server, &login);
register_wifi_endpoint(server);
register_ws_endpoint(server);

View File

@@ -5,9 +5,9 @@
#ifndef ODROID_REMOTE_HTTP_WEBSERVER_H
#define ODROID_REMOTE_HTTP_WEBSERVER_H
#include "esp_http_server.h"
#include <stddef.h>
#include <stdint.h>
#include "esp_http_server.h"
void register_wifi_endpoint(httpd_handle_t server);
void register_ws_endpoint(httpd_handle_t server);

View File

@@ -2,10 +2,12 @@
// Created by shinys on 25. 8. 18..
//
#include "auth.h"
#include "driver/uart.h"
#include "esp_err.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "nconfig.h"
#include "pb.h"
@@ -204,6 +206,57 @@ static esp_err_t ws_handler(httpd_req_t* req)
{
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");
return ESP_OK;
}

View File

@@ -8,7 +8,33 @@
</head>
<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">
<div class="order-md-1" style="flex: 1;">
<div class="d-flex align-items-center">
@@ -37,6 +63,9 @@
data-bs-target="#settingsModal">
<i class="bi bi-gear"></i>
</button>
<button class="btn btn-outline-secondary ms-3" id="logout-button">
<i class="bi bi-box-arrow-right"></i>
</button>
</div>
</header>

View File

@@ -4,15 +4,63 @@
* 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.
* @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.
*/
export async function fetchWifiScan() {
const response = await fetch('/api/wifi/scan');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
const response = await fetch('/api/wifi/scan', {
headers: getAuthHeaders(),
});
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.
*/
export async function postWifiConnect(ssid, password) {
const response = await fetch('/api/setting', { // Updated URL
const response = await fetch('/api/setting', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({ssid, password}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || `Connection failed with status: ${response.status}`);
}
return await response.json();
return await handleResponse(response).then(res => res.json());
}
/**
@@ -42,16 +89,15 @@ export async function postWifiConnect(ssid, password) {
* @throws {Error} Throws an error if the request fails.
*/
export async function postNetworkSettings(payload) {
const response = await fetch('/api/setting', { // Updated URL
const response = await fetch('/api/setting', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || `Failed to apply settings with status: ${response.status}`);
}
return response;
return await handleResponse(response);
}
/**
@@ -63,14 +109,13 @@ export async function postNetworkSettings(payload) {
export async function postBaudRateSetting(baudrate) {
const response = await fetch('/api/setting', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({baudrate}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || `Failed to apply baudrate with status: ${response.status}`);
}
return response;
return await handleResponse(response);
}
/**
@@ -79,9 +124,10 @@ export async function postBaudRateSetting(baudrate) {
* @throws {Error} Throws an error if the network request fails.
*/
export async function fetchSettings() {
const response = await fetch('/api/setting'); // Updated URL
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
const response = await fetch('/api/setting', {
headers: getAuthHeaders(),
});
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.
*/
export async function fetchControlStatus() {
const response = await fetch('/api/control');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
const response = await fetch('/api/control', {
headers: getAuthHeaders(),
});
return await handleResponse(response).then(res => res.json());
}
/**
@@ -104,11 +151,13 @@ export async function fetchControlStatus() {
export async function postControlCommand(command) {
const response = await fetch('/api/control', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(command)
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response;
return await handleResponse(response);
}
/**
@@ -117,7 +166,8 @@ export async function postControlCommand(command) {
* @throws {Error} Throws an error if the network request fails.
*/
export async function fetchVersion() {
const response = await fetch('/api/version');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
const response = await fetch('/api/version', {
headers: getAuthHeaders(),
});
return await handleResponse(response).then(res => res.json());
}

View File

@@ -10,6 +10,7 @@ import * as api from './api.js';
import * as ui from './ui.js';
import {clearTerminal, downloadTerminalOutput, fitTerminal} from './terminal.js';
import {debounce, isMobile} from './utils.js';
import {getAuthHeaders, handleResponse} from './api.js'; // Import auth functions
// A flag to track if charts have been initialized
let chartsInitialized = false;
@@ -28,7 +29,10 @@ function updateSliderValue(slider, span) {
}
function loadCurrentLimitSettings() {
fetch('/api/setting')
fetch('/api/setting', {
headers: getAuthHeaders(), // Add auth headers
})
.then(handleResponse) // Handle response for 401
.then(response => response.json())
.then(data => {
if (data.vin_current_limit !== undefined) {
@@ -58,13 +62,6 @@ export function setupEventListeners() {
}
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 ---
dom.clearButton.addEventListener('click', clearTerminal);
dom.downloadButton.addEventListener('click', downloadTerminalOutput);
@@ -86,8 +83,12 @@ export function setupEventListeners() {
if (dom.rebootButton) {
dom.rebootButton.addEventListener('click', () => {
if (confirm('Are you sure you want to reboot the device?')) {
fetch('/api/reboot', {method: 'POST'})
.then(response => response.ok ? response.json() : Promise.reject('Network response was not ok'))
fetch('/api/reboot', {
method: 'POST',
headers: getAuthHeaders(), // Add auth headers
})
.then(handleResponse) // Handle response for 401
.then(response => response.json())
.then(data => {
console.log('Reboot command sent:', data);
ui.hideSettingsModal();
@@ -115,10 +116,14 @@ export function setupEventListeners() {
fetch('/api/setting', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(), // Add auth headers
},
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 => {
console.log('Current limit settings applied:', data);
})

View File

@@ -31,6 +31,20 @@ import {setupEventListeners} from './events.js';
// --- Globals ---
// 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');
// --- WebSocket Event Handlers ---
function onWsOpen() {
@@ -111,6 +125,80 @@ 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.
}
// --- 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 ---
@@ -131,18 +219,37 @@ function connect() {
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();
setupTerminal();
initializeVersion();
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
applyTheme(savedTheme);
setupEventListeners();
setupEventListeners(); // Attach main app event listeners
logoutButton.addEventListener('click', handleLogout); // Attach logout listener
connect();
}
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 ---
document.addEventListener('DOMContentLoaded', initialize);

View File

@@ -114,6 +114,10 @@ footer a {
/* Mobile Optimizations */
@media (max-width: 767.98px) {
#login-container {
height: 100%;
}
.main-header {
flex-direction: column;
}

View File

@@ -9,7 +9,7 @@
export let websocket;
// 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`;
/**
* Initializes the WebSocket connection and sets up event handlers.
@@ -19,6 +19,13 @@ const gateway = `ws://${window.location.host}/ws`;
* @param {function} callbacks.onMessage - Called when a message is received from the server.
*/
export function initWebSocket({onOpen, onClose, onMessage}) {
const token = localStorage.getItem('authToken');
let gateway = baseGateway;
if (token) {
gateway = `${baseGateway}?token=${token}`;
}
console.log(`Trying to open a WebSocket connection to ${gateway}...`);
websocket = new WebSocket(gateway);
// Set binary type to arraybuffer to handle raw binary data from the UART.