add pcs parameter write test
authorkyz <kyz@kyz.pub>
Mon, 10 Nov 2025 03:04:31 +0000 (11:04 +0800)
committerkyz <kyz@kyz.pub>
Mon, 10 Nov 2025 03:16:40 +0000 (11:16 +0800)
fs_overlay/app/html/test.html
src/user_web_data.c

index 2a6deaf2000f7614df27f8fdbb4a619d999cba4d..cbc84bb65515b7ce94cd2ba3ed32a2cb9329a406 100644 (file)
             </div>
         </div>
 
+        <!-- PCS参数配置测试 -->
+        <div class="section">
+            <h2>PCS参数配置测试</h2>
+<div class="form-group">
+                <label for="pcs-on-off-setting">开关机设置:</label>
+                <input type="text" id="pcs-on-off-setting" value="1" placeholder="0:关, 1:开">
+            </div>
+            <div class="form-group">
+                <label for="pcs-work-mode">工作模式:</label>
+                <input type="text" id="pcs-work-mode" value="1" placeholder="工作模式设置">
+            </div>
+            <div class="form-group">
+                <label for="pcs-target-voltage">目标电压:</label>
+                <input type="text" id="pcs-target-voltage" value="5600" placeholder="单位: 0.1V">
+            </div>
+            <div class="form-group">
+                <label for="pcs-target-current">目标电流:</label>
+                <input type="text" id="pcs-target-current" value="100" placeholder="单位: 0.1A">
+            </div>
+            <div class="form-group">
+                <label for="pcs-target-power">目标功率:</label>
+                <input type="text" id="pcs-target-power" value="800" placeholder="单位: 0.1kW">
+            </div>
+            <div class="button-group">
+                <button id="set-pcs-params-button" class="btn btn-primary">配置PCS参数</button>
+                <div id="pcs-params-loading" class="loading-indicator" style="display: none;">配置中...</div>
+            </div>
+            <div class="response-container">
+                <div class="response-header">配置结果</div>
+                <pre id="pcs-params-response" class="response-box"></pre>
+            </div>
+        </div>
+
         <!-- WebSocket测试 -->
         <div class="section">
             <h2>WebSocket测试</h2>
             <div class="button-group">
                 <button id="send-websocket-message-button" class="btn" disabled>发送消息</button>
             </div>
+            // 在WebSocket消息记录标题旁边添加清除按钮
             <div class="response-container">
-                <div class="response-header">WebSocket消息记录</div>
+                <div class="response-header">
+                    WebSocket消息记录
+                    <button id="clear-websocket-messages-button" class="btn" style="float: right; margin-left: 10px;">清除消息</button>
+                </div>
                 <div class="info-tabs">
                     <div class="tab active" data-tab="all">全部消息</div>
                     <div class="tab" data-tab="sent">发送消息</div>
             });
         });
 
+        // 在WebSocket连接对象定义之前添加此函数
+        // 清除WebSocket消息
+        function clearWebSocketMessages() {
+            const allMessages = document.getElementById("websocket-messages");
+            const sentMessages = document.getElementById("websocket-sent-messages");
+            const receivedMessages = document.getElementById("websocket-received-messages");
+
+            if (allMessages) {
+                allMessages.textContent = "";
+            }
+            if (sentMessages) {
+                sentMessages.textContent = "";
+            }
+            if (receivedMessages) {
+                receivedMessages.textContent = "";
+            }
+
+            addMessage("消息已清除", "info");
+        }
+
         // WebSocket连接对象
         let webSocket = null;
         let heartbeatInterval = null;
             }
         }
 
