web get bms info
authorkyz <kyz@kyz.pub>
Thu, 30 Oct 2025 09:15:19 +0000 (17:15 +0800)
committerkyz <kyz@kyz.pub>
Thu, 30 Oct 2025 09:15:19 +0000 (17:15 +0800)
src/main.c
src/rtu_master.c
src/user_bms.c
src/user_bms.h
src/user_pcs.h
src/user_web_data.c
src/user_web_server.c
test-bms.html [new file with mode: 0644]

index fb96cee9e90e9e62ad1f650628749b8b0236416d..4c7ce48a6db677f537b37316df9fae3e077c7dc9 100644 (file)
@@ -5,6 +5,8 @@
 int bms_start(void);
 int pcs_start(void);
 int webserver_start(void);
+char *bms_data_to_str(bms_data_t *bms_data);
+extern bool user_bms_send_heartbeat(uint16_t heartbeat_value);
 
 board_info_t g_board_info;
 
@@ -12,6 +14,10 @@ board_info_t g_board_info;
 int main(void)
 {
    pcs_data_t pcs_data;
+   bms_data_t bms_data;
+   uint16_t heartbeat_value = 0x1234;
+   uint32_t n = 0;
+
    user_log_init();
 
    printf("---PCS DTU, Version:1.0\n");
@@ -41,7 +47,21 @@ int main(void)
         user_pcs_data_get( &pcs_data );
         if( memcmp( &g_board_info.pcs_data, &pcs_data, sizeof( pcs_data ) ) != 0 ){
             memcpy( &g_board_info.pcs_data, &pcs_data, sizeof( pcs_data ) );
+            printf( "pcs data chnged --: \n" );
+            //todo
+        }
+        user_bms_data_get( &bms_data );
+        if( memcmp( &g_board_info.bms_data, &bms_data, 32 ) != 0 ){
+            printf( "bms data chnged \n" );
+            printf( "\n\n bms data: %s \n\n", bms_data_to_str( &bms_data ) );
+            memcpy( &g_board_info.bms_data, &bms_data, sizeof( bms_data ) );
+        }
+        if( n++ > 10 ){
+            n = 0;
+            user_bms_send_heartbeat( heartbeat_value++ );
         }
+
+
     }
 
     return 0;
