add pcs_dtu_d
authorkyz <kyz@kyz.pub>
Fri, 7 Nov 2025 06:30:30 +0000 (14:30 +0800)
committerkyz <kyz@kyz.pub>
Fri, 7 Nov 2025 06:30:30 +0000 (14:30 +0800)
13 files changed:
CMakeLists.txt
fs_overlay/app/html/test.html [new file with mode: 0644]
fs_overlay/app/log4crc [new file with mode: 0644]
fs_overlay/app/pcs_dtu_d [new file with mode: 0755]
fs_overlay/etc/init.d/S99_pcs_dtu [new file with mode: 0755]
fs_overlay/etc/network/interfaces [new file with mode: 0644]
fs_overlay/etc/nginx/nginx.conf
src/main.c
src/user_bms.c
src/user_mb.c
src/user_web_server.c
test-login.html [deleted file]
test.html [deleted file]

index 7ff617b0780f69f1d9461a1504389cea0a03df54..68137bbdd82dcfb5fa7dac7e1bb3d71af9ded71e 100644 (file)
@@ -46,4 +46,7 @@ target_link_libraries(
 )
 
 install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION /app)
-install(FILES ${PROJECT_SOURCE_DIR}/log4crc DESTINATION /app)
+#install(FILES ${PROJECT_SOURCE_DIR}/log4crc DESTINATION /app)
+#install(PROGRAMS ${PROJECT_SOURCE_DIR}/pcs_dtu_d DESTINATION /app)
+#install(FILES ${PROJECT_SOURCE_DIR}/log4crc DESTINATION /app)
+#install(PROGRAMS ${PROJECT_SOURCE_DIR}/S99_pcs_dtu DESTINATION /etc/init.d)
diff --git a/fs_overlay/app/html/test.html b/fs_overlay/app/html/test.html
new file mode 100644 (file)
index 0000000..2a6deaf
--- /dev/null
@@ -0,0 +1,1363 @@
+<!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" value="admin" placeholder="输入用户名">
+                </div>
+                <div class="form-group">
+                    <label for="password">密码:</label>
+                    <input type="password" id="password" value="password123" 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://localhost:8000/api/get" 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://localhost:8000/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>
+
+        <!-- upload测试 -->
+               <p>
+        <div class="section">
+               <form id=myForm name=multipart action="/upload/" method="post" enctype="multipart/form-data">
+                       <h2>文件上传测试</h2>
+                       <input type="file" name="file" id="file" size="20">&nbsp;
+                               <span id=file_info style="font-size:12pt;"></span><br>
+                       <br>
+                       <input type="submit" name="send" value="Submit">
+               </form>
+        </div>
+    </div>
+<div id="responseMessage"></div>
+    <script>
+       document.getElementById('myForm').addEventListener('submit', function(e) {
+              //处理上传文件成功后的响应处理,避免直接跳转到新页面
+
+            e.preventDefault(); // 阻止表单默认提交行为
+
+            const formData = new FormData(this);
+            const responseDiv = document.getElementById('responseMessage');
+
+            // 显示加载状态
+            responseDiv.innerHTML = '提交中...';
+            responseDiv.style.color = 'blue';
+
+            // 使用 Fetch API 发送请求
+            fetch('/upload/', {
+                method: 'POST',
+                body: formData
+            })
+            .then(response => {
+                if (!response.ok) {
+                    throw new Error('网络响应不正常');
+                }
+                return response.json(); // 假设服务器返回 JSON
+            })
+            .then(data => {
+                // 请求成功处理
+                responseDiv.innerHTML = `成功: ${data.message}`;
+                responseDiv.style.color = 'green';
+
+                // 可以在这里添加其他成功后的逻辑
+                console.log('服务器响应:', data);
+            })
+            .catch(error => {
+                // 错误处理
+                responseDiv.innerHTML = `错误: ${error.message}`;
+                responseDiv.style.color = 'red';
+                console.error('请求失败:', error);
+            });
+        });
+
+        // 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>
diff --git a/fs_overlay/app/log4crc b/fs_overlay/app/log4crc
new file mode 100644 (file)
index 0000000..efc4a0f
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!DOCTYPE log4c SYSTEM "">
+
+<log4c>
+
+    <config>
+        <bufsize>0</bufsize>
+        <debug level="0"/>
+        <nocleanup>0</nocleanup>
+    </config>
+
+    <!-- root category ========================================= -->
+    <category name="root" priority="notice"/>
+
+    <!-- 输出到文件console -->
+    <category name="PC" priority="debug" appender = "stdout"/>
+
+    <!-- 输出到文件mylogfilename.x ========================================= -->
+    <!-- category name="app" priority="debug" appender = "stdout"/ -->
+    <category name="XPC" priority="debug" appender = "myrollingappender"/>
+    <appender name="myrollingappender" type="rollingfile" logdir="./" prefix="am-log" layout="dated" rollingpolicy="myrollingpolicy" />
+    <rollingpolicy name="myrollingpolicy" type="sizewin" maxsize="102400" maxnum="3" />
+
+    <!-- default appenders ===================================== -->
+    <appender name="stdout" type="stream" layout="basic"/>
+    <appender name="stderr" type="stream" layout="dated"/>
+    <appender name="syslog" type="syslog" layout="basic"/>
+
+    <!-- default layouts ======================================= -->
+    <layout name="basic" type="basic"/>
+    <layout name="dated" type="dated"/>
+</log4c>
+
diff --git a/fs_overlay/app/pcs_dtu_d b/fs_overlay/app/pcs_dtu_d
new file mode 100755 (executable)
index 0000000..50ff634
--- /dev/null
@@ -0,0 +1,56 @@
+#!/bin/bash
+
+mkdir -p /var/run/pcs_dtu
+
+# 定义守护进程的名称和运行路径
+DAEMON_NAME="pcs_dtu"
+DAEMON_PATH="/app/"
+#DAEMON_PATH="/tmp/" ##debug path
+
+
+# 检查守护进程是否已经在运行
+is_running() {
+    pid=$(cat /var/run/pcs_dtu/pcs_dtu.pid)
+    ps -p $pid > /dev/null
+}
+
+
+# 启动守护进程
+start() {
+    if is_running; then
+        echo "守护进程 $DAEMON_NAME 已经在运行。"
+    fi
+
+    sleep 10
+
+    echo "启动守护进程 $DAEMON_NAME ..."
+    cd "$DAEMON_PATH"
+    ./"$DAEMON_NAME" &
+    echo "守护进程 $DAEMON_NAME 启动成功。"
+}
+
+# 监测守护进程并重新启动
+monitor() {
+    while true; do
+        if ! is_running; then
+            echo "守护进程 $DAEMON_NAME 未在运行,重新启动..."
+            start
+        fi
+
+        ###TODO: add ota check
+
+        sleep 10
+    done
+}
+
+# 检查命令行参数
+case "$1" in 
+    start)
+    start
+       monitor
+        ;;
+    *)
+        echo "error"
+        exit 1
+        ;;
+esac
diff --git a/fs_overlay/etc/init.d/S99_pcs_dtu b/fs_overlay/etc/init.d/S99_pcs_dtu
new file mode 100755 (executable)
index 0000000..d7c2237
--- /dev/null
@@ -0,0 +1,19 @@
+#!/bin/sh
+#
+# Start init
+#
+
+case "$1" in
+  start)
+       /app/pcs_dtu_d start &
+       ;;
+  stop)
+       ;;
+  restart|reload)
+       ;;
+  *)
+       echo "Usage: $0 {start|stop|restart}"
+       exit 1
+esac
+
+exit $?
diff --git a/fs_overlay/etc/network/interfaces b/fs_overlay/etc/network/interfaces
new file mode 100644 (file)
index 0000000..20a7a4d
--- /dev/null
@@ -0,0 +1,15 @@
+# interface file auto-generated by buildroot
+
+auto lo
+iface lo inet loopback
+
+auto eth0
+iface eth0 inet dhcp
+
+auto eth0:1
+iface eth0:1 inet static
+    address 192.168.1.8
+    netmask 255.255.255.0
+
+
+source-directory /etc/network/interfaces.d
index b7cc4c1eae2b5782249644db8222c15fc08f64c2..37a012ab239da5997675a0f16c5006373377cb3a 100755 (executable)
@@ -42,7 +42,7 @@ http {
 
         location / {
             root   /app/html;
-            index  index.html index.htm;
+            index  index.html index.htm test.html;
         }
 
         #error_page  404              /404.html;
@@ -79,7 +79,7 @@ http {
 
         # HTTP API 反向代理
         location /api/ {
-            proxy_pass http://localhost:7681;
+            proxy_pass http://localhost:12345;
             proxy_set_header Host $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
@@ -91,7 +91,7 @@ http {
 
         # 修改WebSocket代理配置
         location /ws {
-            proxy_pass http://localhost:7681/;  # 添加尾部斜杠,确保路径正确映射
+            proxy_pass http://localhost:12345/;  # 添加尾部斜杠,确保路径正确映射
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";
@@ -104,6 +104,15 @@ http {
             proxy_send_timeout 86400;
         }
 
+        client_max_body_size 100m; 
+        location /upload {
+            proxy_pass http://localhost:12345;
+            proxy_http_version 1.1;
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+        }
     }
 
 
index 7f5287ac8d5cec877b04c5a905224c01270f99fc..74fb403378c13c2955aeb25de66c8669d337ebbb 100644 (file)
@@ -2,6 +2,17 @@
 #include <unistd.h>
 #include "user.h"
 
+#ifdef __x86_64__
+
+#define PID_FILE  "/tmp/pcs_dtu.pid"
+
+#else
+
+#define PID_FILE  "/var/run/pcs_dtu/pcs_dtu.pid"
+
+#endif
+
+
 int bms_start(void);
 int pcs_start(void);
 int webserver_start(void);
@@ -10,6 +21,40 @@ extern bool user_bms_send_heartbeat(uint16_t heartbeat_value);
 
 board_info_t g_board_info;
 
+static int alone_runnind(void)
+{
+    int fd;
+    char buf[16];
+    struct flock fl;
+
+    fd = open(PID_FILE, O_RDWR | O_CREAT, 0666);
+    if (fd < 0){
+        perror("open");
+        exit(1);
+    }
+
+    fl.l_type = F_WRLCK;
+    fl.l_start = 0;
+    fl.l_whence = SEEK_SET;
+    fl.l_len = 0;
+
+    if(fcntl(fd, F_SETLK, &fl)<0){
+        if (errno == EACCES || errno == EAGAIN){
+            close(fd);
+            return -1;
+        }
+    }
+
+    if( ftruncate(fd, 0) ){  //设置文件的大小为0
+    }
+
+    sprintf(buf, "%ld\n", (long)getpid());
+    if( write(fd, buf, strlen(buf) )){
+    }
+
+    //这里不关闭文件, 保持锁定状态
+    return 0;
+}
 
 int main(void)
 {
@@ -18,6 +63,10 @@ int main(void)
    uint16_t heartbeat_value = 0x1234;
    uint32_t n = 0;
 
+    if( alone_runnind()<0){
+        printf( "pcs_dtu already running ...exit!\n " );
+        exit(-1);
+    }
    user_log_init();
 
    printf("---PCS DTU, Version:1.0\n");
@@ -56,7 +105,7 @@ int main(void)
             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 ){
+        if( n++ > 5 ){
             n = 0;
             user_bms_send_heartbeat( heartbeat_value++ );
         }
index 45b77bbe41ec43bca2527c82cdd8c1c1a584d4ed..c0248b6f257bf6cdfcb1dd9234db30ba195c34f0 100644 (file)
@@ -9,9 +9,13 @@
 #include <linux/can/raw.h>
 #include <time.h>
 #include <pthread.h>
+#include <errno.h>
 
 #include "user_bms.h"
 
+#define BMS_CAN  "can0"
+#define BMS_CAN_DOWN "ip link set can0 down"
+#define BMS_CAN_UP "ip link set can0 up"
 
 static struct sockaddr_can addr;
 
@@ -28,6 +32,16 @@ static int16_t le16s_to_host(const uint8_t *data) {
     return (int16_t)(data[0] | (data[1] << 8));
 }
 
+void bms_can_reset( void )
+{
+    printf( "can0 down...\n" );
+    system( BMS_CAN_DOWN );
+    usleep(100);
+    printf( "can0 up...\n" );
+    system( BMS_CAN_UP );
+
+}
+
 /* 获取BMS设备信息 */
 int user_bms_data_get(bms_data_t *bms_data)
 {
@@ -58,6 +72,7 @@ bool user_bms_init(const char *can_interface)
 
     // 初始化BMS数据
     memset(&g_bms, 0, sizeof(g_bms));
+    g_bms.can_socket = -1;
     pthread_mutex_init(&g_bms.mutex, NULL);
 
     // 创建CAN socket
@@ -110,8 +125,13 @@ bool user_bms_send_heartbeat(uint16_t heartbeat_value)
     memset(&frame.data[2], 0, 6);
 
     // 发送CAN帧
+    printf( "bms write ... \n" );
     if (write(g_bms.can_socket, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
-        perror("write");
+        perror("bsm write error");
+        if (errno == ENOBUFS) {
+            printf("write faile [ENOBUFS]: reset can interface!\b");
+            bms_can_reset();
+        }
         return false;
     }
 
index 1d440b45b74d4a0fda153a119cd19bf18e120658..ec69278dd7b4b2fd39c5773b030dcf0b27810944 100644 (file)
@@ -262,6 +262,7 @@ static void *user_mb_thread_func(void *arg) {
         }
 
         /* 等待1秒 */
+        printf( "mb read sleep(%d s);\n", handler->read_interval );
         if( modbus_read_input_bits > 0 && handler->read_interval < 30 )
             sleep(handler->read_interval);
         else
index 0a34fb589440c15dbaa41540c1283e520405c934..6cd0d084b2c1e109b6bee42033ac94069f0d5183 100644 (file)
@@ -755,10 +755,10 @@ static void* webserver_task_thread(void* arg)
        int thread_create_result;
 
        lws_set_log_level(logs, NULL);
-       lwsl_user("LWS minimal HTTP & WebSocket combined server | visit http://localhost:7681\n");
+       lwsl_user("LWS minimal HTTP & WebSocket combined server | visit http://localhost:12345\n");
 
        memset(&info, 0, sizeof info); /* 否则是未初始化的垃圾值 */
-       info.port = 7681;
+       info.port = 12345;
        info.protocols = protocols;
        info.mounts = &mount;
        info.pvo = &pvo;
diff --git a/test-login.html b/test-login.html
deleted file mode 100644 (file)
index f555d4f..0000000
+++ /dev/null
@@ -1,880 +0,0 @@
-<!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; max-width: 900px;
-            margin: 0 auto; padding: 20px; line-height: 1.6;
-        }
-        h1 {
-            color: #333; border-bottom: 1px solid #ddd;
-            padding-bottom: 10px; margin-bottom: 30px;
-        }
-        h2 { color: #444; margin-top: 30px; }
-        .section {
-            background-color: #f9f9f9; padding: 20px;
-            border-radius: 5px; border: 1px solid #ddd;
-            margin-bottom: 30px;
-        }
-        button {
-            background-color: #4CAF50; color: white;
-            border: none; padding: 10px 20px;
-            margin: 5px 0; cursor: pointer;
-            border-radius: 4px; font-size: 16px;
-        }
-        button:hover { background-color: #45a049; }
-        button:disabled { background-color: #cccccc; cursor: not-allowed; }
-        .response-box {
-            margin-top: 20px; padding: 15px;
-            background-color: #f5f5f5; border: 1px solid #ddd;
-            border-radius: 4px; white-space: pre-wrap;
-            font-family: monospace; max-height: 400px;
-            overflow-y: auto;
-        }
-        input[type="text"], input[type="password"], textarea {
-            width: 100%; padding: 10px;
-            margin: 10px 0; border: 1px solid #ddd;
-            border-radius: 4px; box-sizing: border-box;
-        }
-        textarea { height: 100px; resize: vertical; }
-        .loading { display: inline-block; margin-left: 10px; color: #666; font-style: italic; }
-        .status-code { font-weight: bold; margin-right: 10px; }
-        .status-code.success { color: #4CAF50; }
-        .status-code.error { color: #f44336; }
-        .status-code.warning { color: #ff9800; }
-        .connection-status { font-weight: bold; margin-left: 10px; }
-        .connection-status.connected { color: #4CAF50; }
-        .connection-status.disconnected { color: #f44336; }
-        .message-list {
-            max-height: 300px; overflow-y: auto;
-            border: 1px solid #ddd; padding: 10px;
-            margin-top: 10px; background-color: #f9f9f9;
-        }
-        .message { margin-bottom: 10px; padding: 8px; border-radius: 4px; }
-        .message.server { background-color: #e3f2fd; border-left: 3px solid #2196f3; }
-        .message.client { background-color: #e8f5e9; border-right: 3px solid #4caf50; text-align: right; }
-        .message-time { font-size: 11px; color: #666; }
-        .info-tabs { display: flex; margin-bottom: 10px; }
-        .info-tab { padding: 8px 15px; cursor: pointer; background-color: #e0e0e0; border: 1px solid #ddd; border-bottom: none; border-radius: 4px 4px 0 0; margin-right: 5px; }
-        .info-tab.active { background-color: #f5f5f5; font-weight: bold; }
-        .info-content { display: none; }
-        .info-content.active { display: block; }
-        .auth-status {
-            position: absolute; top: 10px; right: 10px;
-            padding: 10px; background-color: #f1f1f1;
-            border: 1px solid #ddd; border-radius: 4px;
-            font-size: 14px;
-        }
-        .auth-status.logged-in {
-            background-color: #e8f5e9; border-color: #4caf50;
-        }
-        .auth-status.logged-out {
-            background-color: #ffebee; border-color: #f44336;
-        }
-        .login-form {
-            display: grid; grid-template-columns: 120px 1fr;
-            gap: 10px; align-items: center;
-        }
-        .login-form button { grid-column: 2; }
-        .form-group { margin-bottom: 15px; }
-    </style>
-</head>
-<body>
-    <div class="auth-status" id="auth-status">
-        未登录 <span id="username-display"></span>
-    </div>
-    
-    <h1>HTTP & WebSocket 综合测试页面</h1>
-    
-    <!-- 登录/登出功能区域 -->
-    <div class="section" id="auth-section">
-        <h2>用户认证</h2>
-        <div id="login-form">
-            <div class="form-group">
-                <label for="username">用户名:</label>
-                <input type="text" id="username" placeholder="请输入用户名" value="admin">
-            </div>
-            <div class="form-group">
-                <label for="password">密码:</label>
-                <input type="password" id="password" placeholder="请输入密码" value="admin123">
-            </div>
-            <button id="login-button" onclick="userLogin()">登录</button>
-            <span id="login-loading" class="loading" style="display: none;">登录中...</span>
-        </div>
-        <div id="logout-section" style="display: none;">
-            <p>您已登录,用户名:<span id="current-username"></span></p>
-            <button id="logout-button" onclick="userLogout()">登出</button>
-        </div>
-        <div class="response-box" id="auth-response">
-            等待认证操作...
-        </div>
-    </div>
-    
-    <!-- GET 请求测试 -->
-    <div class="section">
-        <h2>GET 请求测试</h2>
-        <p>点击按钮发送 GET 请求到服务器,并查看返回的 JSON 数据。</p>
-        <button id="get-button" onclick="testGet()">发送 GET 请求</button>
-        <span id="get-loading" class="loading" style="display: none;">请求中...</span>
-        
-        <div class="response-box" id="get-response">
-            等待响应...
-        </div>
-    </div>
-    
-    <!-- POST 请求测试 - 修改为获取PCS信息 -->
-    <div class="section">
-        <h2>获取PCS信息测试</h2>
-        <p>点击按钮发送 POST 请求获取PCS信息,服务器将返回包含PCS详细数据的JSON响应。</p>
-        
-        <button id="post-button" onclick="getPcsInfo()">获取PCS信息</button>
-        <span id="post-loading" class="loading" style="display: none;">请求中...</span>
-        
-        <div class="response-box" id="post-response">
-            等待响应...
-        </div>
-    </div>
-    
-    <!-- WebSocket 测试 -->
-    <div class="section">
-        <h2>WebSocket 测试</h2>
-        <p>连接到 WebSocket 服务器,并发送/接收消息。</p>
-        
-        <div>
-            <label for="ws-url">WebSocket URL:</label>
-            <input type="text" id="ws-url" value="ws://localhost:7681" placeholder="WebSocket URL">
-        </div>
-        
-        <div>
-            <button id="ws-connect" onclick="connectWebSocket()">连接 WebSocket</button>
-            <button id="ws-disconnect" onclick="disconnectWebSocket()" disabled>断开连接</button>
-            <span id="ws-status" class="connection-status disconnected">未连接</span>
-        </div>
-        
-        <div id="ws-message-section" style="display: none;">
-            <label for="ws-message">消息内容:</label>
-            <input type="text" id="ws-message" placeholder="输入要发送的消息" value="{"msg":"get_pcs_info"}">
-            <button id="ws-send" onclick="sendWebSocketMessage()">发送消息</button>
-            
-            <div class="message-list" id="ws-message-list">
-                <!-- 消息将显示在这里 -->
-            </div>
-        </div>
-    </div>
-
-    <script>
-        // WebSocket 连接对象
-        let webSocket = null;
-        
-        // 显示响应内容
-        function showResponse(elementId, content) {
-            document.getElementById(elementId).textContent = content;
-        }
-        
-        // 格式化 JSON 以便显示
-        function formatJson(jsonStr) {
-            try {
-                const parsed = JSON.parse(jsonStr);
-                return JSON.stringify(parsed, null, 2);
-            } catch (e) {
-                return jsonStr; // 如果不是有效的 JSON,返回原始字符串
-            }
-        }
-        
-        // 测试 GET 请求
-        function testGet() {
-            const getButton = document.getElementById("get-button");
-            const getLoading = document.getElementById("get-loading");
-            
-            // 显示加载状态
-            getButton.disabled = true;
-            getLoading.style.display = "inline";
-            showResponse("get-response", "发送 GET 请求中...");
-            
-            // 创建 XMLHttpRequest 对象
-            const xhr = new XMLHttpRequest();
-            // 修改GET请求URL
-            xhr.open("GET", "/api/get", true);
-            
-            // 添加token头
-            const token = getToken();
-            if (token) {
-                xhr.setRequestHeader("Authorization", "Bearer " + token);
-            }
-            
-            // 设置请求完成回调
-            xhr.onreadystatechange = function() {
-                if (xhr.readyState === 4) {
-                    // 隐藏加载状态
-                    getButton.disabled = false;
-                    getLoading.style.display = "none";
-                    
-                    // 处理响应
-                    if (xhr.status === 200) {
-                        const formattedResponse = "HTTP 状态码: " + xhr.status + " (成功)\n\n" + formatJson(xhr.responseText);
-                        showResponse("get-response", formattedResponse);
-                    } else if (xhr.status === 401) {
-                        // 处理认证失败
-                        showResponse("get-response", "请求失败\nHTTP 状态码: " + xhr.status + " (认证失败,请先登录)");
-                        handleAuthFailure();
-                    } else {
-                        showResponse("get-response", "请求失败\nHTTP 状态码: " + xhr.status);
-                    }
-                }
-            };
-            
-            // 发送请求
-            xhr.send();
-        }
-        
-        // 获取PCS信息 - 按照pcs.md中的协议规范
-        function getPcsInfo() {
-            const postButton = document.getElementById("post-button");
-            const postLoading = document.getElementById("post-loading");
-            
-            // 显示加载状态
-            postButton.disabled = true;
-            postLoading.style.display = "inline";
-            showResponse("post-response", "发送获取PCS信息请求中...");
-            
-            // 创建 XMLHttpRequest 对象
-            const xhr = new XMLHttpRequest();
-            // 修改POST请求URL为pcs.md中定义的路径
-            xhr.open("POST", "/api/pcs_info", true);
-            // 设置内容类型为 JSON
-            xhr.setRequestHeader("Content-Type", "application/json");
-            
-            // 添加token头
-            const token = getToken();
-            if (token) {
-                xhr.setRequestHeader("Authorization", "Bearer " + token);
-            }
-            
-            // 设置请求完成回调
-            xhr.onreadystatechange = function() {
-                if (xhr.readyState === 4) {
-                    // 隐藏加载状态
-                    postButton.disabled = false;
-                    postLoading.style.display = "none";
-                    
-                    // 处理响应
-                    if (xhr.status === 200) {
-try {
-                            // 尝试解析JSON响应
-                            const responseObj = JSON.parse(xhr.responseText);
-                            const formattedResponse = "HTTP 状态码: " + xhr.status + " (成功)\n\n" + JSON.stringify(responseObj, null, 2);
-                            showResponse("post-response", formattedResponse);
-                        } catch (e) {
-                            // 如果解析失败,显示原始响应
-                            showResponse("post-response", "HTTP 状态码: " + xhr.status + " (成功)\n\n但响应不是有效的JSON:\n" + xhr.responseText);
-                        }
-                    } else if (xhr.status === 401) {
-                        // 处理认证失败
-                        showResponse("post-response", "请求失败\nHTTP 状态码: " + xhr.status + " (认证失败,请先登录)\n响应文本: " + xhr.responseText);
-                        handleAuthFailure();
-                    } else {
-                        showResponse("post-response", "请求失败\nHTTP 状态码: " + xhr.status + "\n响应文本: " + xhr.responseText);
-                    }
-                }
-};
-            
-            // 添加错误处理
-            xhr.onerror = function(error) {
-                console.error("请求错误:", error);
-                postButton.disabled = false;
-                postLoading.style.display = "none";
-                showResponse("post-response", "请求发生错误\n" + (error.message || "未知错误"));
-            };
-            
-            // 添加超时处理
-            xhr.timeout = 10000; // 10秒超时
-            xhr.ontimeout = function() {
-                console.error("请求超时");
-                postButton.disabled = false;
-                postLoading.style.display = "none";
-                showResponse("post-response", "请求超时 (超过10秒)");
-            };
-            
-            // 构建符合pcs.md协议规范的JSON数据,包含token
-            const jsonData = JSON.stringify({
-                "code": 0,
-                "msg": "get_pcs_info",
-                "token": getToken() || ""
-            });
-            
-            console.log("发送的JSON数据:", jsonData);
-            
-            // 发送请求
-            xhr.send(jsonData);
-        }
-        
-        // 连接 WebSocket
-        function connectWebSocket() {
-            const wsUrl = document.getElementById("ws-url").value;
-const wsConnectButton = document.getElementById("ws-connect");
-            const wsDisconnectButton = document.getElementById("ws-disconnect");
-const wsStatus = document.getElementById("ws-status");
-            const wsMessageSection = document.getElementById("ws-message-section");
-            
-            try {
-                // 获取token
-                const token = getToken();
-                if (!token) {
-                    addMessage("server", "WebSocket连接需要先登录");
-                    return;
-                }
-                
-                // 创建 WebSocket 连接,添加协议参数
-                // 注意:WebSocket协议不支持自定义headers,token需要通过其他方式传递
-                webSocket = new WebSocket(wsUrl, ['ws']);
-                
-                // 连接成功事件
-                webSocket.onopen = function() {
-                    console.log("WebSocket 连接已建立");
-wsConnectButton.disabled = true;
-                    wsDisconnectButton.disabled = false;
-                    wsStatus.textContent = "已连接";
-                    wsStatus.className = "connection-status connected";
-                    wsMessageSection.style.display = "block";
-                    addMessage("server", "WebSocket 连接已建立");
-                    
-                    // 连接成功后发送认证消息
-                    sendAuthMessage();
-                };
-                
-                // 接收消息事件
-                webSocket.onmessage = function(event) {
-                    console.log("收到 WebSocket 消息: " + event.data);
-                    processReceivedMessage(event.data);
-                };
-                
-                // 连接关闭事件
-                webSocket.onclose = function(event) {
-                    console.log("WebSocket 连接已关闭");
-                    wsConnectButton.disabled = false;
-                    wsDisconnectButton.disabled = true;
-                    wsStatus.textContent = "未连接";
-                    wsStatus.className = "connection-status disconnected";
-                    wsMessageSection.style.display = "none";
-                    
-                    let closeMessage = "WebSocket 连接已关闭";
-                    if (event.code !== 1000) {
-                        closeMessage += " (错误码: " + event.code + ")";
-                    }
-                    addMessage("server", closeMessage);
-                };
-                
-                // 连接错误事件
-                webSocket.onerror = function(error) {
-                    console.error("WebSocket 错误: ", error);
-                    addMessage("server", "WebSocket 错误: " + (error.message || "未知错误"));
-                };
-            } catch (e) {
-                console.error("WebSocket 连接失败: ", e);
-                addMessage("server", "连接失败: " + e.message);
-            }
-        }
-        
-        // 发送认证消息到WebSocket服务器
-        function sendAuthMessage() {
-            const token = getToken();
-            if (webSocket && webSocket.readyState === WebSocket.OPEN && token) {
-                const authMessage = JSON.stringify({
-                    "msg": "auth",
-                    "token": token
-                });
-                webSocket.send(authMessage);
-                console.log("已发送认证消息: ", authMessage);
-            }
-        }
-        
-        // 断开 WebSocket 连接
-        function disconnectWebSocket() {
-            if (webSocket) {
-                console.log("正在关闭WebSocket连接");
-                webSocket.close();
-                webSocket = null;
-            }
-        }
-        
-        // 发送 WebSocket 消息
-        function sendWebSocketMessage() {
-            const messageInput = document.getElementById("ws-message");
-            const message = messageInput.value;
-            
-            if (webSocket && webSocket.readyState === WebSocket.OPEN && message.trim()) {
-                try {
-                    // 尝试解析用户输入作为JSON
-                    let messageObj = JSON.parse(message);
-                    
-                    // 添加token到消息中
-                    const token = getToken();
-                    if (token) {
-                        messageObj.token = token;
-                    }
-                    
-                    const jsonMessage = JSON.stringify(messageObj);
-                    webSocket.send(jsonMessage);
-                    addMessage("client", jsonMessage);
-                } catch (e) {
-                    // 如果用户输入不是有效的JSON,包装成JSON对象并添加token
-                    const token = getToken();
-                    const jsonMessage = JSON.stringify({
-                        message: message,
-                        token: token || ""
-                    });
-                    webSocket.send(jsonMessage);
-                    addMessage("client", jsonMessage);
-                }
-            } else {
-                addMessage("server", "WebSocket未连接或消息为空");
-                console.log("WebSocket状态:", webSocket ? webSocket.readyState : "未初始化");
-            }
-        }
-        
-        // 专门处理接收到的消息,特别是广播消息
-        function processReceivedMessage(data) {
-            try {
-                console.log('收到消息时间:', new Date().toLocaleTimeString(), '消息内容:', data);
-                // 尝试将数据解析为JSON
-                const messageObj = JSON.parse(data);
-                
-                // 识别服务器发送的认证失败消息
-                if (messageObj.msg === "auth_failed") {
-                    addMessage("server", "认证失败:" + (messageObj.reason || "无效的token"));
-                    handleAuthFailure();
-                    return;
-                }
-                
-                // 识别服务器发送的time_broadcast类型
-                if (messageObj.type === "time_broadcast" && messageObj.timestamp) {
-                    console.log('处理广播消息:', messageObj.timestamp);
-                    // 格式化时间消息显示
-                    addMessage("server", `广播消息:当前服务器时间 - ${messageObj.timestamp}`);
-                } else {
-                    // 普通消息,直接显示
-                    addMessage("server", data);
-                }
-            } catch (e) {
-                // 不是JSON格式,直接显示
-                addMessage("server", data);
-            }
-        }
-        
-        // 添加消息到消息列表
-        function addMessage(type, content) {
-            const messageList = document.getElementById("ws-message-list");
-            const messageElement = document.createElement("div");
-            messageElement.className = "message " + type;
-            
-            const now = new Date();
-            const timeString = now.toLocaleTimeString();
-            
-            // 如果是广播消息,添加特殊样式类
-            let contentClass = "message-content";
-            if (content.includes("广播消息")) {
-                contentClass += " broadcast-message";
-            }
-            
-            messageElement.innerHTML = "<div class='message-time'>" + timeString + "</div><div class='" + contentClass + "'>" + escapeHtml(content) + "</div>";
-            
-            messageList.appendChild(messageElement);
-            messageList.scrollTop = messageList.scrollHeight; // 滚动到底部
-        }
-        
-        // HTML 转义函数
-        function escapeHtml(text) {
-            const div = document.createElement('div');
-            div.textContent = text;
-            return div.innerHTML;
-        }
-        
-        // 添加特殊样式用于广播消息
-        function addBroadcastStyles() {
-            const style = document.createElement('style');
-            style.textContent = `
-                .broadcast-message {
-                    color: #d32f2f;
-                    font-weight: bold;
-                    animation: fadeIn 0.5s ease-in;
-                }
-                @keyframes fadeIn {
-                    from { opacity: 0; transform: translateY(10px); }
-                    to { opacity: 1; transform: translateY(0); }
-                }
-            `;
-            document.head.appendChild(style);
-        }
-        
-        // 显示响应内容 - 添加错误处理
-        function showResponse(elementId, content) {
-            const element = document.getElementById(elementId);
-            if (element) {
-                element.textContent = content;
-            } else {
-                console.error(`元素ID "${elementId}" 未找到`);
-                // 如果找不到元素,可以使用console.log显示信息
-                console.log(`响应内容 [${elementId}]:`, content);
-                
-                // 尝试找到第一个response-box作为备选显示
-                const responseBox = document.querySelector('.response-box');
-                if (responseBox) {
-                    responseBox.textContent = `[${elementId}] ${content}`;
-                }
-            }
-        }
-        
-        // 登录功能 - 按照pcs.md中的协议规范
-        function userLogin() {
-            // 确保DOM元素存在
-            const usernameElement = document.getElementById("username");
-            const passwordElement = document.getElementById("password");
-            const loginButton = document.getElementById("login-button");
-            const loginLoading = document.getElementById("login-loading");
-            const authResponseElement = document.getElementById("auth-response");
-            
-            if (!usernameElement || !passwordElement || !loginButton || !loginLoading || !authResponseElement) {
-                console.error("必要的DOM元素未找到");
-                if (authResponseElement) {
-                    authResponseElement.textContent = "错误:页面元素加载不完整,请刷新页面重试";
-                }
-                return;
-            }
-            
-            const username = usernameElement.value;
-            const password = passwordElement.value;
-            
-            if (!username || !password) {
-                authResponseElement.textContent = "错误:用户名和密码不能为空";
-                return;
-            }
-            
-            // 显示加载状态
-            loginButton.disabled = true;
-            loginLoading.style.display = "inline";
-            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 {
-                                    console.log("原始响应文本:", xhr.responseText);
-                                    
-                                    // 尝试解析JSON响应
-                                    let responseObj = JSON.parse(xhr.responseText);
-                                    console.log("解析后的JSON对象:", responseObj);
-                                    
-                                    // 检查是否登录成功
-                                    if (responseObj && responseObj.code === 0 && 
-                                        responseObj.msg === "login_success" && 
-                                        responseObj.data && responseObj.data.token) {
-                                        // 保存token和用户名
-                                        saveToken(responseObj.data.token);
-                                        saveUsername(username);
-                                        
-                                        // 更新UI显示
-                                        try {
-                                            updateAuthUI();
-                                        } catch (uiError) {
-                                            console.error("更新UI时发生错误:", uiError);
-                                        }
-                                        
-                                        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();
-            }
-        }
-        
-        // 页面加载完成后执行
-        document.addEventListener('DOMContentLoaded', function() {
-            console.log('测试页面已加载完成');
-            // 添加广播消息样式
-            addBroadcastStyles();
-            // 检查是否已有登录状态
-            updateAuthUI();
-        });
-    </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/test.html b/test.html
deleted file mode 100644 (file)
index 6959cc2..0000000
--- a/test.html
+++ /dev/null
@@ -1,497 +0,0 @@
-<!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;
-            max-width: 900px;
-            margin: 0 auto;
-            padding: 20px;
-            line-height: 1.6;
-        }
-        h1 {
-            color: #333;
-            border-bottom: 1px solid #ddd;
-            padding-bottom: 10px;
-            margin-bottom: 30px;
-        }
-        h2 {
-            color: #444;
-            margin-top: 30px;
-        }
-        .section {
-            background-color: #f9f9f9;
-            padding: 20px;
-            border-radius: 5px;
-            border: 1px solid #ddd;
-            margin-bottom: 30px;
-        }
-        button {
-            background-color: #4CAF50;
-            color: white;
-            border: none;
-            padding: 10px 20px;
-            margin: 5px 0;
-            cursor: pointer;
-            border-radius: 4px;
-            font-size: 16px;
-        }
-        button:hover {
-            background-color: #45a049;
-        }
-        button:disabled {
-            background-color: #cccccc;
-            cursor: not-allowed;
-        }
-        .response-box {
-            margin-top: 20px;
-            padding: 15px;
-            background-color: #f5f5f5;
-            border: 1px solid #ddd;
-            border-radius: 4px;
-            white-space: pre-wrap;
-            font-family: monospace;
-            max-height: 400px;
-            overflow-y: auto;
-        }
-        input[type="text"], textarea {
-            width: 100%;
-            padding: 10px;
-            margin: 10px 0;
-            border: 1px solid #ddd;
-            border-radius: 4px;
-            box-sizing: border-box;
-        }
-        textarea {
-            height: 100px;
-            resize: vertical;
-        }
-        .loading {
-            display: inline-block;
-            margin-left: 10px;
-            color: #666;
-            font-style: italic;
-        }
-        .status-code {
-            font-weight: bold;
-            margin-right: 10px;
-        }
-        .status-code.success {
-            color: #4CAF50;
-        }
-        .status-code.error {
-            color: #f44336;
-        }
-        .status-code.warning {
-            color: #ff9800;
-        }
-        .connection-status {
-            font-weight: bold;
-            margin-left: 10px;
-        }
-        .connection-status.connected {
-            color: #4CAF50;
-        }
-        .connection-status.disconnected {
-            color: #f44336;
-        }
-        .message-list {
-            max-height: 300px;
-            overflow-y: auto;
-            border: 1px solid #ddd;
-            padding: 10px;
-            margin-top: 10px;
-            background-color: #f9f9f9;
-        }
-        .message {
-            margin-bottom: 10px;
-            padding: 8px;
-            border-radius: 4px;
-        }
-        .message.server {
-            background-color: #e3f2fd;
-            border-left: 3px solid #2196f3;
-        }
-        .message.client {
-            background-color: #e8f5e9;
-            border-right: 3px solid #4caf50;
-            text-align: right;
-        }
-        .message-time {
-            font-size: 11px;
-            color: #666;
-        }
-        .info-tabs {
-            display: flex;
-            margin-bottom: 10px;
-        }
-        .info-tab {
-            padding: 8px 15px;
-            cursor: pointer;
-            background-color: #e0e0e0;
-            border: 1px solid #ddd;
-            border-bottom: none;
-            border-radius: 4px 4px 0 0;
-            margin-right: 5px;
-        }
-        .info-tab.active {
-            background-color: #f5f5f5;
-            font-weight: bold;
-        }
-        .info-content {
-            display: none;
-        }
-        .info-content.active {
-            display: block;
-        }
-    </style>
-</head>
-<body>
-    <h1>HTTP & WebSocket 综合测试页面</h1>
-    
-    <!-- GET 请求测试 -->
-    <div class="section">
-        <h2>GET 请求测试</h2>
-        <p>点击按钮发送 GET 请求到服务器,并查看返回的 JSON 数据。</p>
-        <button id="get-button" onclick="testGet()">发送 GET 请求</button>
-        <span id="get-loading" class="loading" style="display: none;">请求中...</span>
-        
-        <div class="response-box" id="get-response">
-            等待响应...
-        </div>
-    </div>
-    
-    <!-- POST 请求测试 - 修改为获取PCS信息 -->
-    <div class="section">
-        <h2>获取PCS信息测试</h2>
-        <p>点击按钮发送 POST 请求获取PCS信息,服务器将返回包含PCS详细数据的JSON响应。</p>
-        
-        <button id="post-button" onclick="getPcsInfo()">获取PCS信息</button>
-        <span id="post-loading" class="loading" style="display: none;">请求中...</span>
-        
-        <div class="response-box" id="post-response">
-            等待响应...
-        </div>
-    </div>
-    
-    <!-- WebSocket 测试 -->
-    <div class="section">
-        <h2>WebSocket 测试</h2>
-        <p>连接到 WebSocket 服务器,并发送/接收消息。</p>
-        
-        <div>
-            <label for="ws-url">WebSocket URL:</label>
-            <input type="text" id="ws-url" value="ws://localhost:7681" placeholder="WebSocket URL">
-        </div>
-        
-        <div>
-            <button id="ws-connect" onclick="connectWebSocket()">连接 WebSocket</button>
-            <button id="ws-disconnect" onclick="disconnectWebSocket()" disabled>断开连接</button>
-            <span id="ws-status" class="connection-status disconnected">未连接</span>
-        </div>
-        
-        <div id="ws-message-section" style="display: none;">
-            <label for="ws-message">消息内容:</label>
-            <input type="text" id="ws-message" placeholder="输入要发送的消息" value="Hello WebSocket!">
-            <button id="ws-send" onclick="sendWebSocketMessage()">发送消息</button>
-            
-            <div class="message-list" id="ws-message-list">
-                <!-- 消息将显示在这里 -->
-            </div>
-        </div>
-    </div>
-
-    <script>
-        // WebSocket 连接对象
-        let webSocket = null;
-        
-        // 显示响应内容
-        function showResponse(elementId, content) {
-            document.getElementById(elementId).textContent = content;
-        }
-        
-        // 格式化 JSON 以便显示
-        function formatJson(jsonStr) {
-            try {
-                const parsed = JSON.parse(jsonStr);
-                return JSON.stringify(parsed, null, 2);
-            } catch (e) {
-                return jsonStr; // 如果不是有效的 JSON,返回原始字符串
-            }
-        }
-        
-        // 测试 GET 请求
-        function testGet() {
-            const getButton = document.getElementById("get-button");
-            const getLoading = document.getElementById("get-loading");
-            
-            // 显示加载状态
-            getButton.disabled = true;
-            getLoading.style.display = "inline";
-            showResponse("get-response", "发送 GET 请求中...");
-            
-            // 创建 XMLHttpRequest 对象
-            const xhr = new XMLHttpRequest();
-            // 修改GET请求URL
-            xhr.open("GET", "/api/get", true);
-            
-            // 设置请求完成回调
-            xhr.onreadystatechange = function() {
-                if (xhr.readyState === 4) {
-                    // 隐藏加载状态
-                    getButton.disabled = false;
-                    getLoading.style.display = "none";
-                    
-                    // 处理响应
-                    if (xhr.status === 200) {
-                        const formattedResponse = "HTTP 状态码: " + xhr.status + " (成功)\n\n" + formatJson(xhr.responseText);
-                        showResponse("get-response", formattedResponse);
-                    } else {
-                        showResponse("get-response", "请求失败\nHTTP 状态码: " + xhr.status);
-                    }
-                }
-            };
-            
-            // 发送请求
-            xhr.send();
-        }
-        
-        // 获取PCS信息 - 按照pcs.md中的协议规范
-        function getPcsInfo() {
-            const postButton = document.getElementById("post-button");
-            const postLoading = document.getElementById("post-loading");
-            
-            // 显示加载状态
-            postButton.disabled = true;
-            postLoading.style.display = "inline";
-            showResponse("post-response", "发送获取PCS信息请求中...");
-            
-            // 创建 XMLHttpRequest 对象
-            const xhr = new XMLHttpRequest();
-            // 修改POST请求URL为pcs.md中定义的路径
-            xhr.open("POST", "/api/pcs_info", true);
-            // 设置内容类型为 JSON
-            xhr.setRequestHeader("Content-Type", "application/json");
-            
-            // 设置请求完成回调
-            xhr.onreadystatechange = function() {
-                if (xhr.readyState === 4) {
-                    // 隐藏加载状态
-                    postButton.disabled = false;
-                    postLoading.style.display = "none";
-                    
-                    // 处理响应
-                    if (xhr.status === 200) {
-                        try {
-                            // 尝试解析JSON响应
-                            const responseObj = JSON.parse(xhr.responseText);
-                            const formattedResponse = "HTTP 状态码: " + xhr.status + " (成功)\n\n" + JSON.stringify(responseObj, null, 2);
-                            showResponse("post-response", formattedResponse);
-                        } catch (e) {
-                            // 如果解析失败,显示原始响应
-                            showResponse("post-response", "HTTP 状态码: " + xhr.status + " (成功)\n\n但响应不是有效的JSON:\n" + xhr.responseText);
-                        }
-                    } else {
-                        showResponse("post-response", "请求失败\nHTTP 状态码: " + xhr.status + "\n响应文本: " + xhr.responseText);
-                    }
-                }
-            };
-            
-            // 添加错误处理
-            xhr.onerror = function(error) {
-                console.error("请求错误:", error);
-                postButton.disabled = false;
-                postLoading.style.display = "none";
-                showResponse("post-response", "请求发生错误\n" + (error.message || "未知错误"));
-            };
-            
-            // 添加超时处理
-            xhr.timeout = 10000; // 10秒超时
-            xhr.ontimeout = function() {
-                console.error("请求超时");
-                postButton.disabled = false;
-                postLoading.style.display = "none";
-                showResponse("post-response", "请求超时 (超过10秒)");
-            };
-            
-            // 构建符合pcs.md协议规范的JSON数据
-            const jsonData = JSON.stringify({
-                "code": 0,
-                "msg": "get_pcs_info"
-            });
-            
-            console.log("发送的JSON数据:", jsonData);
-            
-            // 发送请求
-            xhr.send(jsonData);
-        }
-        
-        // 连接 WebSocket
-        function connectWebSocket() {
-            const wsUrl = document.getElementById("ws-url").value;
-            const wsConnectButton = document.getElementById("ws-connect");
-            const wsDisconnectButton = document.getElementById("ws-disconnect");
-            const wsStatus = document.getElementById("ws-status");
-            const wsMessageSection = document.getElementById("ws-message-section");
-            
-            try {
-                // 创建 WebSocket 连接,添加协议参数
-                webSocket = new WebSocket(wsUrl, ['ws']);
-                
-                // 连接成功事件
-                webSocket.onopen = function() {
-                    console.log("WebSocket 连接已建立");
-                    wsConnectButton.disabled = true;
-                    wsDisconnectButton.disabled = false;
-                    wsStatus.textContent = "已连接";
-                    wsStatus.className = "connection-status connected";
-                    wsMessageSection.style.display = "block";
-                    addMessage("server", "WebSocket 连接已建立");
-                };
-                
-                // 接收消息事件
-                webSocket.onmessage = function(event) {
-                    console.log("收到 WebSocket 消息: " + event.data);
-                    processReceivedMessage(event.data);
-                };
-                
-                // 连接关闭事件
-                webSocket.onclose = function(event) {
-                    console.log("WebSocket 连接已关闭");
-                    wsConnectButton.disabled = false;
-                    wsDisconnectButton.disabled = true;
-                    wsStatus.textContent = "未连接";
-                    wsStatus.className = "connection-status disconnected";
-                    wsMessageSection.style.display = "none";
-                    
-                    let closeMessage = "WebSocket 连接已关闭";
-                    if (event.code !== 1000) {
-                        closeMessage += " (错误码: " + event.code + ")";
-                    }
-                    addMessage("server", closeMessage);
-                };
-                
-                // 连接错误事件
-                webSocket.onerror = function(error) {
-                    console.error("WebSocket 错误: ", error);
-                    addMessage("server", "WebSocket 错误: " + (error.message || "未知错误"));
-                };
-            } catch (e) {
-                console.error("WebSocket 连接失败: ", e);
-                addMessage("server", "连接失败: " + e.message);
-            }
-        }
-        
-        // 断开 WebSocket 连接
-        function disconnectWebSocket() {
-            if (webSocket) {
-                console.log("正在关闭WebSocket连接");
-                webSocket.close();
-                webSocket = null;
-            }
-        }
-        
-        // 发送 WebSocket 消息
-        function sendWebSocketMessage() {
-            const messageInput = document.getElementById("ws-message");
-            const message = messageInput.value;
-            
-            if (webSocket && webSocket.readyState === WebSocket.OPEN && message.trim()) {
-                try {
-                    // 尝试解析用户输入作为JSON,如果不是有效JSON,则包装成JSON对象
-                    JSON.parse(message);
-                    webSocket.send(message);
-                    addMessage("client", message);
-                } catch (e) {
-                    // 如果用户输入不是有效的JSON,则包装成JSON对象
-                    const jsonMessage = JSON.stringify({
-                        message: message
-                    });
-                    webSocket.send(jsonMessage);
-                    addMessage("client", jsonMessage);
-                }
-            } else {
-                addMessage("server", "WebSocket未连接或消息为空");
-                console.log("WebSocket状态:", webSocket ? webSocket.readyState : "未初始化");
-            }
-        }
-        
-        // 专门处理接收到的消息,特别是广播消息
-        function processReceivedMessage(data) {
-            try {
-                console.log('收到消息时间:', new Date().toLocaleTimeString(), '消息内容:', data);
-                // 尝试将数据解析为JSON
-                const messageObj = JSON.parse(data);
-                
-                // 识别服务器发送的time_broadcast类型
-                if (messageObj.type === "time_broadcast" && messageObj.timestamp) {
-                    console.log('处理广播消息:', messageObj.timestamp);
-                    // 格式化时间消息显示
-                    addMessage("server", `广播消息:当前服务器时间 - ${messageObj.timestamp}`);
-                } else {
-                    // 普通消息,直接显示
-                    addMessage("server", data);
-                }
-            } catch (e) {
-                // 不是JSON格式,直接显示
-                addMessage("server", data);
-            }
-        }
-        
-        // 添加消息到消息列表
-        function addMessage(type, content) {
-            const messageList = document.getElementById("ws-message-list");
-            const messageElement = document.createElement("div");
-            messageElement.className = "message " + type;
-            
-            const now = new Date();
-            const timeString = now.toLocaleTimeString();
-            
-            // 如果是广播消息,添加特殊样式类
-            let contentClass = "message-content";
-            if (content.includes("广播消息")) {
-                contentClass += " broadcast-message";
-            }
-            
-            messageElement.innerHTML = "<div class='message-time'>" + timeString + "</div><div class='" + contentClass + "'>" + escapeHtml(content) + "</div>";
-            
-            messageList.appendChild(messageElement);
-            messageList.scrollTop = messageList.scrollHeight; // 滚动到底部
-        }
-        
-        // HTML 转义函数
-        function escapeHtml(text) {
-            const div = document.createElement('div');
-            div.textContent = text;
-            return div.innerHTML;
-        }
-        
-        // 添加特殊样式用于广播消息
-        function addBroadcastStyles() {
-            const style = document.createElement('style');
-            style.textContent = `
-                .broadcast-message {
-                    color: #d32f2f;
-                    font-weight: bold;
-                    animation: fadeIn 0.5s ease-in;
-                }
-                @keyframes fadeIn {
-                    from { opacity: 0; transform: translateY(10px); }
-                    to { opacity: 1; transform: translateY(0); }
-                }
-            `;
-            document.head.appendChild(style);
-        }
-
-        // 页面加载完成后执行
-        document.addEventListener('DOMContentLoaded', function() {
-            console.log('测试页面已加载完成');
-            // 添加广播消息样式
-            addBroadcastStyles();
-        });
-    </script>
-</body>
-</html>