+        // 配置PCS参数
+        function setPcsParameters() {
+            const setPcsParamsButton = document.getElementById("set-pcs-params-button");
+            const pcsParamsLoading = document.getElementById("pcs-params-loading");
+            const pcsParamsResponse = document.getElementById("pcs-params-response");
+
+            // 检查DOM元素是否存在
+            if (!setPcsParamsButton || !pcsParamsLoading || !pcsParamsResponse) {
+                console.error("配置PCS参数所需的DOM元素不存在");
+                return;
+            }
+
+            // 显示加载状态
+            setPcsParamsButton.disabled = true;
+            pcsParamsLoading.style.display = "inline-block";
+            pcsParamsResponse.textContent = "正在配置PCS参数...";
+
+            // 获取token
+            const token = getToken();
+            if (!token) {
+                // 没有token,提示登录
+                setTimeout(() => {
+                    setPcsParamsButton.disabled = false;
+                    pcsParamsLoading.style.display = "none";
+                    pcsParamsResponse.textContent = "请先登录后再尝试配置PCS参数";
+                }, 500);
+                return;
+            }
+
+            try {
+                // 获取参数值
+                const onOffSetting = parseInt(document.getElementById("pcs-on-off-setting").value);
+                const workMode = parseInt(document.getElementById("pcs-work-mode").value);
+                const targetVoltage = parseInt(document.getElementById("pcs-target-voltage").value);
+                const targetCurrent = parseInt(document.getElementById("pcs-target-current").value);
+                const targetPower = parseInt(document.getElementById("pcs-target-power").value);
+
+                // 验证参数
+                if (isNaN(onOffSetting) || isNaN(workMode) || isNaN(targetVoltage) || isNaN(targetCurrent) || isNaN(targetPower)) {
+                    pcsParamsResponse.textContent = "参数值必须为数字";
+                    setPcsParamsButton.disabled = false;
+                    pcsParamsLoading.style.display = "none";
+                    return;
+                }
+
+                // 创建 XMLHttpRequest 对象
+                const xhr = new XMLHttpRequest();
+                // 设置PCS参数配置API URL
+                xhr.open("POST", "/api/pcs_config", true);
+                // 设置内容类型为 JSON
+                xhr.setRequestHeader("Content-Type", "application/json");
+
+                // 设置请求完成回调
+                xhr.onreadystatechange = function() {
+                    if (xhr.readyState === 4) {
+                        // 隐藏加载状态
+                        setPcsParamsButton.disabled = false;
+                        pcsParamsLoading.style.display = "none";
+
+                        if (xhr.status === 200) {
+                            try {
+                                // 尝试解析JSON响应
+                                const responseObj = JSON.parse(xhr.responseText);
+
+                                // 检查认证是否失败
+                                if (responseObj.code === 401 && responseObj.msg === "auth_failed") {
+                                    handleAuthFailure();
+                                    pcsParamsResponse.textContent = "认证失败:" +
+                                        (responseObj.data ? responseObj.data.error : "无效的token");
+                                    return;
+                                }
+
+                                // 格式化响应,便于阅读
+                                const formattedResponse = JSON.stringify(responseObj, null, 2);
+                                pcsParamsResponse.textContent = formattedResponse;
+
+                                // 如果PCS未连接,显示提示信息
+                                if (responseObj.code === 503 && responseObj.msg === "pcs_disconnected") {
+                                    console.log("PCS未连接");
+                                }
+                            } catch (e) {
+                                // JSON解析错误
+                                console.error("JSON解析错误:", e);
+                                pcsParamsResponse.textContent =
+                                    "配置PCS参数失败:处理响应时发生JSON解析错误\n" +
+                                    "错误信息: " + e.message + "\n" +
+                                    "原始响应: " + xhr.responseText;
+                            }
+                        } else {
+                            // HTTP请求失败
+                            pcsParamsResponse.textContent =
+                                "配置PCS参数请求失败\n" +
+                                "HTTP 状态码: " + xhr.status + "\n" +
+                                "响应文本: " + xhr.responseText;
+                        }
+                    }
+                };
+
+                // 添加错误处理
+                xhr.onerror = function(error) {
+                    console.error("配置PCS参数请求错误:", error);
+                    setPcsParamsButton.disabled = false;
+                    pcsParamsLoading.style.display = "none";
+                    pcsParamsResponse.textContent =
+                        "配置PCS参数请求发生错误\n" +
+                        (error.message || "未知错误");
+                };
+
+                // 添加超时处理
+                xhr.timeout = 10000; // 10秒超时
+                xhr.ontimeout = function() {
+                    console.error("配置PCS参数请求超时");
+                    setPcsParamsButton.disabled = false;
+                    pcsParamsLoading.style.display = "none";
+                    pcsParamsResponse.textContent = "配置PCS参数请求超时 (超过10秒)";
+                };
+
+                // 构建符合pcs.md协议规范的JSON数据
+                const jsonData = JSON.stringify({
+                    "code": 0,
+                    "msg": "pcs_parameter",
+                    "token": token,
+                    "data": {
+                        "on_off_setting": onOffSetting,
+                        "work_mode_setting": workMode,
+                        "target_voltage_p1v": targetVoltage,
+                        "target_current_p1a": targetCurrent,
+                        "target_power_p1kw": targetPower
+                    }
+                });
+
+                console.log("发送的PCS参数配置数据:", jsonData);
+
+                // 发送请求
+                xhr.send(jsonData);
+            } catch (outerError) {
+                console.error("配置PCS参数函数执行异常:", outerError);
+                setPcsParamsButton.disabled = false;
+                pcsParamsLoading.style.display = "none";
+                pcsParamsResponse.textContent =
+                    "配置PCS参数功能执行异常\n" +
+                    "错误信息: " + outerError.message;
+            }
+        }
+
         // 更新WebSocket按钮状态
         function updateWebSocketButtonState(connected) {
             const connectButton = document.getElementById("connect-websocket-button");
                                     const responseObj = JSON.parse(xhr.responseText);
 
                                     // 检查登录是否成功
-                                    if (responseObj.code === 0 && responseObj.msg === "login_success" && responseObj.data && responseObj.data.token) {
+                                    if (responseObj.code === 200 && responseObj.msg === "login_success" && responseObj.data && responseObj.data.token) {
                                         // 保存token和用户名
                                         saveToken(responseObj.data.token);
                                         saveUsername(username);
                                     "HTTP 状态码: " + xhr.status + "\n" +
                                     "响应文本: " + xhr.responseText;
                             }
+                        // 完全替换错误的代码部分(大约在第1220-1254行)
                         } catch (innerError) {
-                            console.error("处理响应时发生异常:", innerError);
-                            loginButton.disabled = false;
-                            loginLoading.style.display = "none";
-                            authResponseElement.textContent =
-                                "登录过程中发生异常\n" +
-                                "错误信息: " + innerError.message;
+                        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 =
+                        }
+                        };
+
+                        // 添加错误处理
+                        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
-                    }
-                });
+                        // 添加超时处理
+                        xhr.timeout = 10000; // 10秒超时
+                        xhr.ontimeout = function() {
+                            console.error("登录请求超时");
+                            loginButton.disabled = false;
+                            loginLoading.style.display = "none";
+                            authResponseElement.textContent = "登录请求超时 (超过10秒)";
+                        };
 