index c7c2d217f91a891fe740ff490362493290cd0e68..9e2b73bdfebc62f3ce201b361440db7d4963426b 100644 (file)
@@ -28,8 +28,9 @@ typedef struct{
 
 
 static mb_t s_mb[MB_RTU_BUS_NRS] = {
-    {NULL, "RTU_BUS_1", MB_RTU_PORT_PATH_1, "/sys/class/gpio/gpio0/value",  -1 },
-    {NULL, "RTU_BUS_2", MB_RTU_PORT_PATH_2, "/sys/class/gpio/gpio14/value", -1 },
+//    {NULL, "RTU_BUS_1", MB_RTU_PORT_PATH_1, "/sys/class/gpio/gpio0/value",  -1 },
+    {NULL, "RTU_BUS_1", MB_RTU_PORT_PATH_1, NULL, -1 },
+    {NULL, "RTU_BUS_2", MB_RTU_PORT_PATH_2, NULL, -1 },
     {NULL, "RTU_BUS_3", MB_RTU_PORT_PATH_3, NULL, -1 },
     {NULL, "RTU_BUS_4", MB_RTU_PORT_PATH_4, NULL, -1 },
     {NULL, "RTU_BUS_5", MB_RTU_PORT_PATH_5, NULL, -1 },
@@ -41,21 +42,19 @@ static void rtu_switch_direction(modbus_t *ctx, int direction)
         if (direction) { // 设置为发送模式
             //system( "echo 1 > /sys/class/gpio/gpio0/value" );
             if( s_mb[MB_RTU_BUS_1].dir_gpio_fd >= 0 ){
-                write( s_mb[MB_RTU_BUS_1].dir_gpio_fd, "1", 1 );
+                //write( s_mb[MB_RTU_BUS_1].dir_gpio_fd, "1", 1 );
             }
         }else{
             if( s_mb[MB_RTU_BUS_1].dir_gpio_fd >= 0 ){
-                write( s_mb[MB_RTU_BUS_1].dir_gpio_fd, "0", 1 );
+                //write( s_mb[MB_RTU_BUS_1].dir_gpio_fd, "0", 1 );
             }
         }
     }else if( ctx == s_mb[MB_RTU_BUS_2].ctx ){
         if (direction) { // 设置为发送模式
             if( s_mb[MB_RTU_BUS_2].dir_gpio_fd >= 0 ){
-                write( s_mb[MB_RTU_BUS_2].dir_gpio_fd, "1", 1 );
             }
         }else{
             if( s_mb[MB_RTU_BUS_2].dir_gpio_fd >= 0 ){
-                write( s_mb[MB_RTU_BUS_2].dir_gpio_fd, "0", 1 );
             }
         }
     }
index d435c597d6d28d40ea6fd741b037dd917b0f5b1a..10b525508d8e87f777f2791e8465070394061ad0 100644 (file)
@@ -14,7 +14,7 @@
 
 static int can_socket = -1;
 static struct sockaddr_can addr;
-static struct ifreq ifr;
+
 
 static bms_info_t g_bms;
 
@@ -28,9 +28,36 @@ static int16_t le16s_to_host(const uint8_t *data) {
     return (int16_t)(data[0] | (data[1] << 8));
 }
 
-bool user_bms_init(const char *can_interface) {
+/* 获取BMS设备信息 */
+int user_bms_data_get(bms_data_t *bms_data)
+{
+    if( !bms_data ){
+        return -1;
+    }
+    pthread_mutex_lock(&g_bms.mutex);
+    memcpy( bms_data, &g_bms.data, sizeof( bms_data_t ));
+    pthread_mutex_unlock(&g_bms.mutex);
+    return 0;
+}
+
+bool user_bms_init(const char *can_interface)
+{
+    struct ifreq ifr;
+    int ret;
+
+    //check can0 interface
+    if( strcmp( can_interface, "can0" ) != 0 ){
+        printf( "user_bms_init: can interface must be can0\n" );
+        return false;
+    }
+    ret = system( "ip link set can0 down" );
+    ret = system( "ip link set can0 type can bitrate 250000 dbitrate 250000 fd on" );
+    ret = system( "ip link set can0 up" );
+    printf( "system set can ret:%d\n", ret );
+
     // 初始化BMS数据
     memset(&g_bms, 0, sizeof(g_bms));
+    pthread_mutex_init(&g_bms.mutex, NULL);
 
     // 创建CAN socket
     if ((can_socket = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
@@ -61,7 +88,8 @@ bool user_bms_init(const char *can_interface) {
     return true;
 }
 
-bool user_bms_send_heartbeat(uint16_t heartbeat_value) {
+bool user_bms_send_heartbeat(uint16_t heartbeat_value)
+{
     if (can_socket < 0) return false;
 
     struct can_frame frame;
@@ -88,6 +116,9 @@ bool user_bms_send_heartbeat(uint16_t heartbeat_value) {
 }
 
 void user_bms_parse_frame1(const uint8_t *data) {
+
+    pthread_mutex_lock( &g_bms.mutex );
+
     // 解析最大允许充电电流 (0.1A)
     g_bms.data.max_charge_current_p1a = le16_to_host(data);
 
@@ -99,6 +130,9 @@ void user_bms_parse_frame1(const uint8_t *data) {
 
     // 解析总电流 (0.1A)
     g_bms.data.total_current_p1a = le16s_to_host(data + 6);
+
+    pthread_mutex_unlock( &g_bms.mutex );
+
     printf( "can recv frame 1: max_charge_current_p1a:%d, max_discharge_current_p1a:%d, total_voltage_p1v:%d, total_current_p1a:%d\n",
         g_bms.data.max_charge_current_p1a,
         g_bms.data.max_discharge_current_p1a,
@@ -107,6 +141,9 @@ void user_bms_parse_frame1(const uint8_t *data) {
 }
 
 void user_bms_parse_frame2(const uint8_t *data) {
+
+    pthread_mutex_lock( &g_bms.mutex );
+
     // 解析总SOC (0.1%)
     g_bms.data.total_soc_p1 = le16_to_host(data);
 
@@ -118,6 +155,9 @@ void user_bms_parse_frame2(const uint8_t *data) {
 
     // 第7-8字节为预留,不处理
     g_bms.data.reserve_2 = le16_to_host(data + 6);
+
+    pthread_mutex_unlock( &g_bms.mutex );
+
     printf( "can recv frame 2: total_soc_p1:%d, total_soh_p1:%d, max_charge_voltage_p1v:%d, reserve_2:%d\n",
         g_bms.data.total_soc_p1,
         g_bms.data.total_soh_p1,
@@ -126,6 +166,9 @@ void user_bms_parse_frame2(const uint8_t *data) {
 }
 
 void user_bms_parse_frame3(const uint8_t *data) {
+
+    pthread_mutex_lock( &g_bms.mutex );
+
     // 解析电池状态
     g_bms.data.battery_status = le16_to_host(data);
 
@@ -137,9 +180,19 @@ void user_bms_parse_frame3(const uint8_t *data) {
 
     // 解析严重告警
     g_bms.data.serious_alarm = le16_to_host(data + 6);
+
+    pthread_mutex_unlock( &g_bms.mutex );
+    printf( "can recv frame 3: battery_status:%d, light_alarm:%d, medium_alarm:%d, serious_alarm:%d\n",
+        g_bms.data.battery_status,
+        g_bms.data.light_alarm,
+        g_bms.data.medium_alarm,
+        g_bms.data.serious_alarm );
 }
 
-void user_bms_parse_frame4(const uint8_t *data) {
+void user_bms_parse_frame4(const uint8_t *data)
+{
+    pthread_mutex_lock( &g_bms.mutex );
+
     // 解析单体最低电池电压 (0.001V)
     g_bms.data.min_cell_voltage_p3v = le16_to_host(data);
 
@@ -151,9 +204,20 @@ void user_bms_parse_frame4(const uint8_t *data) {
 
     // 解析单体最高电池电压编号
     g_bms.data.max_cell_num = le16_to_host(data + 6);
+
+    pthread_mutex_unlock( &g_bms.mutex );
+    printf( "can recv frame 4: min_cell_voltage_p3v: %d, min_cell_num:%d, max_cell_voltage_p3v:%d, max_cell_num:%d\n",
+        g_bms.data.min_cell_voltage_p3v,
+        g_bms.data.min_cell_num,
+        g_bms.data.max_cell_voltage_p3v,
+        g_bms.data.max_cell_num );
+
 }
 
-void user_bms_parse_frame5(const uint8_t *data) {
+void user_bms_parse_frame5(const uint8_t *data)
+{
+    pthread_mutex_lock( &g_bms.mutex );
+
     // 解析单体最低电池温度 (0.1℃)
     g_bms.data.min_cell_temp_p1c = le16s_to_host(data);
 
@@ -165,6 +229,13 @@ void user_bms_parse_frame5(const uint8_t *data) {
 
     // 解析单体最高电池温度编号
     g_bms.data.max_temp_num = le16_to_host(data + 6);
+
+    pthread_mutex_unlock( &g_bms.mutex );
+    printf( "can recv frame 5: min_cell_temp_p1c:%d, min_temp_num:%d, max_cell_temp_p1c:%d, max_temp_num:%d \n",
+        g_bms.data.min_cell_temp_p1c,
+        g_bms.data.min_temp_num,
+        g_bms.data.max_cell_temp_p1c,
+        g_bms.data.max_temp_num );
 }
 
 void user_bms_receive_data(void) {
@@ -177,7 +248,7 @@ void user_bms_receive_data(void) {
         perror("read");
         return;
     }
-    printf( "can read msg, size:%d\n", nbytes );
+    printf( "can read msg, size:%ld\n", nbytes );
     if (nbytes != sizeof(struct can_frame)) return;
 
     printf( "read frame: id:%08X, dlc:%d, data:", frame.can_id, frame.can_dlc );
@@ -193,7 +264,6 @@ void user_bms_receive_data(void) {
     // 根据CAN ID解析不同的数据帧
     switch (frame.can_id) {
         case BMS_FRAME1_ID:
-printf( "FRAME1_ID\n" );
             if (frame.can_dlc == 8) {
                 user_bms_parse_frame1(frame.data);
             }
@@ -229,6 +299,57 @@ printf( "FRAME1_ID\n" );
     }
 }
 
+
+char *bms_data_to_str(bms_data_t *bms_data)
+{
+    static char str[1024];
+
+    if (bms_data == NULL) {
+        snprintf(str, sizeof(str), "BMS data: NULL");
+        return str;
+    }
+
+    snprintf(str, sizeof(str),
+        "BMS Data: Status:%d, SOC:%.1f%%, SOH:%.1f%%, "
+        "Voltage:%.1fV, Current:%.1fA, "
+        "ChargeCurrMax:%.1fA, DischCurrMax:%.1fA, "
+        "ChargeVoltMax:%.1fV, "
+        "CellVoltMin:%.3fV(#%d), CellVoltMax:%.3fV(#%d), "
+        "TempMin:%d°C(#%d), TempMax:%d°C(#%d), "
+        "Alarms[L:M:S]:[%d:%d:%d], "
+        "Connected:%s, LastUpdate:%u",
+
+        bms_data->battery_status,
+        (float)bms_data->total_soc_p1 / 10.0,
+        (float)bms_data->total_soh_p1 / 10.0,
+
+        (float)bms_data->total_voltage_p1v / 10.0,
+        (float)bms_data->total_current_p1a / 10.0,
+
+        (float)bms_data->max_charge_current_p1a / 10.0,
+        (float)bms_data->max_discharge_current_p1a / 10.0,
+        (float)bms_data->max_charge_voltage_p1v / 10.0,
+
+        (float)bms_data->min_cell_voltage_p3v / 1000.0,
+        bms_data->min_cell_num,
+        (float)bms_data->max_cell_voltage_p3v / 1000.0,
+        bms_data->max_cell_num,
+
+        bms_data->min_cell_temp_p1c,
+        bms_data->min_temp_num,
+        bms_data->max_cell_temp_p1c,
+        bms_data->max_temp_num,
+
+        bms_data->light_alarm,
+        bms_data->medium_alarm,
+        bms_data->serious_alarm,
+
+        bms_data->is_connected ? "Yes" : "No",
+        bms_data->last_update_time
+    );
+
+    return str;
+}
 const bms_data_t *user_bms_get_data( bms_data_t *data )
 {
 // 检查BMS连接状态 (5秒超时)
index 7a2e16e47a5b4ae37679ed64f9c126f81ed41129..e1281e5627095164286dcfbda242ec2f5ff71ee6 100644 (file)
@@ -3,6 +3,7 @@
 
 #include <stdint.h>
 #include <stdbool.h>
+#include <pthread.h>
 
 // BMS设备地址定义
 #define BMS_ADDR_1         0x01
@@ -59,6 +60,7 @@ typedef struct{
     bms_data_t data;
     int connected;
     int lock; //for w/r data;
+    pthread_mutex_t mutex;
 } bms_info_t;
 
 // 初始化BMS通信模块
@@ -76,4 +78,6 @@ const bms_data_t *user_bms_get_data( bms_data_t *data );
 // 关闭BMS通信模块
 void user_bms_deinit(void);
 
+/* 获取BMS设备信息 */
+int user_bms_data_get(bms_data_t *pcs_data);
 #endif // USER_BMS_H
index 5d062c0a5bef17ec734ce42c36eb3c987312efcf..7f495f1d83d7590d02fe8fc36eecf02b1d24b295 100644 (file)
@@ -3,6 +3,7 @@
 
 #include <stdint.h>
 #include <stdbool.h>
+#include <pthread.h>
 #include "user_mb.h"
 #include "user_log.h"
 
index 3b82ce1c7576b468bab0a57cdc1d913c81beff34..aed6a9a4873c7c812511ad96d9f2a9bc50baeb4b 100644 (file)
@@ -124,6 +124,8 @@ int process_http_post_message( char * url, char *message, size_t len, char **p_r
     cJSON *response_json = NULL;
     cJSON *data_json = NULL;
     pcs_data_t pcs_data;
+    bms_data_t bms_data;
+
 printf( "-------------post msg ------[%s] [%s]----------------------\n", url, message );
     if (!message) {
         return -1;
@@ -341,26 +343,28 @@ printf( "login success!\n" );
                 data_json = cJSON_CreateObject();
                 cJSON_AddItemToObject(response_json, "data", data_json);
 
+                user_bms_data_get( &bms_data );
+
                 // 添加BMS信息字段
-                cJSON_AddNumberToObject(data_json, "max_charge_current_p1a", g_board_info.bms_data.data.max_charge_current_p1a);
-                cJSON_AddNumberToObject(data_json, "max_discharge_current_p1a", g_board_info.bms_data.data.max_discharge_current_p1a);
-                cJSON_AddNumberToObject(data_json, "total_voltage_p1v", g_board_info.bms_data.data.total_voltage_p1v);
-                cJSON_AddNumberToObject(data_json, "total_current_p1a", g_board_info.bms_data.data.total_current_p1a);
-                cJSON_AddNumberToObject(data_json, "total_soc_p1", g_board_info.bms_data.data.total_soc_p1);
-                cJSON_AddNumberToObject(data_json, "total_soh_p1", g_board_info.bms_data.data.total_soh_p1);
-                cJSON_AddNumberToObject(data_json, "max_charge_voltage_p1v", g_board_info.bms_data.data.max_charge_voltage_p1v);
-                cJSON_AddNumberToObject(data_json, "battery_status", g_board_info.bms_data.data.battery_status);
-                cJSON_AddNumberToObject(data_json, "light_alarm", g_board_info.bms_data.data.light_alarm);
-                cJSON_AddNumberToObject(data_json, "medium_alarm", g_board_info.bms_data.data.medium_alarm);
-                cJSON_AddNumberToObject(data_json, "serious_alarm", g_board_info.bms_data.data.serious_alarm);
-                cJSON_AddNumberToObject(data_json, "min_cell_voltage_p3v", g_board_info.bms_data.data.min_cell_voltage_p3v);
-                cJSON_AddNumberToObject(data_json, "min_cell_num", g_board_info.bms_data.data.min_cell_num);
-                cJSON_AddNumberToObject(data_json, "max_cell_voltage_p3v", g_board_info.bms_data.data.max_cell_voltage_p3v);
-                cJSON_AddNumberToObject(data_json, "max_cell_num", g_board_info.bms_data.data.max_cell_num);
-                cJSON_AddNumberToObject(data_json, "min_cell_temp_p1c", g_board_info.bms_data.data.min_cell_temp_p1c);
-                cJSON_AddNumberToObject(data_json, "min_temp_num", g_board_info.bms_data.data.min_temp_num);
-                cJSON_AddNumberToObject(data_json, "max_cell_temp_p1c", g_board_info.bms_data.data.max_cell_temp_p1c);
-                cJSON_AddNumberToObject(data_json, "max_temp_num", g_board_info.bms_data.data.max_temp_num);
+                cJSON_AddNumberToObject(data_json, "max_charge_current_p1a", bms_data.max_charge_current_p1a);
+                cJSON_AddNumberToObject(data_json, "max_discharge_current_p1a", bms_data.max_discharge_current_p1a);
+                cJSON_AddNumberToObject(data_json, "total_voltage_p1v", bms_data.total_voltage_p1v);
+                cJSON_AddNumberToObject(data_json, "total_current_p1a", bms_data.total_current_p1a);
+                cJSON_AddNumberToObject(data_json, "total_soc_p1", bms_data.total_soc_p1);
+                cJSON_AddNumberToObject(data_json, "total_soh_p1", bms_data.total_soh_p1);
+                cJSON_AddNumberToObject(data_json, "max_charge_voltage_p1v", bms_data.max_charge_voltage_p1v);
+                cJSON_AddNumberToObject(data_json, "battery_status", bms_data.battery_status);
+                cJSON_AddNumberToObject(data_json, "light_alarm", bms_data.light_alarm);
+                cJSON_AddNumberToObject(data_json, "medium_alarm", bms_data.medium_alarm);
+                cJSON_AddNumberToObject(data_json, "serious_alarm", bms_data.serious_alarm);
+                cJSON_AddNumberToObject(data_json, "min_cell_voltage_p3v", bms_data.min_cell_voltage_p3v);
+                cJSON_AddNumberToObject(data_json, "min_cell_num", bms_data.min_cell_num);
+                cJSON_AddNumberToObject(data_json, "max_cell_voltage_p3v", bms_data.max_cell_voltage_p3v);
+                cJSON_AddNumberToObject(data_json, "max_cell_num", bms_data.max_cell_num);
+                cJSON_AddNumberToObject(data_json, "min_cell_temp_p1c", bms_data.min_cell_temp_p1c);
+                cJSON_AddNumberToObject(data_json, "min_temp_num", bms_data.min_temp_num);
+                cJSON_AddNumberToObject(data_json, "max_cell_temp_p1c", bms_data.max_cell_temp_p1c);
+                cJSON_AddNumberToObject(data_json, "max_temp_num", bms_data.max_temp_num);
 
             // 处理设置PCS参数的请求
             } else if (strcmp(msg, "set_pcs_parameter") == 0) {
index 6a5229fe20b25a81d8517b1cf77eeaf3cae01686..cf79e771ba1b0e85864f13f74b1192dfe284c177 100644 (file)
@@ -311,10 +311,13 @@ static int callback_minimal_server_echo(struct lws *wsi, enum lws_callback_reaso
                        // 如果尚未认证,尝试进行token认证
                        if (!pss->authenticated) {
                                cJSON *root = cJSON_Parse((const char *)in);
+                               printf( "----------WebSocket message received: %s\n", (const char *)in );
                                if (root) {
                                        cJSON *token_item = cJSON_GetObjectItem(root, "token");
                                        if (token_item && cJSON_IsString(token_item)) {
+                                               printf( "token_item->valuestring: %s\n", token_item->valuestring );
                                                if (validate_token(token_item->valuestring)) {
+                                                       printf( "validate_token success\n" );
                                                        pss->authenticated = 1;
                                                        strncpy(pss->token, token_item->valuestring, sizeof(pss->token) - 1);
 
@@ -345,6 +348,7 @@ static int callback_minimal_server_echo(struct lws *wsi, enum lws_callback_reaso
                                                        }
                                                        cJSON_Delete(auth_response);
                                                } else {
+                                                       printf( "validate_token failed\n" );
                                                        // 返回认证失败响应
                                                        cJSON *auth_response = cJSON_CreateObject();
                                                        cJSON_AddNumberToObject(auth_response, "code", 401);
diff --git a/test-bms.html b/test-bms.html
new file mode 100644 (file)
index 0000000..6f9609e
--- /dev/null
@@ -0,0 +1,1313 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>HTTP & WebSocket 综合测试页面</title>
+    <style>
+        body {
+            font-family: Arial, sans-serif;
+            line-height: 1.6;
+            color: #333;
+            max-width: 1200px;
+            margin: 0 auto;
+            padding: 20px;
+            background-color: #f4f4f4;
+        }
+        .container {
+            background-color: #fff;
+            padding: 20px;
+            border-radius: 8px;
+            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
+        }
+        h1 {
+            color: #2c3e50;
+            border-bottom: 1px solid #eee;
+            padding-bottom: 10px;
+        }
+        h2 {
+            color: #34495e;
+            margin-top: 30px;
+        }
+        .section {
+            margin-bottom: 30px;
+            padding: 15px;
+            background-color: #f9f9f9;
+            border-radius: 5px;
+        }
+        .button-group {
+            margin: 15px 0;
+        }
+        .btn {
+            background-color: #3498db;
+            color: white;
+            border: none;
+            padding: 10px 15px;
+            border-radius: 4px;
+            cursor: pointer;
+            font-size: 14px;
+            margin-right: 10px;
+        }
+        .btn:hover {
+            background-color: #2980b9;
+        }
+        .btn-primary {
+            background-color: #2ecc71;
+        }
+        .btn-primary:hover {
+            background-color: #27ae60;
+        }
+        .btn-danger {
+            background-color: #e74c3c;
+        }
+        .btn-danger:hover {
+            background-color: #c0392b;
+        }
+        /* 添加WebSocket连接状态按钮样式 */
+        .btn-connected {
+            background-color: #27ae60;
+        }
+        .btn-disconnected {
+            background-color: #e74c3c;
+        }
+        .form-group {
+            margin: 10px 0;
+        }
+        label {
+            display: inline-block;
+            width: 100px;
+            font-weight: bold;
+        }
+        input[type="text"], input[type="password"] {
+            padding: 8px;
+            width: 200px;
+            border: 1px solid #ddd;
+            border-radius: 4px;
+        }
+        .response-container {
+            margin-top: 20px;
+        }
+        .response-header {
+            font-weight: bold;
+            margin-bottom: 5px;
+            color: #2c3e50;
+        }
+        .response-box {
+            background-color: #2c3e50;
+            color: #ecf0f1;
+            padding: 15px;
+            border-radius: 4px;
+            max-height: 400px;
+            overflow-y: auto;
+            white-space: pre-wrap;
+            font-family: "Courier New", Courier, monospace;
+        }
+        /* 修复BMS和PCS信息的文本颜色 */
+        #bms-info-response, #pcs-info-response {
+            color: #ecf0f1 !important;
+        }
+        .auth-status {
+            padding: 8px;
+            border-radius: 4px;
+            display: inline-block;
+            margin-bottom: 15px;
+        }
+        .auth-status.logged-in {
+            background-color: #d4edda;
+            color: #155724;
+        }
+        .auth-status.logged-out {
+            background-color: #f8d7da;
+            color: #721c24;
+        }
+        #username-display {
+            margin-left: 10px;
+            color: #3498db;
+            font-weight: bold;
+        }
+        .loading-indicator {
+            display: inline-block;
+            margin-left: 10px;
+            color: #3498db;
+            font-style: italic;
+        }
+        .info-tabs {
+            display: flex;
+            margin-bottom: 15px;
+        }
+        .tab {
+            padding: 8px 15px;
+            cursor: pointer;
+            border: 1px solid #ddd;
+            background-color: #f1f1f1;
+        }
+        .tab.active {
+            background-color: #3498db;
+            color: white;
+            border-color: #3498db;
+        }
+        .tab-content {
+            display: none;
+        }
+        .tab-content.active {
+            display: block;
+        }
+        /* 修复WebSocket消息样式 */
+        .message-sent {
+            color: #3498db;
+        }
+        .message-received {
+            color: #2ecc71;
+        }
+        .message-info {
+            color: #f39c12;
+        }
+        .message-error {
+            color: #e74c3c;
+        }
+    </style>
+</head>
+<body>
+    <div class="container">
+        <h1>HTTP & WebSocket 综合测试页面</h1>
+
+        <!-- 认证区域 -->
+        <div class="section">
+            <h2>用户认证</h2>
+            <div id="auth-status" class="auth-status logged-out">未登录</div>
+            <span id="username-display" style="display: none;"></span>
+
+            <!-- 登录表单 -->
+            <div id="login-form">
+                <div class="form-group">
+                    <label for="username">用户名:</label>
+                    <input type="text" id="username" placeholder="输入用户名">
+                </div>
+                <div class="form-group">
+                    <label for="password">密码:</label>
+                    <input type="password" id="password" placeholder="输入密码">
+                </div>
+                <div class="button-group">
+                    <button id="login-button" class="btn btn-primary">登录</button>
+                    <div id="login-loading" class="loading-indicator" style="display: none;">登录中...</div>
+                </div>
+                <div class="response-container">
+                    <div class="response-header">认证结果</div>
+                    <pre id="auth-response" class="response-box"></pre>
+                </div>
+            </div>
+
+            <!-- 登出区域 (默认隐藏) -->
+            <div id="logout-section" style="display: none;">
+                <p>当前登录用户: <span id="current-username"></span></p>
+                <div class="button-group">
+                    <button id="logout-button" class="btn btn-danger">登出</button>
+                </div>
+            </div>
+        </div>
+
+        <!-- GET请求测试 -->
+        <div class="section">
+            <h2>GET请求测试</h2>
+            <div class="form-group">
+                <label for="get-url">URL:</label>
+                <input type="text" id="get-url" value="http://192.168.1.1/api/version" placeholder="输入GET请求URL">
+            </div>
+            <div class="button-group">
+                <button id="get-request-button" class="btn">发送GET请求</button>
+                <div id="get-loading" class="loading-indicator" style="display: none;">请求中...</div>
+            </div>
+            <div class="response-container">
+                <div class="response-header">响应结果</div>
+                <pre id="get-response" class="response-box"></pre>
+            </div>
+        </div>
+
+        <!-- 获取PCS信息测试 -->
+        <div class="section">
+            <h2>PCS信息测试</h2>
+            <div class="button-group">
+                <button id="get-pcs-info-button" class="btn btn-primary">获取PCS信息</button>
+                <div id="pcs-info-loading" class="loading-indicator" style="display: none;">获取中...</div>
+            </div>
+            <div class="response-container">
+                <div class="response-header">响应结果</div>
+                <pre id="pcs-info-response" class="response-box"></pre>
+            </div>
+        </div>
+
+        <!-- BMS信息测试 -->
+        <div class="section">
+            <h2>BMS信息测试</h2>
+            <div class="button-group">
+                <button id="get-bms-info-button" class="btn btn-primary">获取BMS信息</button>
+                <div id="bms-info-loading" class="loading-indicator" style="display: none;">获取中...</div>
+            </div>
+            <div class="response-container">
+                <div class="response-header">响应结果</div>
+                <pre id="bms-info-response" class="response-box"></pre>
+            </div>
+        </div>
+
+        <!-- WebSocket测试 -->
+        <div class="section">
+            <h2>WebSocket测试</h2>
+            <div class="form-group">
+                <label for="websocket-url">WebSocket URL:</label>
+                <input type="text" id="websocket-url" value="ws://192.168.1.1/ws" placeholder="输入WebSocket URL">
+            </div>
+            <div class="button-group">
+                <button id="connect-websocket-button" class="btn btn-primary btn-disconnected">连接</button>
+                <button id="disconnect-websocket-button" class="btn btn-danger" disabled>断开连接</button>
+                <div id="websocket-loading" class="loading-indicator" style="display: none;">连接中...</div>
+            </div>
+            <div class="form-group">
+                <label for="websocket-message">发送消息:</label>
+                <input type="text" id="websocket-message" value="{\"code\":0,\"msg\":\"ping\"}" placeholder="输入要发送的消息">
+            </div>
+            <div class="button-group">
+                <button id="send-websocket-message-button" class="btn" disabled>发送消息</button>
+            </div>
+            <div class="response-container">
+                <div class="response-header">WebSocket消息记录</div>
+                <div class="info-tabs">
+                    <div class="tab active" data-tab="all">全部消息</div>
+                    <div class="tab" data-tab="sent">发送消息</div>
+                    <div class="tab" data-tab="received">接收消息</div>
+                </div>
+                <div class="tab-content active" id="all-tab-content">
+                    <pre id="websocket-messages" class="response-box"></pre>
+                </div>
+                <div class="tab-content" id="sent-tab-content">
+                    <pre id="websocket-sent-messages" class="response-box"></pre>
+                </div>
+                <div class="tab-content" id="received-tab-content">
+                    <pre id="websocket-received-messages" class="response-box"></pre>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <script>
+        // WebSocket连接对象
+        let webSocket = null;
+        let heartbeatInterval = null;
+
+        // 添加广播消息样式
+        function addBroadcastStyles() {
+            // 样式已经在CSS中定义,这里可以保留为空或移除
+        }
+
+        // 显示响应内容
+        function showResponse(elementId, content) {
+            const element = document.getElementById(elementId);
+            if (element) {
+                element.textContent = content;
+            }
+        }
+
+        // 发送GET请求
+        function sendGetRequest() {
+            const getUrl = document.getElementById("get-url");
+            const getButton = document.getElementById("get-request-button");
+            const getLoading = document.getElementById("get-loading");
+            const getResponse = document.getElementById("get-response");
+
+            // 检查DOM元素是否存在
+            if (!getUrl || !getButton || !getLoading || !getResponse) {
+                console.error("GET请求所需的DOM元素不存在");
+                return;
+            }
+
+            const url = getUrl.value.trim();
+            if (!url) {
+                getResponse.textContent = "请输入有效的URL";
+                return;
+            }
+
+            // 显示加载状态
+            getButton.disabled = true;
+            getLoading.style.display = "inline-block";
+            getResponse.textContent = "正在发送GET请求...";
+
+            try {
+                // 创建 XMLHttpRequest 对象
+                const xhr = new XMLHttpRequest();
+                xhr.open("GET", url, true);
+
+                // 设置请求完成回调
+                xhr.onreadystatechange = function() {
+                    if (xhr.readyState === 4) {
+                        // 隐藏加载状态
+                        getButton.disabled = false;
+                        getLoading.style.display = "none";
+
+                        if (xhr.status === 200) {
+                            try {
+                                // 尝试格式化JSON响应
+                                const responseObj = JSON.parse(xhr.responseText);
+                                const formattedResponse = JSON.stringify(responseObj, null, 2);
+                                getResponse.textContent = formattedResponse;
+                            } catch (e) {
+                                // 如果不是JSON或解析失败,显示原始响应
+                                getResponse.textContent = xhr.responseText;
+                            }
+                        } else {
+                            getResponse.textContent =
+                                "GET请求失败\n" +
+                                "HTTP 状态码: " + xhr.status + "\n" +
+                                "响应文本: " + xhr.responseText;
+                        }
+                    }
+                };
+
+                // 添加错误处理
+                xhr.onerror = function(error) {
+                    console.error("GET请求错误:", error);
+                    getButton.disabled = false;
+                    getLoading.style.display = "none";
+                    getResponse.textContent =
+                        "GET请求发生错误\n" +
+                        (error.message || "未知错误");
+                };
+
+                // 添加超时处理
+                xhr.timeout = 10000; // 10秒超时
+                xhr.ontimeout = function() {
+                    console.error("GET请求超时");
+                    getButton.disabled = false;
+                    getLoading.style.display = "none";
+                    getResponse.textContent = "GET请求超时 (超过10秒)";
+                };
+
+                // 发送请求
+                xhr.send();
+            } catch (e) {
+                console.error("GET请求函数执行异常:", e);
+                getButton.disabled = false;
+                getLoading.style.display = "none";
+                getResponse.textContent =
+                    "GET请求功能执行异常\n" +
+                    "错误信息: " + e.message;
+            }
+        }
+
+        // 获取PCS信息
+        function getPcsInfo() {
+            const getPcsInfoButton = document.getElementById("get-pcs-info-button");
+            const pcsInfoLoading = document.getElementById("pcs-info-loading");
+            const pcsInfoResponse = document.getElementById("pcs-info-response");
+
+// 检查DOM元素是否存在
+            if (!getPcsInfoButton || !pcsInfoLoading || !pcsInfoResponse) {
+                console.error("获取PCS信息所需的DOM元素不存在");
+                return;
+            }
+
+            // 显示加载状态
+            getPcsInfoButton.disabled = true;
+            pcsInfoLoading.style.display = "inline-block";
+            pcsInfoResponse.textContent = "正在获取PCS信息...";
+
+            // 获取token
+            const token = getToken();
+            if (!token) {
+                // 没有token,提示登录
+                setTimeout(() => {
+                    getPcsInfoButton.disabled = false;
+                    pcsInfoLoading.style.display = "none";
+                    pcsInfoResponse.textContent = "请先登录后再尝试获取PCS信息";
+                }, 500);
+                return;
+            }
+
+            try {
+                // 创建 XMLHttpRequest 对象
+                const xhr = new XMLHttpRequest();
+                // 设置PCS信息API URL
+                xhr.open("POST", "/api/pcs_info", true);
+                // 设置内容类型为 JSON
+                xhr.setRequestHeader("Content-Type", "application/json");
+
+                // 设置请求完成回调
+                xhr.onreadystatechange = function() {
+                    if (xhr.readyState === 4) {
+                        // 隐藏加载状态
+                        getPcsInfoButton.disabled = false;
+                        pcsInfoLoading.style.display = "none";
+
+                        if (xhr.status === 200) {
+                            try {
+                                // 尝试解析JSON响应
+                                const responseObj = JSON.parse(xhr.responseText);
+
+                                // 检查认证是否失败
+                                if (responseObj.code === 401 && responseObj.msg === "auth_failed") {
+                                    handleAuthFailure();
+                                    pcsInfoResponse.textContent = "认证失败:" +
+                                        (responseObj.data ? responseObj.data.error : "无效的token");
+                                    return;
+                                }
+
+                                // 格式化响应,便于阅读
+                                const formattedResponse = JSON.stringify(responseObj, null, 2);
+                                pcsInfoResponse.textContent = formattedResponse;
+
+                                // 如果PCS未连接,显示提示信息,但保持文本颜色为浅色
+                                if (responseObj.code === 503 && responseObj.msg === "pcs_disconnected") {
+                                    // 不修改文本颜色,保持默认的浅色
+                                    console.log("PCS未连接");
+                                }
+                            } catch (e) {
+                                // JSON解析错误
+                                console.error("JSON解析错误:", e);
+                                pcsInfoResponse.textContent =
+                                    "获取PCS信息失败:处理响应时发生JSON解析错误\n" +
+                                    "错误信息: " + e.message + "\n" +
+                                    "原始响应: " + xhr.responseText;
+                            }
+                        } else {
+                            // HTTP请求失败
+                            pcsInfoResponse.textContent =
+                                "获取PCS信息请求失败\n" +
+                                "HTTP 状态码: " + xhr.status + "\n" +
+                                "响应文本: " + xhr.responseText;
+                        }
+                    }
+                };
+
+                // 添加错误处理
+                xhr.onerror = function(error) {
+                    console.error("获取PCS信息请求错误:", error);
+                    getPcsInfoButton.disabled = false;
+                    pcsInfoLoading.style.display = "none";
+                    pcsInfoResponse.textContent =
+                        "获取PCS信息请求发生错误\n" +
+                        (error.message || "未知错误");
+                };
+
+                // 添加超时处理
+                xhr.timeout = 10000; // 10秒超时
+                xhr.ontimeout = function() {
+                    console.error("获取PCS信息请求超时");
+                    getPcsInfoButton.disabled = false;
+                    pcsInfoLoading.style.display = "none";
+                    pcsInfoResponse.textContent = "获取PCS信息请求超时 (超过10秒)";
+                };
+
+                // 构建符合pcs.md协议规范的JSON数据
+                const jsonData = JSON.stringify({
+                    "code": 0,
+                    "msg": "get_pcs_info",
+                    "token": token
+                });
+
+                console.log("发送的PCS信息请求数据:", jsonData);
+
+                // 发送请求
+                xhr.send(jsonData);
+            } catch (outerError) {
+                console.error("获取PCS信息函数执行异常:", outerError);
+                getPcsInfoButton.disabled = false;
+                pcsInfoLoading.style.display = "none";
+                pcsInfoResponse.textContent =
+                    "获取PCS信息功能执行异常\n" +
+                    "错误信息: " + outerError.message;
+            }
+        }
+
+        // 获取BMS信息
+        function getBmsInfo() {
+            const getBmsInfoButton = document.getElementById("get-bms-info-button");
+            const bmsInfoLoading = document.getElementById("bms-info-loading");
+            const bmsInfoResponse = document.getElementById("bms-info-response");
+
+            // 检查DOM元素是否存在
+            if (!getBmsInfoButton || !bmsInfoLoading || !bmsInfoResponse) {
+                console.error("获取BMS信息所需的DOM元素不存在");
+                return;
+            }
+
+            // 显示加载状态
+            getBmsInfoButton.disabled = true;
+            bmsInfoLoading.style.display = "inline-block";
+            bmsInfoResponse.textContent = "正在获取BMS信息...";
+
+            // 获取token
+            const token = getToken();
+            if (!token) {
+                // 没有token,提示登录
+                setTimeout(() => {
+                    getBmsInfoButton.disabled = false;
+                    bmsInfoLoading.style.display = "none";
+                    bmsInfoResponse.textContent = "请先登录后再尝试获取BMS信息";
+                }, 500);
+                return;
+            }
+
+            try {
+                // 创建 XMLHttpRequest 对象
+                const xhr = new XMLHttpRequest();
+                // 设置BMS信息API URL
+                xhr.open("POST", "/api/bms_info", true);
+                // 设置内容类型为 JSON
+                xhr.setRequestHeader("Content-Type", "application/json");
+
+                // 设置请求完成回调
+                xhr.onreadystatechange = function() {
+                    if (xhr.readyState === 4) {
+                        // 隐藏加载状态
+                        getBmsInfoButton.disabled = false;
+                        bmsInfoLoading.style.display = "none";
+
+                        if (xhr.status === 200) {
+                            try {
+                                // 尝试解析JSON响应
+                                const responseObj = JSON.parse(xhr.responseText);
+
+                                // 检查认证是否失败
+                                if (responseObj.code === 401 && responseObj.msg === "auth_failed") {
+                                    handleAuthFailure();
+                                    bmsInfoResponse.textContent = "认证失败:" +
+                                        (responseObj.data ? responseObj.data.error : "无效的token");
+                                    return;
+                                }
+
+                                // 格式化响应,便于阅读
+                                const formattedResponse = JSON.stringify(responseObj, null, 2);
+                                bmsInfoResponse.textContent = formattedResponse;
+
+                                // 如果BMS未连接,显示提示信息,但保持文本颜色为浅色
+                                if (responseObj.code === 503 && responseObj.msg === "bms_disconnected") {
+                                    // 不修改文本颜色,保持默认的浅色
+                                    console.log("BMS未连接");
+                                }
+                            } catch (e) {
+                                // JSON解析错误
+                                console.error("JSON解析错误:", e);
+                                bmsInfoResponse.textContent =
+                                    "获取BMS信息失败:处理响应时发生JSON解析错误\n" +
+                                    "错误信息: " + e.message + "\n" +
+                                    "原始响应: " + xhr.responseText;
+                            }
+                        } else {
+                            // HTTP请求失败
+                            bmsInfoResponse.textContent =
+                                "获取BMS信息请求失败\n" +
+                                "HTTP 状态码: " + xhr.status + "\n" +
+                                "响应文本: " + xhr.responseText;
+                        }
+                    }
+                };
+
+                // 添加错误处理
+                xhr.onerror = function(error) {
+                    console.error("获取BMS信息请求错误:", error);
+                    getBmsInfoButton.disabled = false;
+                    bmsInfoLoading.style.display = "none";
+                    bmsInfoResponse.textContent =
+                        "获取BMS信息请求发生错误\n" +
+                        (error.message || "未知错误");
+                };
+
+                // 添加超时处理
+                xhr.timeout = 10000; // 10秒超时
+                xhr.ontimeout = function() {
+                    console.error("获取BMS信息请求超时");
+                    getBmsInfoButton.disabled = false;
+                    bmsInfoLoading.style.display = "none";
+                    bmsInfoResponse.textContent = "获取BMS信息请求超时 (超过10秒)";
+                };
+
+                // 构建符合pcs.md协议规范的JSON数据
+                const jsonData = JSON.stringify({
+                    "code": 0,
+                    "msg": "get_bms_info",
+                    "token": token
+                });
+
+                console.log("发送的BMS信息请求数据:", jsonData);
+
+                // 发送请求
+                xhr.send(jsonData);
+            } catch (outerError) {
+                console.error("获取BMS信息函数执行异常:", outerError);
+                getBmsInfoButton.disabled = false;
+                bmsInfoLoading.style.display = "none";
+                bmsInfoResponse.textContent =
+                    "获取BMS信息功能执行异常\n" +
+                    "错误信息: " + outerError.message;
+            }
+        }
+
+        // 更新WebSocket按钮状态
+        function updateWebSocketButtonState(connected) {
+            const connectButton = document.getElementById("connect-websocket-button");
+            const disconnectButton = document.getElementById("disconnect-websocket-button");
+
+            if (!connectButton || !disconnectButton) return;
+
+            if (connected) {
+                // 连接状态
+                connectButton.disabled = true;
+                connectButton.classList.remove("btn-disconnected");
+                connectButton.classList.add("btn-connected");
+                connectButton.textContent = "已连接";
+
+                disconnectButton.disabled = false;
+            } else {
+                // 断开状态
+                connectButton.disabled = false;
+                connectButton.classList.remove("btn-connected");
+                connectButton.classList.add("btn-disconnected");
+                connectButton.textContent = "连接";
+
+                disconnectButton.disabled = true;
+            }
+        }
+
+        // 连接WebSocket
+        function connectWebSocket() {
+            const websocketUrl = document.getElementById("websocket-url");
+            const connectButton = document.getElementById("connect-websocket-button");
+            const disconnectButton = document.getElementById("disconnect-websocket-button");
+            const sendButton = document.getElementById("send-websocket-message-button");
+            const websocketLoading = document.getElementById("websocket-loading");
+
+            // 检查DOM元素是否存在
+            if (!websocketUrl || !connectButton || !disconnectButton || !sendButton || !websocketLoading) {
+                console.error("WebSocket功能所需的DOM元素不存在");
+                return;
+            }
+
+            const url = websocketUrl.value.trim();
+            if (!url) {
+                addMessage("请输入有效的WebSocket URL", "error");
+                return;
+            }
+
+            // 显示加载状态
+            connectButton.disabled = true;
+            websocketLoading.style.display = "inline-block";
+            addMessage("正在连接WebSocket...", "info");
+
+            try {
+                // 创建WebSocket连接
+                // 修复:添加协议参数,与test-login.html保持一致
+                webSocket = new WebSocket(url, ['ws']);
+
+                // 添加调试日志
+                console.log("WebSocket实例已创建", webSocket);
+
+                // WebSocket连接成功
+                webSocket.onopen = function(event) {
+                    console.log("WebSocket连接成功,readyState:", webSocket.readyState);
+                    websocketLoading.style.display = "none";
+                    sendButton.disabled = false;
+                    addMessage("WebSocket连接成功", "info");
+
+                    // 更新按钮状态
+                    updateWebSocketButtonState(true);
+
+                    // 发送认证消息
+                    const token = getToken();
+                    if (token) {
+                        const authMessage = JSON.stringify({
+                            "code": 0,
+                            "msg": "auth",
+                            "token": token
+                        });
+
+                        // 直接发送,不通过sendWebSocketMessage函数以避免显示认证消息
+                        webSocket.send(authMessage);
+                        console.log("发送WebSocket认证消息:", authMessage);
+                    }
+
+                    // 启动心跳
+                    startHeartbeat();
+                };
+
+                // 接收WebSocket消息
+                webSocket.onmessage = function(event) {
+                    processReceivedMessage(event.data);
+                };
+
+                // WebSocket连接关闭
+                webSocket.onclose = function(event) {
+                    console.log("WebSocket连接关闭", event);
+                    websocketLoading.style.display = "none";
+                    sendButton.disabled = true;
+
+                    // 停止心跳
+                    stopHeartbeat();
+
+                    // 更新按钮状态
+                    updateWebSocketButtonState(false);
+
+                    addMessage("WebSocket连接已关闭", "info");
+                };
+
+                // WebSocket连接错误
+                webSocket.onerror = function(error) {
+                    console.error("WebSocket连接错误", error);
+                    websocketLoading.style.display = "none";
+                    sendButton.disabled = true;
+
+                    // 更新按钮状态
+                    updateWebSocketButtonState(false);
+
+                    addMessage("WebSocket连接错误: " + (error.message || "未知错误"), "error");
+                };
+            } catch (e) {
+                console.error("连接WebSocket异常:", e);
+                websocketLoading.style.display = "none";
+                sendButton.disabled = true;
+
+                // 更新按钮状态
+                updateWebSocketButtonState(false);
+
+                addMessage("连接WebSocket时发生异常: " + e.message, "error");
+            }
+        }
+
+        // 断开WebSocket连接
+        function disconnectWebSocket() {
+            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
+                addMessage("正在断开WebSocket连接...", "info");
+                webSocket.close();
+            }
+        }
+
+        // 发送WebSocket消息
+        function sendWebSocketMessage() {
+            const websocketMessage = document.getElementById("websocket-message");
+
+            // 获取消息内容
+            let message = websocketMessage ? websocketMessage.value.trim() : "";
+
+            if (!message) {
+                addMessage("请输入要发送的消息", "error");
+                return;
+            }
+
+            if (!webSocket || webSocket.readyState !== WebSocket.OPEN) {
+                addMessage("WebSocket未连接", "error");
+                return;
+            }
+
+            try {
+                // 发送消息
+                webSocket.send(message);
+                addMessage("发送: " + message, "sent");
+                console.log("发送WebSocket消息:", message);
+            } catch (e) {
+                console.error("发送WebSocket消息失败:", e);
+                addMessage("发送消息失败: " + e.message, "error");
+            }
+        }
+
+        // 处理接收到的WebSocket消息
+        function processReceivedMessage(message) {
+            addMessage("接收: " + message, "received");
+            console.log("接收WebSocket消息:", message);
+
+            try {
+                // 尝试解析JSON消息
+                const messageObj = JSON.parse(message);
+
+                // 处理认证失败的情况
+                if (messageObj.code === 401 && messageObj.msg === "auth_failed") {
+                    handleAuthFailure();
+                    addMessage("WebSocket认证失败: " + (messageObj.data ? messageObj.data.error : "无效的token"), "error");
+                }
+
+                // 处理心跳响应
+                if (messageObj.msg === "pong") {
+                    // 心跳响应不需要特殊处理
+                }
+            } catch (e) {
+                // 非JSON格式消息,直接显示
+                console.log("接收到非JSON格式的WebSocket消息");
+            }
+        }
+
+        // 添加消息到显示区域
+        function addMessage(message, type = "info") {
+            const timestamp = new Date().toLocaleTimeString();
+            const formattedMessage = `[${timestamp}] ${message}`;
+
+            // 获取所有消息容器
+            const allMessages = document.getElementById("websocket-messages");
+            const sentMessages = document.getElementById("websocket-sent-messages");
+            const receivedMessages = document.getElementById("websocket-received-messages");
+
+            // 添加到所有消息
+            if (allMessages) {
+                // 使用textContent而不是innerHTML来避免HTML注入风险
+                const currentContent = allMessages.textContent;
+                allMessages.textContent = currentContent + (currentContent ? "\n" : "") + formattedMessage;
+                allMessages.scrollTop = allMessages.scrollHeight;
+            }
+
+            // 根据类型添加到对应分类
+            if (type === "sent" && sentMessages) {
+                const currentContent = sentMessages.textContent;
+                sentMessages.textContent = currentContent + (currentContent ? "\n" : "") + formattedMessage;
+                sentMessages.scrollTop = sentMessages.scrollHeight;
+            } else if (type === "received" && receivedMessages) {
+                const currentContent = receivedMessages.textContent;
+                receivedMessages.textContent = currentContent + (currentContent ? "\n" : "") + formattedMessage;
+                receivedMessages.scrollTop = receivedMessages.scrollHeight;
+            }
+        }
+
+        // HTML转义函数(保留但未使用,因为现在使用textContent)
+        function escapeHtml(text) {
+            const div = document.createElement('div');
+            div.textContent = text;
+            return div.innerHTML;
+        }
+
+        // 启动心跳
+        function startHeartbeat() {
+            // 每30秒发送一次心跳
+            heartbeatInterval = setInterval(function() {
+                if (webSocket && webSocket.readyState === WebSocket.OPEN) {
+                    const heartbeatMessage = JSON.stringify({"code": 0, "msg": "ping"});
+                    webSocket.send(heartbeatMessage);
+                    console.log("发送心跳包");
+                }
+            }, 30000);
+        }
+
+        // 停止心跳
+        function stopHeartbeat() {
+            if (heartbeatInterval) {
+                clearInterval(heartbeatInterval);
+                heartbeatInterval = null;
+            }
+        }
+
+        // 用户登录
+        function userLogin() {
+            const usernameInput = document.getElementById("username");
+            const passwordInput = document.getElementById("password");
+            const loginButton = document.getElementById("login-button");
+            const loginLoading = document.getElementById("login-loading");
+            const authResponseElement = document.getElementById("auth-response");
+
+            // 检查DOM元素是否存在
+            if (!usernameInput || !passwordInput || !loginButton || !loginLoading || !authResponseElement) {
+                console.error("登录功能所需的DOM元素不存在");
+                return;
+            }
+
+            const username = usernameInput.value.trim();
+            const password = passwordInput.value.trim();
+
+            if (!username || !password) {
+                authResponseElement.textContent = "请输入用户名和密码";
+                return;
+            }
+
+            // 显示加载状态
+            loginButton.disabled = true;
+            loginLoading.style.display = "inline-block";
+            authResponseElement.textContent = "登录中...";
+
+            try {
+                // 创建 XMLHttpRequest 对象
+                const xhr = new XMLHttpRequest();
+                // 设置登录API URL
+                xhr.open("POST", "/api/login", true);
+                // 设置内容类型为 JSON
+                xhr.setRequestHeader("Content-Type", "application/json");
+
+                // 设置请求完成回调
+                xhr.onreadystatechange = function() {
+                    if (xhr.readyState === 4) {
+                        try {
+                            // 隐藏加载状态
+                            loginButton.disabled = false;
+                            loginLoading.style.display = "none";
+
+                            if (xhr.status === 200) {
+                                try {
+                                    // 尝试解析JSON响应
+                                    const responseObj = JSON.parse(xhr.responseText);
+
+                                    // 检查登录是否成功
+                                    if (responseObj.code === 0 && responseObj.msg === "login_success" && responseObj.data && responseObj.data.token) {
+                                        // 保存token和用户名
+                                        saveToken(responseObj.data.token);
+                                        saveUsername(username);
+
+                                        // 更新UI状态
+                                        updateAuthUI();
+
+                                        // 显示登录成功消息
+                                        const formattedResponse = "登录成功!\n\n" +
+                                            "Token: " + responseObj.data.token;
+                                        authResponseElement.textContent = formattedResponse;
+                                    } else {
+                                        authResponseElement.textContent = "登录失败:" +
+                                            (responseObj ? (responseObj.msg || "未知错误") : "无效的响应对象");
+                                    }
+                                } catch (e) {
+                                    // 详细打印错误信息
+                                    console.error("JSON解析错误:", e.message);
+                                    console.error("错误堆栈:", e.stack);
+                                    // 如果解析失败,显示原始响应和错误信息
+                                    authResponseElement.textContent =
+                                        "登录失败:处理响应时发生错误\n" +
+                                        "错误信息: " + e.message + "\n" +
+                                        "原始响应: " + xhr.responseText;
+                                }
+                            } else {
+                                authResponseElement.textContent =
+                                    "登录请求失败\n" +
+                                    "HTTP 状态码: " + xhr.status + "\n" +
+                                    "响应文本: " + xhr.responseText;
+                            }
+                        } catch (innerError) {
+                            console.error("处理响应时发生异常:", innerError);
+                            loginButton.disabled = false;
+                            loginLoading.style.display = "none";
+                            authResponseElement.textContent =
+                                "登录过程中发生异常\n" +
+                                "错误信息: " + innerError.message;
+                        }
+                    }
+                };
+
+                // 添加错误处理
+                xhr.onerror = function(error) {
+                    console.error("登录请求错误:", error);
+                    loginButton.disabled = false;
+                    loginLoading.style.display = "none";
+                    authResponseElement.textContent =
+                        "登录请求发生错误\n" +
+                        (error.message || "未知错误");
+                };
+
+                // 添加超时处理
+                xhr.timeout = 10000; // 10秒超时
+                xhr.ontimeout = function() {
+                    console.error("登录请求超时");
+                    loginButton.disabled = false;
+                    loginLoading.style.display = "none";
+                    authResponseElement.textContent = "登录请求超时 (超过10秒)";
+                };
+
+                // 构建符合pcs.md协议规范的JSON数据
+                const jsonData = JSON.stringify({
+                    "code": 0,
+                    "msg": "login",
+                    "data":{
+                        "username": username,
+                        "password": password
+                    }
+                });
+
+                console.log("发送的登录数据:", jsonData);
+
+                // 发送请求
+                xhr.send(jsonData);
+            } catch (outerError) {
+                console.error("登录函数执行异常:", outerError);
+                loginButton.disabled = false;
+                loginLoading.style.display = "none";
+                authResponseElement.textContent =
+                    "登录功能执行异常\n" +
+                    "错误信息: " + outerError.message;
+            }
+        }
+
+        // 登出功能 - 按照pcs.md中的协议规范
+        function userLogout() {
+            const logoutButton = document.getElementById("logout-button");
+            const authResponseElement = document.getElementById("auth-response");
+
+            // 显示加载状态
+            logoutButton.disabled = true;
+            if (authResponseElement) {
+                authResponseElement.textContent = "登出中...";
+            }
+
+            // 获取token
+            const token = getToken();
+            if (!token) {
+                // 没有token,直接更新UI
+                clearAuthData();
+                updateAuthUI();
+                if (authResponseElement) {
+                    authResponseElement.textContent = "您尚未登录";
+                }
+                logoutButton.disabled = false;
+                return;
+            }
+
+            // 创建 XMLHttpRequest 对象
+            const xhr = new XMLHttpRequest();
+            // 设置登出API URL
+            xhr.open("POST", "/api/logout", true);
+            // 设置内容类型为 JSON
+            xhr.setRequestHeader("Content-Type", "application/json");
+
+            // 设置请求完成回调
+            xhr.onreadystatechange = function() {
+                // 无论成功与否,都清除本地token并更新UI
+                clearAuthData();
+                updateAuthUI();
+                logoutButton.disabled = false;
+
+                if (xhr.readyState === 4) {
+                    if (xhr.status === 200) {
+                        try {
+                            // 尝试解析JSON响应
+                            const responseObj = JSON.parse(xhr.responseText);
+
+                            // 检查是否登出成功
+                            if (responseObj.msg === "logout_success") {
+                                showResponse("auth-response", "登出成功!\n\n" + JSON.stringify(responseObj, null, 2));
+                            } else {
+                                showResponse("auth-response", "登出成功,但服务器响应异常\n" + JSON.stringify(responseObj, null, 2));
+                            }
+                        } catch (e) {
+                            // 如果解析失败,显示原始响应
+                            showResponse("auth-response", "登出成功,但服务器返回无效响应\n" + xhr.responseText);
+                        }
+                    } else {
+                        showResponse("auth-response", "登出请求失败,但本地已清除登录状态\nHTTP 状态码: " + xhr.status + "\n响应文本: " + xhr.responseText);
+                    }
+                }
+            };
+
+            // 添加错误处理
+            xhr.onerror = function(error) {
+                console.error("登出请求错误:", error);
+                clearAuthData();
+                updateAuthUI();
+                logoutButton.disabled = false;
+                showResponse("auth-response", "登出请求发生错误,但本地已清除登录状态\n" + (error.message || "未知错误"));
+            };
+
+            // 构建符合pcs.md协议规范的JSON数据
+            const jsonData = JSON.stringify({
+                "msg": "logout",
+                "token": token
+            });
+
+            console.log("发送的登出数据:", jsonData);
+
+            // 发送请求
+            xhr.send(jsonData);
+        }
+
+        // Token管理函数
+        function saveToken(token) {
+            try {
+                localStorage.setItem('pcs_token', token);
+            } catch (e) {
+                console.error("保存token失败:", e);
+            }
+        }
+
+        function getToken() {
+            try {
+                return localStorage.getItem('pcs_token');
+            } catch (e) {
+                console.error("获取token失败:", e);
+                return null;
+            }
+        }
+
+        function saveUsername(username) {
+            try {
+                localStorage.setItem('pcs_username', username);
+            } catch (e) {
+                console.error("保存用户名失败:", e);
+            }
+        }
+
+        function getUsername() {
+            try {
+                return localStorage.getItem('pcs_username');
+            } catch (e) {
+                console.error("获取用户名失败:", e);
+                return null;
+            }
+        }
+
+        function clearAuthData() {
+            try {
+                localStorage.removeItem('pcs_token');
+                localStorage.removeItem('pcs_username');
+            } catch (e) {
+                console.error("清除认证数据失败:", e);
+            }
+        }
+
+        // 更新认证UI状态
+        function updateAuthUI() {
+            const token = getToken();
+            const username = getUsername();
+
+            // 为每个DOM元素添加单独的存在性检查
+            const authStatus = document.getElementById("auth-status");
+            const usernameDisplay = document.getElementById("username-display");
+            const loginForm = document.getElementById("login-form");
+            const logoutSection = document.getElementById("logout-section");
+            const currentUsername = document.getElementById("current-username");
+
+            if (token && username) {
+                // 已登录状态
+                if (authStatus) {
+                    authStatus.className = "auth-status logged-in";
+                    authStatus.textContent = "已登录: ";
+                }
+
+                if (usernameDisplay) {
+                    usernameDisplay.textContent = username;
+                    usernameDisplay.style.display = "inline";
+                }
+
+                if (loginForm) {
+                    loginForm.style.display = "none";
+                }
+
+                if (logoutSection) {
+                    logoutSection.style.display = "block";
+                }
+
+                if (currentUsername) {
+                    currentUsername.textContent = username;
+                }
+            } else {
+                // 未登录状态
+                if (authStatus) {
+                    authStatus.className = "auth-status logged-out";
+                    authStatus.textContent = "未登录";
+                }
+
+                if (usernameDisplay) {
+                    usernameDisplay.textContent = "";
+                    usernameDisplay.style.display = "none";
+                }
+
+                if (loginForm) {
+                    loginForm.style.display = "block";
+                }
+
+                if (logoutSection) {
+                    logoutSection.style.display = "none";
+                }
+            }
+        }
+
+        // 处理认证失败
+        function handleAuthFailure() {
+            clearAuthData();
+            updateAuthUI();
+
+            // 如果WebSocket已连接,断开连接
+            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
+                webSocket.close();
+            }
+        }
+
+        // 切换标签页
+        function switchTab(tabId) {
+            // 隐藏所有标签内容
+            const tabContents = document.querySelectorAll('.tab-content');
+            tabContents.forEach(content => {
+                content.classList.remove('active');
+            });
+
+            // 取消所有标签的激活状态
+            const tabs = document.querySelectorAll('.tab');
+            tabs.forEach(tab => {
+                tab.classList.remove('active');
+            });
+
+            // 显示选中的标签内容
+            const selectedContent = document.getElementById(tabId + '-tab-content');
+            if (selectedContent) {
+                selectedContent.classList.add('active');
+            }
+
+            // 激活选中的标签
+            const selectedTab = document.querySelector(`.tab[data-tab="${tabId}"]`);
+            if (selectedTab) {
+                selectedTab.classList.add('active');
+            }
+        }
+
+        // 页面加载完成后执行
+        document.addEventListener('DOMContentLoaded', function() {
+            console.log('测试页面已加载完成');
+            // 添加广播消息样式
+            addBroadcastStyles();
+            // 检查是否已有登录状态
+            updateAuthUI();
+
+            // 为获取BMS信息按钮添加点击事件
+            const getBmsInfoButton = document.getElementById("get-bms-info-button");
+            if (getBmsInfoButton) {
+                getBmsInfoButton.addEventListener('click', getBmsInfo);
+            }
+
+            // 为发送GET请求按钮添加点击事件
+            const getRequestButton = document.getElementById("get-request-button");
+            if (getRequestButton) {
+                getRequestButton.addEventListener('click', sendGetRequest);
+            }
+
+            // 为获取PCS信息按钮添加点击事件
+            const getPcsInfoButton = document.getElementById("get-pcs-info-button");
+            if (getPcsInfoButton) {
+                getPcsInfoButton.addEventListener('click', getPcsInfo);
+            }
+
+            // 为WebSocket连接按钮添加点击事件
+            const connectWebSocketButton = document.getElementById("connect-websocket-button");
+            if (connectWebSocketButton) {
+                connectWebSocketButton.addEventListener('click', connectWebSocket);
+            }
+
+            // 为WebSocket断开连接按钮添加点击事件
+            const disconnectWebSocketButton = document.getElementById("disconnect-websocket-button");
+            if (disconnectWebSocketButton) {
+                disconnectWebSocketButton.addEventListener('click', disconnectWebSocket);
+            }
+
+            // 为WebSocket发送消息按钮添加点击事件
+            const sendWebSocketMessageButton = document.getElementById("send-websocket-message-button");
+            if (sendWebSocketMessageButton) {
+                sendWebSocketMessageButton.addEventListener('click', sendWebSocketMessage);
+            }
+
+            // 为登录按钮添加点击事件
+            const loginButton = document.getElementById("login-button");
+            if (loginButton) {
+                loginButton.addEventListener('click', userLogin);
+            }
+
+            // 为登出按钮添加点击事件
+            const logoutButton = document.getElementById("logout-button");
+            if (logoutButton) {
+                logoutButton.addEventListener('click', userLogout);
+            }
+
+            // 为标签页添加点击事件
+            const tabs = document.querySelectorAll('.tab');
+            tabs.forEach(tab => {
+                tab.addEventListener('click', function() {
+                    const tabId = this.getAttribute('data-tab');
+                    switchTab(tabId);
+                });
+            });
+        });
+    </script>
+</body>
+</html>