static int can_socket = -1;
static struct sockaddr_can addr;
-static struct ifreq ifr;
+
static bms_info_t g_bms;
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) {
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;
}
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);
// 解析总电流 (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,
}
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);
// 第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,
}
void user_bms_parse_frame3(const uint8_t *data) {
+
+ pthread_mutex_lock( &g_bms.mutex );
+
// 解析电池状态
g_bms.data.battery_status = le16_to_host(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);
// 解析单体最高电池电压编号
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);
// 解析单体最高电池温度编号
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) {
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 );
// 根据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);
}
}
}
+
+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秒超时)
--- /dev/null
+<!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>