-                console.log("发送的登录数据:", jsonData);
+                        // 构建符合pcs.md协议规范的JSON数据
+                        const jsonData = JSON.stringify({
+                            "code": 0,
+                            "msg": "login",
+                            "data":{
+                                "username": username,
+                                "password": password
+                            }
+                        });
 
-                // 发送请求
-                xhr.send(jsonData);
-            } catch (outerError) {
-                console.error("登录函数执行异常:", outerError);
-                loginButton.disabled = false;
-                loginLoading.style.display = "none";
-                authResponseElement.textContent =
-                    "登录功能执行异常\n" +
-                    "错误信息: " + outerError.message;
-            }
-        }
+                        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");
+                // 登出功能 - 按照pcs.md中的协议规范
+                function userLogout() {
+                    const logoutButton = document.getElementById("logout-button");
+                    const authResponseElement = document.getElementById("auth-response");
 
-            // 显示加载状态
-            logoutButton.disabled = true;
-            if (authResponseElement) {
-                authResponseElement.textContent = "登出中...";
-            }
+                    // 显示加载状态
+                    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;
-            }
+                    // 获取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);
+                    // 创建 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));
+                                    // 检查是否登出成功
+                                    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", "登出成功,但服务器响应异常\n" + JSON.stringify(responseObj, null, 2));
+                                showResponse("auth-response", "登出请求失败,但本地已清除登录状态\nHTTP 状态码: " + xhr.status + "\n响应文本: " + xhr.responseText);
                             }
-                        } 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);
                 }
-            };
-
-            // 添加错误处理
-            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 = "已登录: ";
+                // Token管理函数
+                function saveToken(token) {
+                    try {
+                        localStorage.setItem('pcs_token', token);
+                    } catch (e) {
+                        console.error("保存token失败:", e);
+                    }
                 }
 
-                if (usernameDisplay) {
-                    usernameDisplay.textContent = username;
-                    usernameDisplay.style.display = "inline";
+                function getToken() {
+                    try {
+                        return localStorage.getItem('pcs_token');
+                    } catch (e) {
+                        console.error("获取token失败:", e);
+                        return null;
+                    }
                 }
 
-                if (loginForm) {
-                    loginForm.style.display = "none";
+                function saveUsername(username) {
+                    try {
+                        localStorage.setItem('pcs_username', username);
+                    } catch (e) {
+                        console.error("保存用户名失败:", e);
+                    }
                 }
 
-                if (logoutSection) {
-                    logoutSection.style.display = "block";
+                function getUsername() {
+                    try {
+                        return localStorage.getItem('pcs_username');
+                    } catch (e) {
+                        console.error("获取用户名失败:", e);
+                        return null;
+                    }
                 }
 
-                if (currentUsername) {
-                    currentUsername.textContent = username;
-                }
-            } else {
-                // 未登录状态
-                if (authStatus) {
-                    authStatus.className = "auth-status logged-out";
-                    authStatus.textContent = "未登录";
+                function clearAuthData() {
+                    try {
+                        localStorage.removeItem('pcs_token');
+                        localStorage.removeItem('pcs_username');
+                    } catch (e) {
+                        console.error("清除认证数据失败:", e);
+                    }
                 }
 
-                if (usernameDisplay) {
-                    usernameDisplay.textContent = "";
-                    usernameDisplay.style.display = "none";
-                }
+                // 更新认证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 (loginForm) {
-                    loginForm.style.display = "block";
-                }
+                        if (usernameDisplay) {
+                            usernameDisplay.textContent = username;
+                            usernameDisplay.style.display = "inline";
+                        }
 
-                if (logoutSection) {
-                    logoutSection.style.display = "none";
-                }
-            }
-        }
+                        if (loginForm) {
+                            loginForm.style.display = "none";
+                        }
 
-        // 处理认证失败
-        function handleAuthFailure() {
-            clearAuthData();
-            updateAuthUI();
+                        if (logoutSection) {
+                            logoutSection.style.display = "block";
+                        }
 
-            // 如果WebSocket已连接,断开连接
-            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
-                webSocket.close();
-            }
-        }
+                        if (currentUsername) {
+                            currentUsername.textContent = username;
+                        }
+                    } else {
+                        // 未登录状态
+                        if (authStatus) {
+                            authStatus.className = "auth-status logged-out";
+                            authStatus.textContent = "未登录";
+                        }
 
-        // 切换标签页
-        function switchTab(tabId) {
-            // 隐藏所有标签内容
-            const tabContents = document.querySelectorAll('.tab-content');
-            tabContents.forEach(content => {
-                content.classList.remove('active');
-            });
+                        if (usernameDisplay) {
+                            usernameDisplay.textContent = "";
+                            usernameDisplay.style.display = "none";
+                        }
 
-            // 取消所有标签的激活状态
-            const tabs = document.querySelectorAll('.tab');
-            tabs.forEach(tab => {
-                tab.classList.remove('active');
-            });
+                        if (loginForm) {
+                            loginForm.style.display = "block";
+                        }
 
-            // 显示选中的标签内容
-            const selectedContent = document.getElementById(tabId + '-tab-content');
-            if (selectedContent) {
-                selectedContent.classList.add('active');
-            }
+                        if (logoutSection) {
+                            logoutSection.style.display = "none";
+                        }
+                    }
+                }
 
-            // 激活选中的标签
-            const selectedTab = document.querySelector(`.tab[data-tab="${tabId}"]`);
-            if (selectedTab) {
-                selectedTab.classList.add('active');
-            }
-        }
+                // 处理认证失败
+                function handleAuthFailure() {
+                    clearAuthData();
+                    updateAuthUI();
 
-        // 页面加载完成后执行
-        document.addEventListener('DOMContentLoaded', function() {
-            console.log('测试页面已加载完成');
-            // 添加广播消息样式
-            addBroadcastStyles();
-            // 检查是否已有登录状态
-            updateAuthUI();
+                    // 如果WebSocket已连接,断开连接
+                    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
+                        webSocket.close();
+                    }
+                }
 
-            // 为获取BMS信息按钮添加点击事件
-            const getBmsInfoButton = document.getElementById("get-bms-info-button");
-            if (getBmsInfoButton) {
-                getBmsInfoButton.addEventListener('click', getBmsInfo);
-            }
+                // 切换标签页
+                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');
+                    }
 
-            // 为发送GET请求按钮添加点击事件
-            const getRequestButton = document.getElementById("get-request-button");
-            if (getRequestButton) {
-                getRequestButton.addEventListener('click', sendGetRequest);
-            }
+                    // 激活选中的标签
+                    const selectedTab = document.querySelector(`.tab[data-tab="${tabId}"]`);
+                    if (selectedTab) {
+                        selectedTab.classList.add('active');
+                    }
+                }
 
-            // 为获取PCS信息按钮添加点击事件
-            const getPcsInfoButton = document.getElementById("get-pcs-info-button");
-            if (getPcsInfoButton) {
-                getPcsInfoButton.addEventListener('click', getPcsInfo);
-            }
+                // 页面加载完成后执行
+                document.addEventListener('DOMContentLoaded', function() {
+                    console.log('测试页面已加载完成');
+                    // 添加广播消息样式
+                    addBroadcastStyles();
+                    // 检查是否已有登录状态
+                    updateAuthUI();
+
+                    // 找到页面底部的DOMContentLoaded事件监听器(大约在第1500行附近)
+                    // 在现有按钮事件监听器列表中添加以下代码:
+                    // 为清除WebSocket消息按钮添加点击事件
+                    const clearWebSocketMessagesButton = document.getElementById("clear-websocket-messages-button");
+                    if (clearWebSocketMessagesButton) {
+                        clearWebSocketMessagesButton.addEventListener('click', clearWebSocketMessages);
+                    }
 
-            // 为WebSocket连接按钮添加点击事件
+                    // 为获取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);
                 logoutButton.addEventListener('click', userLogout);
             }
 
+            // 为配置PCS参数按钮添加点击事件
+            const setPcsParamsButton = document.getElementById("set-pcs-params-button");
+            if (setPcsParamsButton) {
+                setPcsParamsButton.addEventListener('click', setPcsParameters);
+            }
+
             // 为标签页添加点击事件
             const tabs = document.querySelectorAll('.tab');
             tabs.forEach(tab => {
index eca73b41318c0161feffd6ff18fa23a500542ba8..b4c59ebd561fc795f63ce9f72b1d9ca08e8b1870 100644 (file)
@@ -86,8 +86,12 @@ typedef struct {
 } user_token_t;
 
 static user_token_t g_user_token = {"", 0, 0};
+// 首先,在默认用户名和密码定义后添加第二个用户的常量
 static const char *DEFAULT_USERNAME = "admin";
 static const char *DEFAULT_PASSWORD = "password123";
+// 添加第二个用户
+static const char *SECOND_USERNAME = "user";
+static const char *SECOND_PASSWORD = "user123";
 static const int TOKEN_EXPIRY_SECONDS = 3600; // token有效期1小时
 
 // 生成token的简单实现(实际项目中应使用更安全的方法)
@@ -188,15 +192,17 @@ printf( "-------------post msg ------[%s] [%s]----------------------\n", url, me
                 data_json = cJSON_CreateObject();
                 cJSON_AddItemToObject(response_json, "data", data_json);
                 cJSON_AddStringToObject(data_json, "error", "Missing or invalid username/password");
-            } else if (strcmp(username_item->valuestring, DEFAULT_USERNAME) == 0 &&
-                       strcmp(password_item->valuestring, DEFAULT_PASSWORD) == 0) {
+            } else if ((strcmp(username_item->valuestring, DEFAULT_USERNAME) == 0 &&
+                       strcmp(password_item->valuestring, DEFAULT_PASSWORD) == 0) ||
+                      (strcmp(username_item->valuestring, SECOND_USERNAME) == 0 &&
+                       strcmp(password_item->valuestring, SECOND_PASSWORD) == 0)) {
                 // 登录成功,生成token
 printf( "login success!\n" );
                 generate_token(g_user_token.token, sizeof(g_user_token.token));
                 g_user_token.expiry_time = time(NULL) + TOKEN_EXPIRY_SECONDS;
                 g_user_token.is_valid = 1;
 
-                cJSON_AddNumberToObject(response_json, "code", 0);
+                cJSON_AddNumberToObject(response_json, "code", 200);
                 cJSON_AddStringToObject(response_json, "msg", "login_success");
                 data_json = cJSON_CreateObject();
                 cJSON_AddItemToObject(response_json, "data", data_json);
@@ -222,7 +228,7 @@ printf( "login success!\n" );
         } else if (validate_token(token_item->valuestring)) {
             // 登出成功,使token失效
             g_user_token.is_valid = 0;
-            cJSON_AddNumberToObject(response_json, "code", 0);
+            cJSON_AddNumberToObject(response_json, "code", 200);
             cJSON_AddStringToObject(response_json, "msg", "logout_success");
         } else {
             cJSON_AddNumberToObject(response_json, "code", 401);
@@ -255,7 +261,7 @@ printf( "login success!\n" );
                     cJSON_AddStringToObject(data_json, "error", "PCS device not connected");
                 } else {
                     // PCS设备在线,返回PCS信息
-                    cJSON_AddNumberToObject(response_json, "code", 0);
+                    cJSON_AddNumberToObject(response_json, "code", 200);
                     cJSON_AddStringToObject(response_json, "msg", "get_pcs_info");
 
                     // 创建data字段
@@ -388,7 +394,7 @@ printf( "login success!\n" );
                     cJSON_AddNumberToObject(data_json, "max_temp_num", bms_data.max_temp_num);
                 }
             // 处理设置PCS参数的请求
-            } else if (strcmp(msg, "set_pcs_parameter") == 0) {
+            } else if (strcmp(msg, "pcs_parameter") == 0) {
                 cJSON *data_item = cJSON_GetObjectItem(root, "data");
                 if (!data_item || !cJSON_IsObject(data_item)) {
                     cJSON_AddNumberToObject(response_json, "code", 1);
@@ -621,8 +627,8 @@ printf( "login success!\n" );
                         parameter_set = true;
                     }
                     // 设置响应
-                    cJSON_AddNumberToObject(response_json, "code", 0);
-                    cJSON_AddStringToObject(response_json, "msg", "set_pcs_parameter");
+                    cJSON_AddNumberToObject(response_json, "code", 200);
+                    cJSON_AddStringToObject(response_json, "msg", "pcs_parameter");
                 }
 
             // 未知的请求类型
@@ -1044,4 +1050,4 @@ char * get_user_ws_notify_msg( void )
     cJSON_Delete(response_json);
 
     return response_string;
-}
+}
\ No newline at end of file