添加现有代码V1.6
This commit is contained in:
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
+2018
File diff suppressed because it is too large
Load Diff
Binary file not shown.
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
+1
@@ -0,0 +1 @@
|
||||
.cm-s-monokai.CodeMirror{background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483e}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle{color:#d0d0d0}.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom{color:#ae81ff}.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-comment.cm-attribute{color:#97b757}.cm-s-monokai span.cm-comment.cm-def{color:#bc9262}.cm-s-monokai span.cm-comment.cm-tag{color:#bc6283}.cm-s-monokai span.cm-comment.cm-type{color:#5998a6}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-type,.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header{color:#ae81ff}.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
|
||||
@@ -0,0 +1,81 @@
|
||||
.card {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.form-control {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
#feedbackVoltage,
|
||||
#feedbackCurrent,
|
||||
#filamentVoltage,
|
||||
#filamentCurrent {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
|
||||
/* 导航栏样式 */
|
||||
.navbar {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.nav-link i {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
/* 编辑器相关样式 */
|
||||
.CodeMirror {
|
||||
height: calc(100vh - 200px);
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#fileTree {
|
||||
height: calc(100vh - 200px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-icon {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon {
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon-custom {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
/* 文件类型图标颜色 */
|
||||
.bi-filetype-py {
|
||||
color: #306998;
|
||||
}
|
||||
|
||||
.bi-filetype-json {
|
||||
color: #f7df1e;
|
||||
}
|
||||
|
||||
.bi-filetype-sh {
|
||||
color: #4eaa25;
|
||||
}
|
||||
|
||||
.bi-folder {
|
||||
color: #ffc107;
|
||||
}
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,325 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>测偏仪DAQ测试台</title>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="css/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="css/style.min.css" rel="stylesheet">
|
||||
<link href="css/codemirror.min.css" rel="stylesheet">
|
||||
<link href="css/monokai.min.css" rel="stylesheet">
|
||||
|
||||
<link href="css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- 导航栏 -->
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="/">测偏仪DAQ测试台</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid mt-4">
|
||||
<!-- Toast提示组件 -->
|
||||
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong class="me-auto">系统提示</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="toast-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 选项卡 -->
|
||||
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||
脚本编辑器</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="firmware-tab" data-bs-toggle="tab" data-bs-target="#firmware" type="button"
|
||||
role="tab" aria-controls="firmware" aria-selected="false"><i class="bi bi-pc-display"></i>
|
||||
固件升级</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content" id="mainTabContent">
|
||||
<!-- 固件升级 -->
|
||||
<div class="tab-pane fade" id="firmware" role="tabpanel" aria-labelledby="firmware-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">固件升级</div>
|
||||
<div class="card-body">
|
||||
<!-- 显示当前版本 -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label">当前固件版本:</label>
|
||||
<span id="currentVersion">--------</span>
|
||||
</div>
|
||||
<!-- 选择固件文件 -->
|
||||
<div class="mb-3">
|
||||
<label for="firmwareFile" class="form-label">选择固件文件 (.bin)</label>
|
||||
<input type="file" class="form-control" id="firmwareFile" accept=".bin">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">文件信息</label>
|
||||
<div class="form-control" id="fileInfo" style="height: auto;">
|
||||
<div>文件名: <span id="fileName"></span></div>
|
||||
<div>文件大小: <span id="fileSize"></span></div>
|
||||
<div>校验值: <span id="fileChecksum"></span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">上传进度</label>
|
||||
<div class="progress" style="height: 30px;">
|
||||
<div class="progress-bar progress-bar-striped progress-bar-animated"
|
||||
id="uploadProgress" role="progressbar"
|
||||
style="width: 0%;"
|
||||
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
|
||||
0%
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-grid gap-2">
|
||||
<button class="btn btn-primary" id="startUpload" disabled>
|
||||
<i class="bi bi-upload"></i> 开始上传
|
||||
</button>
|
||||
<button class="btn btn-danger" id="cancelUpload" disabled>
|
||||
<i class="bi bi-x-circle"></i> 取消上传
|
||||
</button>
|
||||
<button class="btn btn-success" id="upgradeFirmware" disabled>
|
||||
<i class="bi bi-play-circle"></i> 执行升级
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<label class="form-label">升级日志</label>
|
||||
<div class="form-control" id="upgradeLog" style="height: 200px; overflow-y: auto;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="card">
|
||||
<div class="card-header">升级说明</div>
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">注意事项</h5>
|
||||
<ul class="list-unstyled">
|
||||
<li><i class="bi bi-exclamation-triangle text-warning"></i> 固件升级过程中请勿断电</li>
|
||||
<li><i class="bi bi-exclamation-triangle text-warning"></i> 升级完成后设备会自动重启</li>
|
||||
<li><i class="bi bi-exclamation-triangle text-warning"></i> 请确保上传的是正确的固件文件</li>
|
||||
<li><i class="bi bi-exclamation-triangle text-warning"></i> 升级过程可能需要几分钟时间</li>
|
||||
</ul>
|
||||
<h5 class="card-title mt-4">升级步骤</h5>
|
||||
<ol>
|
||||
<li>点击"选择固件文件"按钮选择.bin格式的固件文件</li>
|
||||
<li>等待系统计算文件校验值</li>
|
||||
<li>点击"开始上传"按钮上传固件文件</li>
|
||||
<li>上传完成后点击"执行升级"按钮开始升级</li>
|
||||
<li>等待升级完成,设备会自动重启</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 控制面板 -->
|
||||
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||
<!-- DAQ数据采集控制 -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header">DAQ数据采集</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-1">
|
||||
<button class="btn btn-warning" id="reboot">设备重启</button>
|
||||
</div>
|
||||
<div class="col-md-1">
|
||||
<button class="btn btn-success" id="start_daq">开始采集</button>
|
||||
</div>
|
||||
<div class="col-md-1">
|
||||
<button class="btn btn-danger" id="stop_daq">停止采集</button>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">采集时长</span>
|
||||
<input type="number" class="form-control" id="daq_duration" value="1000" min="100" max="10000" step="100">
|
||||
<span class="input-group-text">ms</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">序列号</span>
|
||||
<div class="form-control" id="daq_info">--</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md">
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">DAQ状态</span>
|
||||
<div class="form-control" id="daq_status">--</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据曲线图 -->
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header">数据曲线</div>
|
||||
<div class="card-body">
|
||||
<canvas id="daq_chart" width="800" height="400"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据统计信息 -->
|
||||
<div class="row mt-4">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>数据统计信息</span>
|
||||
<div class="btn-group" role="group" aria-label="数据操作按钮组">
|
||||
<button id="save_data" class="btn btn-primary btn-sm px-2">
|
||||
<i class="bi bi-save me-1"></i> 保存到设备
|
||||
</button>
|
||||
<button id="load_device" class="btn btn-info btn-sm px-2">
|
||||
<i class="bi bi-hdd me-1"></i> 从设备载入
|
||||
</button>
|
||||
<button id="export_csv" class="btn btn-secondary btn-sm px-2">
|
||||
<i class="bi bi-download me-1"></i> 导出CSV
|
||||
</button>
|
||||
<button id="load_local" class="btn btn-success btn-sm px-2">
|
||||
<i class="bi bi-upload me-1"></i> 从本地载入
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-bordered">
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th>采集时间</th>
|
||||
<th>数据长度</th>
|
||||
<th>CH1平均值</th>
|
||||
<th>CH1峰峰值</th>
|
||||
<th>CH1波动水平</th>
|
||||
<th>CH2平均值</th>
|
||||
<th>CH2峰峰值</th>
|
||||
<th>CH2波动水平</th>
|
||||
<th>通道间差异</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="stats_table_body">
|
||||
<!-- 统计数据将通过JavaScript动态添加 -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 脚本编辑器 -->
|
||||
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>文件目录</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="fileTree"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span id="currentFile">未选择文件</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||
<i class="bi bi-save"></i> 保存
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<textarea id="editor"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/lib/jquery.min.js"></script>
|
||||
<script src="js/lib/bootstrap.bundle.min.js"></script>
|
||||
<script src="js/lib/jstree.min.js"></script>
|
||||
<script src="js/lib/codemirror.min.js"></script>
|
||||
<script src="js/lib/python.min.js"></script>
|
||||
<script src="js/lib/javascript.min.js"></script>
|
||||
<script src="js/lib/shell.min.js"></script>
|
||||
<script src="js/lib/htmlmixed.min.js"></script>
|
||||
<script src="js/lib/xml.min.js"></script>
|
||||
<script src="js/lib/css.min.js"></script>
|
||||
<script src="js/lib/base64.min.js"></script>
|
||||
<script src="js/lib/hammer.min.js"></script>
|
||||
<script src="js/lib/chart.min.js"></script>
|
||||
<script src="js/lib/chartjs-plugin-zoom.min.js"></script>
|
||||
|
||||
<!-- 模块化脚本文件 -->
|
||||
<script src="js/ui-utils.js"></script>
|
||||
<script src="js/websocket.js"></script>
|
||||
<script src="js/firmware-upgrade.js"></script>
|
||||
<script src="js/script-editor.js"></script>
|
||||
<script src="js/chart.js"></script>
|
||||
|
||||
<script src="js/main.js"></script>
|
||||
|
||||
<!-- 序列号设置模态对话框 -->
|
||||
<div class="modal fade" id="snModal" tabindex="-1" aria-labelledby="snModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="snModalLabel">设置序列号</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="mb-3">
|
||||
<label for="snInput" class="form-label">新序列号</label>
|
||||
<input type="text" class="form-control" id="snInput" placeholder="请输入新的序列号">
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
|
||||
<button type="button" class="btn btn-primary" id="saveSnBtn">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,573 @@
|
||||
// chart.js - 图表功能模块
|
||||
|
||||
const ChartModule = (function() {
|
||||
let daqChart = null;
|
||||
let chartData = {
|
||||
ch1: [],
|
||||
ch2: []
|
||||
};
|
||||
|
||||
function getCurrentSn() {
|
||||
// 从设备信息中获取SN并移除所有空格和所有斜杠
|
||||
return $('#daq_info').text().replace(/\s+/g, '').replace(/\//g, '');
|
||||
}
|
||||
|
||||
// 初始化图表模块
|
||||
function init() {
|
||||
// 初始化图表
|
||||
initChart();
|
||||
|
||||
// 设置拖动和缩放模式切换
|
||||
initZoomControls();
|
||||
|
||||
// 将处理DAQ数据的函数暴露到全局
|
||||
window.handleDaqData = handleDaqData;
|
||||
|
||||
// 添加删除行按钮的事件委托
|
||||
const tbody = document.getElementById('stats_table_body');
|
||||
tbody.addEventListener('click', function(event) {
|
||||
if (event.target.closest('.delete-row')) {
|
||||
const row = event.target.closest('tr');
|
||||
row.remove();
|
||||
}
|
||||
});
|
||||
|
||||
// 绑定功能按钮事件
|
||||
bindFunctionButtons();
|
||||
}
|
||||
|
||||
// 绑定功能按钮事件
|
||||
function bindFunctionButtons() {
|
||||
// 导出CSV
|
||||
document.getElementById('export_csv').addEventListener('click', exportToCSV);
|
||||
|
||||
// 保存到设备
|
||||
document.getElementById('save_data').addEventListener('click', saveDataToDevice);
|
||||
|
||||
// 从本地载入
|
||||
document.getElementById('load_local').addEventListener('click', loadDataFromLocal);
|
||||
|
||||
// 从设备载入
|
||||
document.getElementById('load_device').addEventListener('click', loadDataFromDevice);
|
||||
}
|
||||
|
||||
// 导出数据到CSV文件
|
||||
function exportToCSV() {
|
||||
const table = document.querySelector('#stats_table_body');
|
||||
const rows = table.querySelectorAll('tr');
|
||||
|
||||
// 获取表头
|
||||
const headerRow = document.querySelector('#stats_table_body').previousElementSibling.querySelector('tr');
|
||||
const headers = Array.from(headerRow.querySelectorAll('th')).map(th => {
|
||||
// 移除操作列
|
||||
if (th.textContent.trim() === '操作') return '';
|
||||
return th.textContent.trim();
|
||||
}).filter(h => h);
|
||||
|
||||
// 构建CSV内容
|
||||
let csvContent = 'data:text/csv;charset=utf-8,';
|
||||
csvContent += headers.join(',') + '\n';
|
||||
|
||||
// 添加行数据
|
||||
rows.forEach(row => {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
const rowData = cells.map((cell, index) => {
|
||||
// 跳过操作列
|
||||
if (index === cells.length - 1) return '';
|
||||
return cell.textContent.trim();
|
||||
}).filter(d => d);
|
||||
csvContent += rowData.join(',') + '\n';
|
||||
});
|
||||
|
||||
// 创建下载链接
|
||||
const sn = getCurrentSn();
|
||||
const encodedUri = encodeURI(csvContent);
|
||||
const link = document.createElement('a');
|
||||
link.setAttribute('href', encodedUri);
|
||||
link.setAttribute('download', `daq_stats_${sn}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
// 显示提示
|
||||
UIUtils.showToast('数据已导出为CSV文件');
|
||||
}
|
||||
|
||||
// 保存数据到设备
|
||||
function saveDataToDevice() {
|
||||
const table = document.querySelector('#stats_table_body');
|
||||
const rows = table.querySelectorAll('tr');
|
||||
|
||||
// 收集所有统计数据
|
||||
const statsData = Array.from(rows).map(row => {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
return {
|
||||
time: cells[0].textContent.trim(),
|
||||
dataLength: parseInt(cells[1].textContent.trim()),
|
||||
ch1: {
|
||||
average: parseFloat(cells[2].textContent.trim()),
|
||||
peakToPeak: parseFloat(cells[3].textContent.trim()),
|
||||
snr: parseFloat(cells[4].textContent.trim())
|
||||
},
|
||||
ch2: {
|
||||
average: parseFloat(cells[5].textContent.trim()),
|
||||
peakToPeak: parseFloat(cells[6].textContent.trim()),
|
||||
snr: parseFloat(cells[7].textContent.trim())
|
||||
},
|
||||
channelDiff: parseFloat(cells[8].textContent.trim())
|
||||
};
|
||||
});
|
||||
|
||||
console.log(statsData);
|
||||
// 从设备信息中获取SN并移除空格和/
|
||||
const sn = getCurrentSn();
|
||||
// 生成文件名
|
||||
const filename = `stats_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`;
|
||||
|
||||
// 通过HTTP POST发送数据到设备
|
||||
fetch('/api/stats/save', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sn: sn,
|
||||
filename: filename,
|
||||
stats: statsData
|
||||
})
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
UIUtils.showToast('统计数据已保存到设备');
|
||||
} else {
|
||||
UIUtils.showToast(`保存失败: ${data.message}`, 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
UIUtils.showToast(`保存失败: ${error.message}`, 'error');
|
||||
});
|
||||
|
||||
// 显示提示
|
||||
UIUtils.showToast('正在保存数据到设备...');
|
||||
}
|
||||
|
||||
// 从本地载入数据
|
||||
function loadDataFromLocal() {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = '.csv';
|
||||
|
||||
input.onchange = function(e) {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = function(event) {
|
||||
const csvContent = event.target.result;
|
||||
parseCSVAndLoadData(csvContent);
|
||||
};
|
||||
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
input.click();
|
||||
}
|
||||
|
||||
// 解析CSV并加载数据
|
||||
function parseCSVAndLoadData(csvContent) {
|
||||
const lines = csvContent.split('\n');
|
||||
if (lines.length < 2) {
|
||||
UIUtils.showToast('CSV文件格式错误');
|
||||
return;
|
||||
}
|
||||
|
||||
// 清空现有表格
|
||||
const tbody = document.getElementById('stats_table_body');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
// 收集所有数据行到数组
|
||||
const dataRows = [];
|
||||
|
||||
// 跳过表头行,从数据行开始处理
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
if (!line) continue;
|
||||
|
||||
const cells = line.split(',');
|
||||
if (cells.length < 9) continue;
|
||||
|
||||
// 收集数据行,包含时间和所有单元格
|
||||
dataRows.push({ time: cells[0], cells: cells });
|
||||
}
|
||||
|
||||
// 按时间字符串倒序排列,确保最新数据在前
|
||||
dataRows.sort((a, b) => {
|
||||
if (a.time > b.time) return -1;
|
||||
if (a.time < b.time) return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
// 将排序后的数据行添加到表格
|
||||
dataRows.forEach(row => {
|
||||
const cells = row.cells;
|
||||
|
||||
// 创建新的表格行
|
||||
const newRow = `
|
||||
<tr>
|
||||
<td>${cells[0]}</td>
|
||||
<td>${cells[1]}</td>
|
||||
<td>${cells[2]}</td>
|
||||
<td>${cells[3]}</td>
|
||||
<td>${cells[4]}</td>
|
||||
<td>${cells[5]}</td>
|
||||
<td>${cells[6]}</td>
|
||||
<td>${cells[7]}</td>
|
||||
<td>${cells[8]}</td>
|
||||
<td>
|
||||
<button class="btn btn-danger btn-sm delete-row">
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
// 添加到表格
|
||||
tbody.insertAdjacentHTML('beforeend', newRow);
|
||||
});
|
||||
|
||||
// 显示提示
|
||||
UIUtils.showToast('数据已从本地CSV文件加载');
|
||||
}
|
||||
|
||||
// 从设备载入数据
|
||||
function loadDataFromDevice() {
|
||||
// 通过HTTP GET从设备获取数据
|
||||
const sn = getCurrentSn();
|
||||
fetch('/api/stats/load?sn=' + sn)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
// 清空现有表格
|
||||
const tbody = document.getElementById('stats_table_body');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
// 检查是否有数据,
|
||||
if (!data.data.stats || data.data.stats.length === 0) {
|
||||
UIUtils.showToast('设备上没有统计数据');
|
||||
return;
|
||||
}
|
||||
|
||||
// 按时间字符串倒序排列,确保最新数据在前
|
||||
const sortedStats = data.data.stats.sort((a, b) => {
|
||||
// 比较时间字符串,倒序排列
|
||||
if (a.time > b.time) return -1;
|
||||
if (a.time < b.time) return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
sortedStats.forEach(stat => {
|
||||
const newRow = `
|
||||
<tr>
|
||||
<td>${stat.time}</td>
|
||||
<td>${stat.dataLength}</td>
|
||||
<td>${stat.ch1.average}</td>
|
||||
<td>${stat.ch1.peakToPeak}</td>
|
||||
<td>${stat.ch1.snr}%</td>
|
||||
<td>${stat.ch2.average}</td>
|
||||
<td>${stat.ch2.peakToPeak}</td>
|
||||
<td>${stat.ch2.snr}%</td>
|
||||
<td>${stat.channelDiff}%</td>
|
||||
<td>
|
||||
<button class="btn btn-danger btn-sm delete-row">
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
tbody.insertAdjacentHTML('beforeend', newRow);
|
||||
});
|
||||
|
||||
UIUtils.showToast('统计数据已从设备加载');
|
||||
} else {
|
||||
UIUtils.showToast(`加载失败: ${data.message}`, 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
UIUtils.showToast(`加载失败: ${error.message}`, 'error');
|
||||
});
|
||||
|
||||
// 显示提示
|
||||
UIUtils.showToast('正在从设备加载数据...');
|
||||
}
|
||||
|
||||
// 初始化图表
|
||||
function initChart() {
|
||||
const ctx = document.getElementById('daq_chart').getContext('2d');
|
||||
daqChart = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: [],
|
||||
datasets: [
|
||||
{
|
||||
label: 'CH1',
|
||||
data: [],
|
||||
borderColor: 'rgba(219, 24, 67, 1)',
|
||||
backgroundColor: 'rgba(219, 24, 67, 1)',
|
||||
borderWidth: 1,
|
||||
fill: false,
|
||||
tension: 0,
|
||||
pointRadius: 3,
|
||||
pointBackgroundColor: 'rgba(219, 24, 67, 1)',
|
||||
pointBorderColor: 'rgba(219, 24, 67, 1)',
|
||||
pointHoverRadius: 5,
|
||||
pointHoverBackgroundColor: 'rgba(219, 24, 67, 0.8)',
|
||||
pointHoverBorderColor: 'rgba(219, 24, 67, 1)'
|
||||
},
|
||||
{
|
||||
label: 'CH2',
|
||||
data: [],
|
||||
borderColor: 'rgba(10, 49, 223, 1)',
|
||||
backgroundColor: 'rgba(10, 49, 223, 1)',
|
||||
borderWidth: 1,
|
||||
fill: false,
|
||||
tension: 0,
|
||||
pointRadius: 3,
|
||||
pointBackgroundColor: 'rgba(10, 49, 223, 1)',
|
||||
pointBorderColor: 'rgba(10, 49, 223, 1)',
|
||||
pointHoverRadius: 5,
|
||||
pointHoverBackgroundColor: 'rgba(10, 49, 223, 0.8)',
|
||||
pointHoverBorderColor: 'rgba(10, 49, 223, 1)'
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: '样本点'
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(0, 0, 0, 0.1)'
|
||||
}
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: '数值 (uint16)'
|
||||
},
|
||||
min: 0,
|
||||
max: 65535,
|
||||
grid: {
|
||||
color: 'rgba(0, 0, 0, 0.1)'
|
||||
}
|
||||
}
|
||||
},
|
||||
animation: false,
|
||||
plugins: {
|
||||
zoom: {
|
||||
pan: {
|
||||
enabled: true,
|
||||
mode: 'xy',
|
||||
speed: 10,
|
||||
threshold: 10,
|
||||
scaleMode: 'xy'
|
||||
},
|
||||
zoom: {
|
||||
wheel: {
|
||||
enabled: true,
|
||||
speed: 0.1
|
||||
},
|
||||
drag: {
|
||||
enabled: false,
|
||||
borderColor: 'rgba(255, 255, 255, 0.5)',
|
||||
borderWidth: 1,
|
||||
backgroundColor: 'rgba(225, 225, 225, 0.3)',
|
||||
drawTime: 'beforeDatasetsDraw'
|
||||
},
|
||||
pinch: {
|
||||
enabled: true
|
||||
},
|
||||
mode: 'xy',
|
||||
speed: 0.1,
|
||||
scaleMode: 'xy'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化缩放控制
|
||||
function initZoomControls() {
|
||||
// 重置缩放按钮
|
||||
$('#reset_zoom').on('click', function() {
|
||||
if (daqChart) {
|
||||
daqChart.resetZoom();
|
||||
}
|
||||
});
|
||||
|
||||
// 缩放模式切换按钮
|
||||
$('.zoom-mode-btn').on('click', function() {
|
||||
const mode = $(this).data('mode');
|
||||
|
||||
// 更新按钮状态
|
||||
$('.zoom-mode-btn').removeClass('active');
|
||||
$(this).addClass('active');
|
||||
|
||||
// 更新图表缩放模式
|
||||
if (daqChart) {
|
||||
daqChart.options.plugins.zoom.pan.mode = mode;
|
||||
daqChart.options.plugins.zoom.zoom.mode = mode;
|
||||
daqChart.update('none');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 处理DAQ数据
|
||||
function handleDaqData(daqData) {
|
||||
if (!daqData || !daqData.data) {
|
||||
console.error('无效的DAQ数据格式');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 解析数据
|
||||
const parsedData = parseDaqData(daqData.data);
|
||||
|
||||
// 更新图表数据
|
||||
chartData.ch1 = parsedData.ch1;
|
||||
chartData.ch2 = parsedData.ch2;
|
||||
|
||||
// 更新图表
|
||||
updateChart();
|
||||
|
||||
// 计算并显示统计信息
|
||||
calculateAndDisplayStats(parsedData.ch1, parsedData.ch2);
|
||||
} catch (error) {
|
||||
console.error('解析DAQ数据失败:', error);
|
||||
showToast('解析DAQ数据失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 计算并显示统计信息
|
||||
function calculateAndDisplayStats(ch1Data, ch2Data) {
|
||||
// 计算各通道统计值
|
||||
const ch1Stats = calculateStats(ch1Data);
|
||||
const ch2Stats = calculateStats(ch2Data);
|
||||
|
||||
// 获取当前时间
|
||||
const currentTime = new Date().toLocaleString();
|
||||
|
||||
const diff = Math.abs(ch1Stats.average - ch2Stats.average) / (Math.max(ch1Stats.average, ch2Stats.average) || 1) * 100;
|
||||
|
||||
// 创建新的表格行
|
||||
const newRow = `
|
||||
<tr>
|
||||
<td>${currentTime}</td>
|
||||
<td>${ch1Data.length}</td>
|
||||
<td>${ch1Stats.average.toFixed(0)}</td>
|
||||
<td>${ch1Stats.peakToPeak.toFixed(0)}</td>
|
||||
<td>${ch1Stats.snr.toFixed(0)}%</td>
|
||||
<td>${ch2Stats.average.toFixed(0)}</td>
|
||||
<td>${ch2Stats.peakToPeak.toFixed(0)}</td>
|
||||
<td>${ch2Stats.snr.toFixed(0)}%</td>
|
||||
<td>${diff.toFixed(0)}%</td>
|
||||
<td>
|
||||
<button class="btn btn-danger btn-sm delete-row">
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
// 添加到表格顶部
|
||||
const tbody = document.getElementById('stats_table_body');
|
||||
tbody.insertAdjacentHTML('afterbegin', newRow);
|
||||
|
||||
// 限制表格行数(最多保留100条记录)
|
||||
const maxRows = 100;
|
||||
while (tbody.rows.length > maxRows) {
|
||||
tbody.deleteRow(tbody.rows.length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 计算单通道统计值
|
||||
function calculateStats(data) {
|
||||
if (!data || data.length === 0) {
|
||||
return { average: 0, peakToPeak: 0, snr: 0 };
|
||||
}
|
||||
|
||||
// 计算平均值
|
||||
const sum = data.reduce((acc, val) => acc + val, 0);
|
||||
const average = sum / data.length;
|
||||
|
||||
// 计算峰峰值
|
||||
const max = Math.max(...data);
|
||||
const min = Math.min(...data);
|
||||
const peakToPeak = max - min;
|
||||
|
||||
// 计算信噪比 (SNR)
|
||||
// 简单实现:假设噪声是信号的标准差
|
||||
|
||||
const snr = average === 0 ? 0 : peakToPeak / average * 100;
|
||||
|
||||
return { average, peakToPeak, snr };
|
||||
}
|
||||
|
||||
// ========== DAQ数据处理相关 ==========
|
||||
// 解析base64编码的uint16小端数据
|
||||
function parseDaqData(base64Data) {
|
||||
// 解码base64数据
|
||||
const binaryData = atob(base64Data);
|
||||
const dataView = new DataView(new ArrayBuffer(binaryData.length));
|
||||
|
||||
// 将二进制数据写入DataView
|
||||
for (let i = 0; i < binaryData.length; i++) {
|
||||
dataView.setUint8(i, binaryData.charCodeAt(i));
|
||||
}
|
||||
|
||||
// 解析uint16小端数据
|
||||
const data = [];
|
||||
for (let i = 4; i < binaryData.length; i += 2) { // 跳过前4字节头
|
||||
data.push(dataView.getUint16(i, true)); // true表示小端
|
||||
}
|
||||
|
||||
// 分离CH1和CH2数据
|
||||
const ch1 = [];
|
||||
const ch2 = [];
|
||||
for (let i = 0; i < data.length; i += 2) {
|
||||
ch1.push(data[i]);
|
||||
if (i + 1 < data.length) {
|
||||
ch2.push(data[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
return { ch1, ch2 };
|
||||
}
|
||||
|
||||
// 更新图表
|
||||
function updateChart() {
|
||||
if (!daqChart) {
|
||||
initChart();
|
||||
}
|
||||
|
||||
// 更新标签和数据
|
||||
const labels = chartData.ch1.map((_, index) => index);
|
||||
|
||||
daqChart.data.labels = labels;
|
||||
daqChart.data.datasets[0].data = chartData.ch1;
|
||||
daqChart.data.datasets[1].data = chartData.ch2;
|
||||
|
||||
daqChart.update('none');
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
init: init,
|
||||
updateChart: updateChart
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,261 @@
|
||||
// firmware-upgrade.js - 固件升级模块
|
||||
|
||||
const FirmwareUpgrade = (function() {
|
||||
const CHUNK_SIZE = 4096; // 4KB 分段大小
|
||||
let uploadInProgress = false;
|
||||
let uploadOffset = 0;
|
||||
let uploadFile = null;
|
||||
let fileChecksum = '';
|
||||
|
||||
// 初始化固件升级功能
|
||||
function init() {
|
||||
// 文件选择事件
|
||||
$('#firmwareFile').on('change', handleFileSelect);
|
||||
|
||||
// 开始上传按钮点击事件
|
||||
$('#startUpload').on('click', handleStartUpload);
|
||||
|
||||
// 取消上传按钮点击事件
|
||||
$('#cancelUpload').on('click', handleCancelUpload);
|
||||
|
||||
// 执行升级按钮点击事件
|
||||
$('#upgradeFirmware').on('click', handleUpgradeFirmware);
|
||||
}
|
||||
|
||||
// 处理文件选择
|
||||
function handleFileSelect(e) {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
// 验证文件类型
|
||||
if (!file.name.endsWith('.bin')) {
|
||||
showToast('请选择.bin格式的固件文件');
|
||||
$(this).val('');
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示文件信息
|
||||
$('#fileName').text(file.name);
|
||||
$('#fileSize').text(formatFileSize(file.size));
|
||||
|
||||
// 计算校验和
|
||||
calculateFileChecksum(file);
|
||||
|
||||
// 重置状态
|
||||
uploadOffset = 0;
|
||||
uploadFile = file;
|
||||
$('#uploadProgress').css('width', '0%').text('0%').attr('aria-valuenow', 0);
|
||||
$('#startUpload').prop('disabled', true);
|
||||
$('#upgradeFirmware').prop('disabled', true);
|
||||
}
|
||||
|
||||
// 计算文件校验和
|
||||
function calculateFileChecksum(file) {
|
||||
$('#fileChecksum').text('计算中...');
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = function(e) {
|
||||
const arrayBuffer = e.target.result;
|
||||
const checksum = calculateChecksum(arrayBuffer);
|
||||
fileChecksum = checksum;
|
||||
$('#fileChecksum').text(checksum);
|
||||
|
||||
// 启用上传按钮
|
||||
$('#startUpload').prop('disabled', false);
|
||||
};
|
||||
reader.onerror = function() {
|
||||
$('#fileChecksum').text('计算失败');
|
||||
showToast('文件校验和计算失败');
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
}
|
||||
|
||||
// 计算校验和的函数
|
||||
function calculateChecksum(arrayBuffer) {
|
||||
let checksum = 0;
|
||||
const dataView = new DataView(arrayBuffer);
|
||||
|
||||
// 对每个字节进行累加,32位
|
||||
for (let i = 0; i < dataView.byteLength; i++) {
|
||||
checksum = (checksum + dataView.getUint8(i)) & 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
// 转换为十六进制字符串,确保8位
|
||||
return checksum.toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
// 格式化文件大小
|
||||
function formatFileSize(bytes) {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
|
||||
else return (bytes / 1048576).toFixed(2) + ' MB';
|
||||
}
|
||||
|
||||
// 处理开始上传
|
||||
function handleStartUpload() {
|
||||
if (!uploadFile) return;
|
||||
|
||||
$('#startUpload').prop('disabled', true);
|
||||
$('#cancelUpload').prop('disabled', false);
|
||||
uploadInProgress = true;
|
||||
|
||||
// 清空日志
|
||||
$('#upgradeLog').text('开始上传固件...\n');
|
||||
|
||||
// 开始分段上传
|
||||
uploadOffset = 0;
|
||||
uploadNextChunk();
|
||||
}
|
||||
|
||||
// 处理取消上传
|
||||
function handleCancelUpload() {
|
||||
uploadInProgress = false;
|
||||
$(this).prop('disabled', true);
|
||||
|
||||
// 发送取消请求
|
||||
$.ajax({
|
||||
url: '/api/firmware/cancel',
|
||||
type: 'POST',
|
||||
success: function() {
|
||||
showToast('固件上传已取消');
|
||||
$('#upgradeLog').append('上传已取消\n');
|
||||
},
|
||||
error: function() {
|
||||
showToast('取消上传失败');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 处理执行升级
|
||||
function handleUpgradeFirmware() {
|
||||
$(this).prop('disabled', true);
|
||||
$('#upgradeLog').append('开始执行固件升级...\n');
|
||||
|
||||
$.ajax({
|
||||
url: '/api/firmware/upgrade',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
$('#upgradeLog').append('固件升级成功!\n');
|
||||
$('#upgradeLog').append('设备将在1秒后重启...\n');
|
||||
showToast('固件升级成功,设备将在1秒后重启');
|
||||
} else {
|
||||
$('#upgradeLog').append('升级失败:' + response.message + '\n');
|
||||
showToast('固件升级失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
let message = '升级请求失败';
|
||||
if (xhr.responseJSON && xhr.responseJSON.message) {
|
||||
message = xhr.responseJSON.message;
|
||||
}
|
||||
$('#upgradeLog').append('升级失败:' + message + '\n');
|
||||
showToast('固件升级失败:' + message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 上传下一个文件块
|
||||
function uploadNextChunk() {
|
||||
if (!uploadInProgress || !uploadFile) return;
|
||||
|
||||
// 计算当前块的开始和结束位置
|
||||
const start = uploadOffset;
|
||||
const end = Math.min(start + CHUNK_SIZE, uploadFile.size);
|
||||
const chunk = uploadFile.slice(start, end);
|
||||
|
||||
// 读取块内容并转换为Base64
|
||||
const reader = new FileReader();
|
||||
reader.onload = function(e) {
|
||||
const chunkData = e.target.result;
|
||||
const base64Data = btoa(chunkData);
|
||||
|
||||
// 发送上传请求
|
||||
$.ajax({
|
||||
url: '/api/firmware/upload',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
content: base64Data,
|
||||
offset: start,
|
||||
final: end >= uploadFile.size
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
uploadOffset = response.offset;
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.min(Math.round((uploadOffset / uploadFile.size) * 100), 100);
|
||||
$('#uploadProgress').css('width', progress + '%').text(progress + '%').attr('aria-valuenow', progress);
|
||||
|
||||
// 检查是否完成
|
||||
if (response.final || uploadOffset >= uploadFile.size) {
|
||||
$('#upgradeLog').append('固件上传完成!\n');
|
||||
$('#upgradeLog').append('正在验证固件...\n');
|
||||
|
||||
// 验证固件
|
||||
verifyFirmware();
|
||||
} else {
|
||||
// 继续上传下一块
|
||||
setTimeout(uploadNextChunk, 100); // 添加小延迟,避免请求过于频繁
|
||||
}
|
||||
} else {
|
||||
throw new Error(response.message || '上传失败');
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
let message = '上传失败';
|
||||
if (xhr.responseJSON && xhr.responseJSON.message) {
|
||||
message = xhr.responseJSON.message;
|
||||
}
|
||||
$('#upgradeLog').append('上传失败:' + message + '\n');
|
||||
showToast('固件上传失败:' + message);
|
||||
uploadInProgress = false;
|
||||
$('#cancelUpload').prop('disabled', true);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
reader.readAsBinaryString(chunk);
|
||||
}
|
||||
|
||||
// 验证固件
|
||||
function verifyFirmware() {
|
||||
$.ajax({
|
||||
url: '/api/firmware/verify',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
checksum: fileChecksum,
|
||||
size: uploadFile.size
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
$('#upgradeLog').append('固件验证成功!\n');
|
||||
$('#upgradeLog').append('可以点击"执行升级"按钮进行升级\n');
|
||||
$('#upgradeFirmware').prop('disabled', false);
|
||||
$('#cancelUpload').prop('disabled', true);
|
||||
showToast('固件上传完成并通过验证');
|
||||
} else {
|
||||
throw new Error(response.message || '验证失败');
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
let message = '验证失败';
|
||||
if (xhr.responseJSON && xhr.responseJSON.message) {
|
||||
message = xhr.responseJSON.message;
|
||||
}
|
||||
$('#upgradeLog').append('验证失败:' + message + '\n');
|
||||
showToast('固件验证失败:' + message);
|
||||
$('#cancelUpload').prop('disabled', true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
init: init
|
||||
};
|
||||
})();
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Minified by jsDelivr using Terser v5.15.1.
|
||||
* Original file: /npm/js-base64@3.7.5/base64.js
|
||||
*
|
||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||
*/
|
||||
!function(t,n){var r,e;"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(r=t.Base64,(e=n()).noConflict=function(){return t.Base64=r,e},t.Meteor&&(Base64=e),t.Base64=e)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,(function(){"use strict";var t,n="3.7.5",r="function"==typeof atob,e="function"==typeof btoa,o="function"==typeof Buffer,u="function"==typeof TextDecoder?new TextDecoder:void 0,i="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),c=(t={},f.forEach((function(n,r){return t[n]=r})),t),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,d=String.fromCharCode.bind(String),s="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){return new Uint8Array(Array.prototype.slice.call(t,0))},l=function(t){return t.replace(/=/g,"").replace(/[+\/]/g,(function(t){return"+"==t?"-":"_"}))},h=function(t){return t.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(t){for(var n,r,e,o,u="",i=t.length%3,c=0;c<t.length;){if((r=t.charCodeAt(c++))>255||(e=t.charCodeAt(c++))>255||(o=t.charCodeAt(c++))>255)throw new TypeError("invalid character found");u+=f[(n=r<<16|e<<8|o)>>18&63]+f[n>>12&63]+f[n>>6&63]+f[63&n]}return i?u.slice(0,i-3)+"===".substring(i):u},y=e?function(t){return btoa(t)}:o?function(t){return Buffer.from(t,"binary").toString("base64")}:p,A=o?function(t){return Buffer.from(t).toString("base64")}:function(t){for(var n=[],r=0,e=t.length;r<e;r+=4096)n.push(d.apply(null,t.subarray(r,r+4096)));return y(n.join(""))},b=function(t,n){return void 0===n&&(n=!1),n?l(A(t)):A(t)},g=function(t){if(t.length<2)return(n=t.charCodeAt(0))<128?t:n<2048?d(192|n>>>6)+d(128|63&n):d(224|n>>>12&15)+d(128|n>>>6&63)+d(128|63&n);var n=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return d(240|n>>>18&7)+d(128|n>>>12&63)+d(128|n>>>6&63)+d(128|63&n)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,x=function(t){return t.replace(B,g)},C=o?function(t){return Buffer.from(t,"utf8").toString("base64")}:i?function(t){return A(i.encode(t))}:function(t){return y(x(t))},m=function(t,n){return void 0===n&&(n=!1),n?l(C(t)):C(t)},v=function(t){return m(t,!0)},U=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,F=function(t){switch(t.length){case 4:var n=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return d(55296+(n>>>10))+d(56320+(1023&n));case 3:return d((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return d((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},w=function(t){return t.replace(U,F)},S=function(t){if(t=t.replace(/\s+/g,""),!a.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(3&t.length));for(var n,r,e,o="",u=0;u<t.length;)n=c[t.charAt(u++)]<<18|c[t.charAt(u++)]<<12|(r=c[t.charAt(u++)])<<6|(e=c[t.charAt(u++)]),o+=64===r?d(n>>16&255):64===e?d(n>>16&255,n>>8&255):d(n>>16&255,n>>8&255,255&n);return o},E=r?function(t){return atob(h(t))}:o?function(t){return Buffer.from(t,"base64").toString("binary")}:S,D=o?function(t){return s(Buffer.from(t,"base64"))}:function(t){return s(E(t).split("").map((function(t){return t.charCodeAt(0)})))},R=function(t){return D(T(t))},z=o?function(t){return Buffer.from(t,"base64").toString("utf8")}:u?function(t){return u.decode(D(t))}:function(t){return w(E(t))},T=function(t){return h(t.replace(/[-_]/g,(function(t){return"-"==t?"+":"/"})))},Z=function(t){return z(T(t))},j=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}},I=function(){var t=function(t,n){return Object.defineProperty(String.prototype,t,j(n))};t("fromBase64",(function(){return Z(this)})),t("toBase64",(function(t){return m(this,t)})),t("toBase64URI",(function(){return m(this,!0)})),t("toBase64URL",(function(){return m(this,!0)})),t("toUint8Array",(function(){return R(this)}))},O=function(){var t=function(t,n){return Object.defineProperty(Uint8Array.prototype,t,j(n))};t("toBase64",(function(t){return b(this,t)})),t("toBase64URI",(function(){return b(this,!0)})),t("toBase64URL",(function(){return b(this,!0)}))},P={version:n,VERSION:"3.7.5",atob:E,atobPolyfill:S,btoa:y,btoaPolyfill:p,fromBase64:Z,toBase64:m,encode:m,encodeURI:v,encodeURL:v,utob:x,btou:w,decode:Z,isValid:function(t){if("string"!=typeof t)return!1;var n=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(n)||!/[^\s0-9a-zA-Z\-_]/.test(n)},fromUint8Array:b,toUint8Array:R,extendString:I,extendUint8Array:O,extendBuiltins:function(){I(),O()},Base64:{}};return Object.keys(P).forEach((function(t){return P.Base64[t]=P[t]})),P}));
|
||||
//# sourceMappingURL=/sm/555281732ed54ee1693a772f485329378d8ea5052ffa4370e9c2e9947eb42d22.map
|
||||
File diff suppressed because one or more lines are too long
+13
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
+7
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],t):t(CodeMirror)}(function(m){"use strict";var l={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var a={};function d(t,e){e=t.match(a[e=e]||(a[e]=new RegExp("\\s+"+e+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return e?/^\s*(.*?)\s*$/.exec(e[2])[1]:""}function g(t,e){return new RegExp((e?"^":"")+"</\\s*"+t+"\\s*>","i")}function o(t,e){for(var a in t)for(var n=e[a]||(e[a]=[]),l=t[a],o=l.length-1;0<=o;o--)n.unshift(l[o])}m.defineMode("htmlmixed",function(i,t){var c=m.getMode(i,{name:"xml",htmlMode:!0,multilineTagIndentFactor:t.multilineTagIndentFactor,multilineTagIndentPastTag:t.multilineTagIndentPastTag,allowMissingTagName:t.allowMissingTagName}),s={},e=t&&t.tags,a=t&&t.scriptTypes;if(o(l,s),e&&o(e,s),a)for(var n=a.length-1;0<=n;n--)s.script.unshift(["type",a[n].matches,a[n].mode]);function u(t,e){var a,o,r,n=c.token(t,e.htmlState),l=/\btag\b/.test(n);return l&&!/[<>\s\/]/.test(t.current())&&(a=e.htmlState.tagName&&e.htmlState.tagName.toLowerCase())&&s.hasOwnProperty(a)?e.inTag=a+" ":e.inTag&&l&&/>$/.test(t.current())?(a=/^([\S]+) (.*)/.exec(e.inTag),e.inTag=null,l=">"==t.current()&&function(t,e){for(var a=0;a<t.length;a++){var n=t[a];if(!n[0]||n[1].test(d(e,n[0])))return n[2]}}(s[a[1]],a[2]),l=m.getMode(i,l),o=g(a[1],!0),r=g(a[1],!1),e.token=function(t,e){return t.match(o,!1)?(e.token=u,e.localState=e.localMode=null):(a=t,n=r,l=e.localMode.token(t,e.localState),t=a.current(),-1<(e=t.search(n))?a.backUp(t.length-e):t.match(/<\/?$/)&&(a.backUp(t.length),a.match(n,!1)||a.match(t)),l);var a,n,l},e.localMode=l,e.localState=m.startState(l,c.indent(e.htmlState,"",""))):e.inTag&&(e.inTag+=t.current(),t.eol()&&(e.inTag+=" ")),n}return{startState:function(){return{token:u,inTag:null,localMode:null,localState:null,htmlState:m.startState(c)}},copyState:function(t){var e;return t.localState&&(e=m.copyState(t.localMode,t.localState)),{token:t.token,inTag:t.inTag,localMode:t.localMode,localState:e,htmlState:m.copyState(c,t.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(t,e,a){return!t.localMode||/^\s*<\//.test(e)?c.indent(t.htmlState,e,a):t.localMode.indent?t.localMode.indent(t.localState,e,a):m.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||c}}}},"xml","javascript","css"),m.defineMIME("text/html","htmlmixed")});
|
||||
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){"use strict";s.defineMode("shell",function(){var o={};function e(e,t){for(var n=0;n<t.length;n++)o[t[n]]=e}var t=["true","false"],n=["if","then","do","else","elif","while","until","for","in","esac","fi","fin","fil","done","exit","set","unset","export","function"],r=["ab","awk","bash","beep","cat","cc","cd","chown","chmod","chroot","clear","cp","curl","cut","diff","echo","find","gawk","gcc","get","git","grep","hg","kill","killall","ln","ls","make","mkdir","openssl","mv","nc","nl","node","npm","ping","ps","restart","rm","rmdir","sed","service","sh","shopt","shred","source","sort","sleep","ssh","start","stop","su","sudo","svn","tee","telnet","top","touch","vi","vim","wall","wc","wget","who","write","yes","zsh"];function i(e,t){if(e.eatSpace())return null;var n,r=e.sol(),i=e.next();if("\\"===i)return e.next(),null;if("'"===i||'"'===i||"`"===i)return t.tokens.unshift(f(i,"`"===i?"quote":"string")),l(e,t);if("#"===i)return r&&e.eat("!")?(e.skipToEnd(),"meta"):(e.skipToEnd(),"comment");if("$"===i)return t.tokens.unshift(u),l(e,t);if("+"===i||"="===i)return"operator";if("-"===i)return e.eat("-"),e.eatWhile(/\w/),"attribute";if("<"==i){if(e.match("<<"))return"operator";r=e.match(/^<-?\s*['"]?([^'"]*)['"]?/);if(r)return t.tokens.unshift((n=r[1],function(e,t){return e.sol()&&e.string==n&&t.tokens.shift(),e.skipToEnd(),"string-2"})),"string-2"}if(/\d/.test(i)&&(e.eatWhile(/\d/),e.eol()||!/\w/.test(e.peek())))return"number";e.eatWhile(/[\w-]/);i=e.current();return"="===e.peek()&&/\w+/.test(i)?"def":o.hasOwnProperty(i)?o[i]:null}function f(i,o){var s="("==i?")":"{"==i?"}":i;return function(e,t){for(var n,r=!1;null!=(n=e.next());){if(n===s&&!r){t.tokens.shift();break}if("$"===n&&!r&&"'"!==i&&e.peek()!=s){r=!0,e.backUp(1),t.tokens.unshift(u);break}if(!r&&i!==s&&n===i)return t.tokens.unshift(f(i,o)),l(e,t);if(!r&&/['"]/.test(n)&&!/['"]/.test(i)){t.tokens.unshift(function(n,r){return function(e,t){return t.tokens[0]=f(n,r),e.next(),l(e,t)}}(n,"string")),e.backUp(1);break}r=!r&&"\\"===n}return o}}s.registerHelper("hintWords","shell",t.concat(n,r)),e("atom",t),e("keyword",n),e("builtin",r);var u=function(e,t){1<t.tokens.length&&e.eat("$");var n=e.next();return/['"({]/.test(n)?(t.tokens[0]=f(n,"("==n?"quote":"{"==n?"def":"string"),l(e,t)):(/\d/.test(n)||e.eatWhile(/\w/),t.tokens.shift(),"def")};function l(e,t){return(t.tokens[0]||i)(e,t)}return{startState:function(){return{tokens:[]}},token:l,closeBrackets:"()[]{}''\"\"``",lineComment:"#",fold:"brace"}}),s.defineMIME("text/x-sh","shell"),s.defineMIME("application/x-sh","shell")});
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
$(document).ready(function() {
|
||||
// 初始化所有模块
|
||||
UIUtils.init();
|
||||
WebSocketManager.init();
|
||||
FirmwareUpgrade.init();
|
||||
ScriptEditor.init();
|
||||
ChartModule.init();
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
// script-editor.js - 脚本编辑器模块
|
||||
|
||||
const ScriptEditor = (function() {
|
||||
let scriptTabInited = false;
|
||||
let editor = null;
|
||||
|
||||
// 初始化脚本编辑器功能
|
||||
function init() {
|
||||
// 监听标签页切换事件
|
||||
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', handleTabShown);
|
||||
}
|
||||
|
||||
// 处理标签页显示事件
|
||||
function handleTabShown(e) {
|
||||
console.log('tab shown', e);
|
||||
const target = $(e.target).attr('data-bs-target');
|
||||
|
||||
// 初始化脚本编辑器
|
||||
if (target === '#script' && !scriptTabInited) {
|
||||
initCodeMirror();
|
||||
initFileTree();
|
||||
|
||||
// 保存文件 - 分段写入
|
||||
$('#saveFile').click(function() {
|
||||
const path = $('#currentFile').text();
|
||||
const fullContent = editor.getValue();
|
||||
const chunkSize = 4096; // 4K 分段
|
||||
const totalSize = fullContent.length;
|
||||
const totalChunks = Math.ceil(totalSize / chunkSize);
|
||||
let currentChunk = 0;
|
||||
let currentOffset = 0;
|
||||
|
||||
showToast('正在保存文件...');
|
||||
|
||||
// 分段写入函数
|
||||
function writeChunk(offset) {
|
||||
if (offset >= totalSize) {
|
||||
// 所有分块写入完成,请求服务器进行最终校验和重命名
|
||||
$.ajax({
|
||||
url: '/api/script/write/finalize',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
total_size: totalSize
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('文件保存成功,但最终校验失败:' + response.message);
|
||||
console.warn('文件校验失败,但内容可能已保存:', response.message);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
// 即使最终校验请求失败,我们仍然告知用户文件已保存
|
||||
// 因为分块已经写入,只是可能没有进行最后的重命名和校验
|
||||
showToast('文件内容已保存,但最终处理请求失败');
|
||||
console.warn('最终处理请求失败');
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取当前分块内容
|
||||
const chunkContent = fullContent.substring(offset, offset + chunkSize);
|
||||
// 使用js-base64库编码
|
||||
const encodedContent = Base64.encode(chunkContent);
|
||||
const isFinal = offset + chunkSize >= totalSize;
|
||||
|
||||
// 更新进度
|
||||
currentChunk++;
|
||||
const progress = Math.min(100, Math.round((currentChunk / totalChunks) * 100));
|
||||
showToast('正在保存文件... (' + progress + '%)');
|
||||
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: encodedContent,
|
||||
offset: offset,
|
||||
final: isFinal
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
// 继续写入下一个分块
|
||||
setTimeout(function() {
|
||||
writeChunk(response.offset);
|
||||
}, 10); // 短暂延迟,避免请求过于密集
|
||||
} else {
|
||||
showToast('保存文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
console.log('分段写入失败:', textStatus, errorThrown);
|
||||
// 如果分段写入失败,尝试使用旧的一次性写入方式作为降级方案
|
||||
console.log('分段写入失败,尝试一次性写入');
|
||||
const fullEncodedContent = Base64.encode(fullContent);
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: fullEncodedContent
|
||||
}),
|
||||
success: function(backupResponse) {
|
||||
if (backupResponse.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('保存文件失败:' + backupResponse.message);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showToast('保存文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 开始写入第一个分块
|
||||
writeChunk(0);
|
||||
});
|
||||
|
||||
// 删除文件
|
||||
$('#deleteFile').click(function() {
|
||||
if (confirm('确定要删除这个文件吗?')) {
|
||||
const path = $('#currentFile').text();
|
||||
$.ajax({
|
||||
url: '/api/script/delete',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件删除成功');
|
||||
$('#currentFile').text('未选择文件');
|
||||
editor.setValue('');
|
||||
$('#saveFile, #deleteFile').prop('disabled', true);
|
||||
$('#fileTree').jstree('refresh');
|
||||
} else {
|
||||
showToast('删除文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('删除文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 刷新文件树
|
||||
$('#refreshTree').click(function() {
|
||||
console.log('刷新文件树');
|
||||
$('#fileTree').jstree('refresh');
|
||||
});
|
||||
|
||||
scriptTabInited = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 初始化CodeMirror编辑器
|
||||
function initCodeMirror() {
|
||||
// 初始化CodeMirror
|
||||
editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
|
||||
mode: 'text/x-python',
|
||||
theme: 'monokai',
|
||||
lineNumbers: true,
|
||||
indentUnit: 4,
|
||||
lineWrapping: true,
|
||||
matchBrackets: true,
|
||||
autoCloseBrackets: true
|
||||
});
|
||||
|
||||
editor.setValue("请选择一个文件");
|
||||
}
|
||||
|
||||
// 初始化文件树
|
||||
function initFileTree() {
|
||||
// 初始化文件树
|
||||
$('#fileTree').jstree({
|
||||
'core': {
|
||||
'data': {
|
||||
'url': function(node) {
|
||||
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||
return url;
|
||||
},
|
||||
'data': function(node) {
|
||||
return { 'id': node.id };
|
||||
},
|
||||
'dataFilter': function(data) {
|
||||
var json = {};
|
||||
try {
|
||||
json = JSON.parse(data);
|
||||
} catch (e) {
|
||||
return "[]";
|
||||
}
|
||||
if (json.success && Array.isArray(json.data)) {
|
||||
return JSON.stringify(json.data);
|
||||
}
|
||||
return "[]";
|
||||
},
|
||||
'error': function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件列表失败:' + textStatus);
|
||||
}
|
||||
},
|
||||
'themes': {
|
||||
'name': 'default',
|
||||
'responsive': true
|
||||
},
|
||||
'check_callback': true,
|
||||
'multiple': false
|
||||
},
|
||||
'types': {
|
||||
'default': {
|
||||
'icon': 'bi bi-file-text'
|
||||
},
|
||||
'folder': {
|
||||
'icon': 'bi bi-folder'
|
||||
},
|
||||
'python': {
|
||||
'icon': 'bi bi-filetype-py'
|
||||
},
|
||||
'json': {
|
||||
'icon': 'bi bi-filetype-json'
|
||||
},
|
||||
'shell': {
|
||||
'icon': 'bi bi-filetype-sh'
|
||||
}
|
||||
},
|
||||
'plugins': ['types']
|
||||
}).on('ready.jstree', function() {
|
||||
// 文件树初始化完成
|
||||
});
|
||||
|
||||
// 文件树节点点击事件
|
||||
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||
const node = data.node;
|
||||
if (node.original.type != 'folder') {
|
||||
loadFile(node.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 加载文件内容 - 分段读取
|
||||
function loadFile(path) {
|
||||
// 先清空编辑器
|
||||
editor.setValue("");
|
||||
$('#currentFile').text(path);
|
||||
showToast('正在加载文件...');
|
||||
|
||||
// 首先获取文件信息
|
||||
$.get('/api/script/info?path=' + encodeURIComponent(path), function(infoResponse) {
|
||||
if (infoResponse.success) {
|
||||
const fileSize = infoResponse.size;
|
||||
const chunkSize = 4096; // 4K 分段
|
||||
let totalChunks = Math.ceil(fileSize / chunkSize);
|
||||
let loadedChunks = 0;
|
||||
let fileContent = '';
|
||||
|
||||
// 显示加载进度
|
||||
showToast('正在加载文件... (0%)');
|
||||
|
||||
// 分段读取函数
|
||||
function readChunk(offset) {
|
||||
if (offset >= fileSize) {
|
||||
// 所有分块读取完成
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
switch(ext) {
|
||||
case 'py':
|
||||
editor.setOption('mode', 'text/x-python');
|
||||
break;
|
||||
case 'json':
|
||||
editor.setOption('mode', 'application/json');
|
||||
break;
|
||||
case 'sh':
|
||||
editor.setOption('mode', 'text/x-sh');
|
||||
break;
|
||||
case 'html':
|
||||
editor.setOption('mode', 'text/html');
|
||||
break;
|
||||
case 'js':
|
||||
editor.setOption('mode', 'javascript');
|
||||
break;
|
||||
case 'css':
|
||||
editor.setOption('mode', 'css');
|
||||
break;
|
||||
default:
|
||||
editor.setOption('mode', 'text/plain');
|
||||
}
|
||||
// 设置编辑器内容
|
||||
editor.setValue(fileContent);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载完成');
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取当前分块
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path) + '&offset=' + offset + '&size=' + chunkSize, function(chunkResponse) {
|
||||
if (chunkResponse.success) {
|
||||
// 使用js-base64库解码
|
||||
const chunkContent = Base64.decode(chunkResponse.data);
|
||||
fileContent += chunkContent;
|
||||
loadedChunks++;
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.round((loadedChunks / totalChunks) * 100);
|
||||
if (progress % 20 === 0 || progress === 100) {
|
||||
showToast('正在加载文件... (' + progress + '%)');
|
||||
}
|
||||
|
||||
// 读取下一个分块
|
||||
readChunk(offset + chunkSize);
|
||||
} else {
|
||||
showToast('加载文件失败:' + chunkResponse.message);
|
||||
}
|
||||
}).fail(function() {
|
||||
showToast('加载文件失败:网络错误');
|
||||
});
|
||||
}
|
||||
|
||||
// 开始读取第一个分块
|
||||
readChunk(0);
|
||||
} else {
|
||||
showToast('获取文件信息失败:' + infoResponse.message);
|
||||
}
|
||||
}).fail(function() {
|
||||
showToast('获取文件信息失败:网络错误');
|
||||
});
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
init: init
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,109 @@
|
||||
// ui-utils.js - UI工具函数模块
|
||||
|
||||
const UIUtils = (function() {
|
||||
let toast;
|
||||
|
||||
// 初始化UI工具
|
||||
function init() {
|
||||
// 初始化Toast
|
||||
initToast();
|
||||
|
||||
// 初始化设备控制按钮
|
||||
initDeviceControls();
|
||||
}
|
||||
|
||||
// 初始化Toast通知
|
||||
function initToast() {
|
||||
const toastEl = document.getElementById('toast');
|
||||
toast = new bootstrap.Toast(toastEl, {
|
||||
autohide: true,
|
||||
delay: 3000
|
||||
});
|
||||
}
|
||||
|
||||
// 显示Toast通知
|
||||
function showToast(message) {
|
||||
$('.toast-body').text(message);
|
||||
toast.show();
|
||||
}
|
||||
|
||||
// 初始化设备控制按钮
|
||||
function initDeviceControls() {
|
||||
// 设备重启按钮
|
||||
$('#reboot').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/device/reboot',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// DAQ控制按钮
|
||||
$('#start_daq').click(function() {
|
||||
WebSocketManager.publish(WebSocketManager.topic_daq_control, {
|
||||
cmd: 'start',
|
||||
len: parseInt($('#daq_duration').val())
|
||||
});
|
||||
});
|
||||
|
||||
$('#stop_daq').click(function() {
|
||||
WebSocketManager.publish(WebSocketManager.topic_daq_control, {
|
||||
cmd: 'stop'
|
||||
});
|
||||
});
|
||||
|
||||
// 序列号设置功能
|
||||
$('#daq_info').dblclick(function() {
|
||||
// 获取当前序列号
|
||||
const currentSn = $(this).text().trim() || '';
|
||||
// 设置输入框的值
|
||||
$('#snInput').val(currentSn);
|
||||
// 显示模态对话框
|
||||
const snModal = new bootstrap.Modal(document.getElementById('snModal'));
|
||||
snModal.show();
|
||||
});
|
||||
|
||||
// 保存序列号按钮点击事件
|
||||
$('#saveSnBtn').click(function() {
|
||||
// 获取输入的序列号
|
||||
const newSn = $('#snInput').val().trim();
|
||||
if (newSn === '') {
|
||||
showToast('序列号不能为空');
|
||||
return;
|
||||
}
|
||||
|
||||
// 通过WebSocket发送设置序列号命令
|
||||
WebSocketManager.publish(WebSocketManager.topic_daq_control, {
|
||||
cmd: 'daq_set_sn',
|
||||
sn: newSn
|
||||
});
|
||||
|
||||
// 关闭模态对话框
|
||||
const snModal = bootstrap.Modal.getInstance(document.getElementById('snModal'));
|
||||
snModal.hide();
|
||||
|
||||
// 显示保存成功提示
|
||||
showToast('序列号设置命令已发送');
|
||||
});
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
init: init,
|
||||
showToast: showToast
|
||||
};
|
||||
})();
|
||||
|
||||
// 为了兼容旧代码,将showToast函数添加到全局作用域
|
||||
window.showToast = function(message) {
|
||||
UIUtils.showToast(message);
|
||||
};
|
||||
@@ -0,0 +1,172 @@
|
||||
// websocket.js - WebSocket通信模块
|
||||
|
||||
const WebSocketManager = (function() {
|
||||
// DAQ相关的topic
|
||||
const topic_daq_control = '/dev/daq/control';
|
||||
const topic_daq_data = '/dev/daq/data';
|
||||
const topic_daq_status = '/dev/daq/status';
|
||||
|
||||
// WebSocket客户端配置
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsHost = location.hostname + (location.port ? ':' + location.port : '');
|
||||
const wsuri = wsProtocol + '//' + wsHost + '/ws';
|
||||
console.log('WebSocket连接URL:', wsuri);
|
||||
|
||||
let ws;
|
||||
let reconnectTimer;
|
||||
let status_str = '';
|
||||
|
||||
// 初始化WebSocket连接
|
||||
function init() {
|
||||
connectWebSocket();
|
||||
|
||||
// 定期检查连接状态(每10秒)
|
||||
setInterval(monitorConnection, 10000);
|
||||
|
||||
// 页面关闭前关闭WebSocket连接
|
||||
$(window).on('beforeunload', function() {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 建立WebSocket连接
|
||||
function connectWebSocket() {
|
||||
console.log('WebSocket URI:', wsuri);
|
||||
ws = new WebSocket(wsuri);
|
||||
|
||||
ws.onopen = function() {
|
||||
showToast('已连接到WebSocket服务器');
|
||||
// 订阅DAQ相关的主题
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_daq_status }));
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_daq_data }));
|
||||
// 清除重连定时器
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
handleMessage(event);
|
||||
};
|
||||
|
||||
ws.onerror = function(error) {
|
||||
console.error('WebSocket错误:', error);
|
||||
showToast('WebSocket连接错误: ' + (error.message || '未知错误'));
|
||||
};
|
||||
|
||||
ws.onclose = function(event) {
|
||||
console.log('WebSocket关闭原因:', event.code, event.reason);
|
||||
showToast('WebSocket连接已关闭,正在尝试重连... 代码: ' + event.code + ', 原因: ' + event.reason);
|
||||
// 仅在没有活跃定时器时创建新的重连定时器
|
||||
if (!reconnectTimer) {
|
||||
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||
}
|
||||
};
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
// 处理WebSocket消息
|
||||
function handleMessage(event) {
|
||||
let data;
|
||||
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
return;
|
||||
}
|
||||
|
||||
const topic = data.topic;
|
||||
const message = data.message;
|
||||
|
||||
if (topic && message) {
|
||||
if (topic.startsWith(topic_daq_data)) {
|
||||
try {
|
||||
const daqData = typeof message === 'string' ? JSON.parse(message) : message;
|
||||
// 处理DAQ数据
|
||||
if (window.handleDaqData) {
|
||||
window.handleDaqData(daqData);
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('解析DAQ数据失败: ' + e.message);
|
||||
}
|
||||
} else if (topic.startsWith(topic_daq_status)) {
|
||||
try {
|
||||
const daqStatus = typeof message === 'string' ? JSON.parse(message) : message;
|
||||
// 更新DAQ状态
|
||||
updateDaqStatus(daqStatus);
|
||||
} catch (e) {
|
||||
showToast('解析DAQ状态消息失败: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 更新DAQ状态
|
||||
function updateDaqStatus(daqStatus) {
|
||||
status_str = '';
|
||||
if (!daqStatus.online) {
|
||||
status_str += '采集板通讯异常';
|
||||
} else {
|
||||
if (daqStatus.run) {
|
||||
status_str += '采集中 ';
|
||||
} else {
|
||||
status_str += '停止采集 ';
|
||||
}
|
||||
if (daqStatus.temp) {
|
||||
daqStatus.temp = daqStatus.temp / 10.0;
|
||||
status_str += '温度:' + daqStatus.temp.toFixed(1) + '℃ ';
|
||||
}
|
||||
if (daqStatus.info) {
|
||||
$('#daq_info').text(daqStatus.info.date + '-' + daqStatus.info.sn);
|
||||
if (daqStatus.info.version) {
|
||||
$('#currentVersion').text(daqStatus.info.version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$('#daq_status').text(status_str || '--');
|
||||
}
|
||||
|
||||
// 监控连接状态
|
||||
function monitorConnection() {
|
||||
if (!ws || ws.readyState === WebSocket.CLOSED) {
|
||||
showToast('定期检查发现连接已关闭,尝试重连...');
|
||||
if (!reconnectTimer) {
|
||||
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 发布消息到WebSocket
|
||||
function wsPublish(topic, msg) {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({
|
||||
action: 'publish',
|
||||
topic: topic,
|
||||
message: msg
|
||||
}));
|
||||
} else {
|
||||
showToast('WebSocket连接未建立,无法发送消息');
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前WebSocket连接
|
||||
function getWebSocket() {
|
||||
return ws;
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
init: init,
|
||||
publish: wsPublish,
|
||||
getWebSocket: getWebSocket,
|
||||
topic_daq_control: topic_daq_control,
|
||||
topic_daq_data: topic_daq_data,
|
||||
topic_daq_status: topic_daq_status
|
||||
};
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
+2018
File diff suppressed because it is too large
Load Diff
Binary file not shown.
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
Vendored
+1
@@ -0,0 +1 @@
|
||||
.cm-s-monokai.CodeMirror{background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483e}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle{color:#d0d0d0}.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom{color:#ae81ff}.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-comment.cm-attribute{color:#97b757}.cm-s-monokai span.cm-comment.cm-def{color:#bc9262}.cm-s-monokai span.cm-comment.cm-tag{color:#bc6283}.cm-s-monokai span.cm-comment.cm-type{color:#5998a6}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-type,.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header{color:#ae81ff}.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
|
||||
@@ -0,0 +1,85 @@
|
||||
.card {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.form-control {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
#feedbackVoltage,
|
||||
#feedbackCurrent,
|
||||
#filamentVoltage,
|
||||
#filamentCurrent {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.navbar {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.nav-link i {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
/* 编辑器相关样式 */
|
||||
.CodeMirror {
|
||||
height: calc(100vh - 200px);
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#fileTree {
|
||||
height: calc(100vh - 200px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-icon {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon {
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon-custom {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
/* 文件类型图标颜色 */
|
||||
.bi-filetype-py {
|
||||
color: #306998;
|
||||
}
|
||||
|
||||
.bi-filetype-json {
|
||||
color: #f7df1e;
|
||||
}
|
||||
|
||||
.bi-filetype-sh {
|
||||
color: #4eaa25;
|
||||
}
|
||||
|
||||
.bi-folder {
|
||||
color: #ffc107;
|
||||
}
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,259 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>扫描臂管理系统</title>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="css/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="css/style.min.css" rel="stylesheet">
|
||||
<link href="css/codemirror.min.css" rel="stylesheet">
|
||||
<link href="css/monokai.min.css" rel="stylesheet">
|
||||
<link href="css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- 导航栏 -->
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="/">扫描臂管理系统</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid mt-4">
|
||||
<!-- Toast提示组件 -->
|
||||
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong class="me-auto">系统提示</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="toast-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 选项卡 -->
|
||||
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||
脚本编辑器</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content" id="mainTabContent">
|
||||
<!-- 控制面板 -->
|
||||
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设备控制</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="reboot">重启设备</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="start_scan">开始扫描</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="stop_scan">停止扫描</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="reset_scan">扫描复位</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mt-3">
|
||||
<div class="col-md-12">
|
||||
<button class="btn btn-danger w-100" id="emer_stop">紧急停止</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md">
|
||||
<div class="card">
|
||||
<div class="card-header">实时状态</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">扫描器ID</label>
|
||||
<div class="form-control" id="scannerId">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">上电时间</label>
|
||||
<div class="form-control" id="runTime">--</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">扫描器状态</label>
|
||||
<div class="form-control" id="scannerState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">当前位置 (mm)</label>
|
||||
<div class="form-control" id="scannerPos">--</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">速度</label>
|
||||
<div class="form-control" id="scannerSpeed">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">上下部位置 (mm)</label>
|
||||
<div class="form-control" id="scannerUpperAndLowerPos">--</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">扫描范围 (mm)</label>
|
||||
<div class="form-control" id="scannerScanRange">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">DAQ状态</label>
|
||||
<div class="form-control" id="daqState">--</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据曲线图 -->
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header">数据曲线</div>
|
||||
<div class="card-body">
|
||||
<canvas id="daq_chart" width="800" height="400"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据统计信息 -->
|
||||
<div class="row mt-4">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>数据统计信息</span>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-bordered">
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th>采集时间</th>
|
||||
<th>数据长度</th>
|
||||
<th>CH1平均值</th>
|
||||
<th>CH1峰峰值</th>
|
||||
<th>CH1波动水平</th>
|
||||
<th>CH2平均值</th>
|
||||
<th>CH2峰峰值</th>
|
||||
<th>CH2波动水平</th>
|
||||
<th>通道间差异</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="stats_table_body">
|
||||
<!-- 统计数据将通过JavaScript动态添加 -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 脚本编辑器 -->
|
||||
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>文件目录</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="fileTree"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span id="currentFile">未选择文件</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||
<i class="bi bi-save"></i> 保存
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<textarea id="editor"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- <script src="http://192.168.8.150:8000/js/lib/jquery.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/bootstrap.bundle.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/jstree.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/codemirror.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/python.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/javascript.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/shell.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/htmlmixed.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/xml.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/css.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/base64.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/hammer.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/chart.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/lib/chartjs-plugin-zoom.min.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/chart.js"></script>
|
||||
<script src="http://192.168.8.150:8000/js/utils.js"></script>
|
||||
|
||||
<script type="module" src="js/main.js"></script> -->
|
||||
|
||||
<script src="js/lib/jquery.min.js"></script>
|
||||
<script src="js/lib/bootstrap.bundle.min.js"></script>
|
||||
<script src="js/lib/jstree.min.js"></script>
|
||||
<script src="js/lib/codemirror.min.js"></script>
|
||||
<script src="js/lib/python.min.js"></script>
|
||||
<script src="js/lib/javascript.min.js"></script>
|
||||
<script src="js/lib/shell.min.js"></script>
|
||||
<script src="js/lib/htmlmixed.min.js"></script>
|
||||
<script src="js/lib/xml.min.js"></script>
|
||||
<script src="js/lib/css.min.js"></script>
|
||||
<script src="js/lib/base64.min.js"></script>
|
||||
<script src="js/lib/hammer.min.js"></script>
|
||||
<script src="js/lib/chart.min.js"></script>
|
||||
<script src="js/lib/chartjs-plugin-zoom.min.js"></script>
|
||||
<script src="js/chart.js"></script>
|
||||
|
||||
<script type="module" src="js/utils.js"></script>
|
||||
<script type="module" src="js/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,297 @@
|
||||
// chart.js - 图表功能模块
|
||||
|
||||
const ChartModule = (function() {
|
||||
let daqChart = null;
|
||||
let chartData = {
|
||||
ch1: [],
|
||||
ch2: []
|
||||
};
|
||||
|
||||
function getCurrentSn() {
|
||||
// 从设备信息中获取SN并移除所有空格和所有斜杠
|
||||
return $('#daq_info').text().replace(/\s+/g, '').replace(/\//g, '');
|
||||
}
|
||||
|
||||
// 初始化图表模块
|
||||
function init() {
|
||||
// 初始化图表
|
||||
initChart();
|
||||
|
||||
// 设置拖动和缩放模式切换
|
||||
initZoomControls();
|
||||
|
||||
// 将处理DAQ数据的函数暴露到全局
|
||||
window.handleDaqData = handleDaqData;
|
||||
|
||||
// 添加删除行按钮的事件委托
|
||||
const tbody = document.getElementById('stats_table_body');
|
||||
tbody.addEventListener('click', function(event) {
|
||||
if (event.target.closest('.delete-row')) {
|
||||
const row = event.target.closest('tr');
|
||||
row.remove();
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 初始化图表
|
||||
function initChart() {
|
||||
const ctx = document.getElementById('daq_chart').getContext('2d');
|
||||
daqChart = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: [],
|
||||
datasets: [
|
||||
{
|
||||
label: 'CH1',
|
||||
data: [],
|
||||
borderColor: 'rgba(219, 24, 67, 1)',
|
||||
backgroundColor: 'rgba(219, 24, 67, 1)',
|
||||
borderWidth: 1,
|
||||
fill: false,
|
||||
tension: 0,
|
||||
pointRadius: 3,
|
||||
pointBackgroundColor: 'rgba(219, 24, 67, 1)',
|
||||
pointBorderColor: 'rgba(219, 24, 67, 1)',
|
||||
pointHoverRadius: 5,
|
||||
pointHoverBackgroundColor: 'rgba(219, 24, 67, 0.8)',
|
||||
pointHoverBorderColor: 'rgba(219, 24, 67, 1)'
|
||||
},
|
||||
{
|
||||
label: 'CH2',
|
||||
data: [],
|
||||
borderColor: 'rgba(10, 49, 223, 1)',
|
||||
backgroundColor: 'rgba(10, 49, 223, 1)',
|
||||
borderWidth: 1,
|
||||
fill: false,
|
||||
tension: 0,
|
||||
pointRadius: 3,
|
||||
pointBackgroundColor: 'rgba(10, 49, 223, 1)',
|
||||
pointBorderColor: 'rgba(10, 49, 223, 1)',
|
||||
pointHoverRadius: 5,
|
||||
pointHoverBackgroundColor: 'rgba(10, 49, 223, 0.8)',
|
||||
pointHoverBorderColor: 'rgba(10, 49, 223, 1)'
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
x: {
|
||||
title: {
|
||||
display: true,
|
||||
text: '样本点'
|
||||
},
|
||||
grid: {
|
||||
color: 'rgba(0, 0, 0, 0.1)'
|
||||
}
|
||||
},
|
||||
y: {
|
||||
title: {
|
||||
display: true,
|
||||
text: '数值 (uint16)'
|
||||
},
|
||||
min: 0,
|
||||
max: 65535,
|
||||
grid: {
|
||||
color: 'rgba(0, 0, 0, 0.1)'
|
||||
}
|
||||
}
|
||||
},
|
||||
animation: false,
|
||||
plugins: {
|
||||
zoom: {
|
||||
pan: {
|
||||
enabled: true,
|
||||
mode: 'xy',
|
||||
speed: 10,
|
||||
threshold: 10,
|
||||
scaleMode: 'xy'
|
||||
},
|
||||
zoom: {
|
||||
wheel: {
|
||||
enabled: true,
|
||||
speed: 0.1
|
||||
},
|
||||
drag: {
|
||||
enabled: false,
|
||||
borderColor: 'rgba(255, 255, 255, 0.5)',
|
||||
borderWidth: 1,
|
||||
backgroundColor: 'rgba(225, 225, 225, 0.3)',
|
||||
drawTime: 'beforeDatasetsDraw'
|
||||
},
|
||||
pinch: {
|
||||
enabled: true
|
||||
},
|
||||
mode: 'xy',
|
||||
speed: 0.1,
|
||||
scaleMode: 'xy'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化缩放控制
|
||||
function initZoomControls() {
|
||||
// 重置缩放按钮
|
||||
$('#reset_zoom').on('click', function() {
|
||||
if (daqChart) {
|
||||
daqChart.resetZoom();
|
||||
}
|
||||
});
|
||||
|
||||
// 缩放模式切换按钮
|
||||
$('.zoom-mode-btn').on('click', function() {
|
||||
const mode = $(this).data('mode');
|
||||
|
||||
// 更新按钮状态
|
||||
$('.zoom-mode-btn').removeClass('active');
|
||||
$(this).addClass('active');
|
||||
|
||||
// 更新图表缩放模式
|
||||
if (daqChart) {
|
||||
daqChart.options.plugins.zoom.pan.mode = mode;
|
||||
daqChart.options.plugins.zoom.zoom.mode = mode;
|
||||
daqChart.update('none');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 处理DAQ数据
|
||||
function handleDaqData(daqData) {
|
||||
try {
|
||||
// 解析数据
|
||||
const parsedData = parseDaqData(daqData);
|
||||
|
||||
// 更新图表数据
|
||||
chartData.ch1 = parsedData.ch1;
|
||||
chartData.ch2 = parsedData.ch2;
|
||||
|
||||
// 更新图表
|
||||
updateChart();
|
||||
|
||||
// 计算并显示统计信息
|
||||
calculateAndDisplayStats(parsedData.ch1, parsedData.ch2);
|
||||
} catch (error) {
|
||||
console.error('解析DAQ数据失败:', error);
|
||||
showToast('解析DAQ数据失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 计算并显示统计信息
|
||||
function calculateAndDisplayStats(ch1Data, ch2Data) {
|
||||
// 计算各通道统计值
|
||||
const ch1Stats = calculateStats(ch1Data);
|
||||
const ch2Stats = calculateStats(ch2Data);
|
||||
|
||||
// 获取当前时间
|
||||
const currentTime = new Date().toLocaleString();
|
||||
|
||||
const diff = Math.abs(ch1Stats.average - ch2Stats.average) / (Math.max(ch1Stats.average, ch2Stats.average) || 1) * 100;
|
||||
|
||||
// 创建新的表格行
|
||||
const newRow = `
|
||||
<tr>
|
||||
<td>${currentTime}</td>
|
||||
<td>${ch1Data.length}</td>
|
||||
<td>${ch1Stats.average.toFixed(0)}</td>
|
||||
<td>${ch1Stats.peakToPeak.toFixed(0)}</td>
|
||||
<td>${ch1Stats.snr.toFixed(0)}%</td>
|
||||
<td>${ch2Stats.average.toFixed(0)}</td>
|
||||
<td>${ch2Stats.peakToPeak.toFixed(0)}</td>
|
||||
<td>${ch2Stats.snr.toFixed(0)}%</td>
|
||||
<td>${diff.toFixed(0)}%</td>
|
||||
<td>
|
||||
<button class="btn btn-danger btn-sm delete-row">
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
// 添加到表格顶部
|
||||
const tbody = document.getElementById('stats_table_body');
|
||||
tbody.insertAdjacentHTML('afterbegin', newRow);
|
||||
|
||||
// 限制表格行数(最多保留100条记录)
|
||||
const maxRows = 100;
|
||||
while (tbody.rows.length > maxRows) {
|
||||
tbody.deleteRow(tbody.rows.length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 计算单通道统计值
|
||||
function calculateStats(data) {
|
||||
if (!data || data.length === 0) {
|
||||
return { average: 0, peakToPeak: 0, snr: 0 };
|
||||
}
|
||||
|
||||
// 计算平均值
|
||||
const sum = data.reduce((acc, val) => acc + val, 0);
|
||||
const average = sum / data.length;
|
||||
|
||||
// 计算峰峰值
|
||||
const max = Math.max(...data);
|
||||
const min = Math.min(...data);
|
||||
const peakToPeak = max - min;
|
||||
|
||||
// 计算信噪比 (SNR)
|
||||
// 简单实现:假设噪声是信号的标准差
|
||||
|
||||
const snr = average === 0 ? 0 : peakToPeak / average * 100;
|
||||
|
||||
return { average, peakToPeak, snr };
|
||||
}
|
||||
|
||||
// ========== DAQ数据处理相关 ==========
|
||||
// 解析uint16小端数据
|
||||
function parseDaqData(arrayBuffer) {
|
||||
// 将ArrayBuffer转换为DataView
|
||||
const dataView = new DataView(arrayBuffer);
|
||||
|
||||
// 解析uint16小端数据
|
||||
const data = [];
|
||||
for (let i = 4; i < arrayBuffer.byteLength; i += 2) { // 跳过前4字节头
|
||||
data.push(dataView.getUint16(i, true)); // true表示小端
|
||||
}
|
||||
|
||||
// 分离CH1和CH2数据
|
||||
const ch1 = [];
|
||||
const ch2 = [];
|
||||
for (let i = 0; i < data.length; i += 2) {
|
||||
ch1.push(data[i]);
|
||||
if (i + 1 < data.length) {
|
||||
ch2.push(data[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
return { ch1, ch2 };
|
||||
}
|
||||
|
||||
// 更新图表
|
||||
function updateChart() {
|
||||
if (!daqChart) {
|
||||
initChart();
|
||||
}
|
||||
|
||||
// 更新标签和数据
|
||||
const labels = chartData.ch1.map((_, index) => index);
|
||||
|
||||
daqChart.data.labels = labels;
|
||||
daqChart.data.datasets[0].data = chartData.ch1;
|
||||
daqChart.data.datasets[1].data = chartData.ch2;
|
||||
|
||||
daqChart.update('none');
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
init: init,
|
||||
updateChart: updateChart
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,117 @@
|
||||
// 文件树和文件操作模块
|
||||
|
||||
let fileTree = null;
|
||||
|
||||
// 初始化文件树
|
||||
function initFileTree(onFileSelect) {
|
||||
if (!fileTree) {
|
||||
fileTree = $('#fileTree').jstree({
|
||||
'core': {
|
||||
'data': {
|
||||
'url': function(node) {
|
||||
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||
return url;
|
||||
},
|
||||
'data': function(node) {
|
||||
return { 'id': node.id };
|
||||
},
|
||||
'dataFilter': function(data) {
|
||||
var json = {};
|
||||
try {
|
||||
json = JSON.parse(data);
|
||||
} catch (e) {
|
||||
return "[]";
|
||||
}
|
||||
if (json.success && Array.isArray(json.data)) {
|
||||
return JSON.stringify(json.data);
|
||||
}
|
||||
return "[]";
|
||||
},
|
||||
'error': function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件列表失败:' + textStatus);
|
||||
}
|
||||
},
|
||||
'themes': {
|
||||
'name': 'default',
|
||||
'responsive': true
|
||||
},
|
||||
'check_callback': true,
|
||||
'multiple': false
|
||||
},
|
||||
'types': {
|
||||
'default': {
|
||||
'icon': 'bi bi-file-text'
|
||||
},
|
||||
'folder': {
|
||||
'icon': 'bi bi-folder'
|
||||
},
|
||||
'python': {
|
||||
'icon': 'bi bi-filetype-py'
|
||||
},
|
||||
'json': {
|
||||
'icon': 'bi bi-filetype-json'
|
||||
},
|
||||
'shell': {
|
||||
'icon': 'bi bi-filetype-sh'
|
||||
}
|
||||
},
|
||||
'plugins': ['types']
|
||||
}).on('ready.jstree', function() {
|
||||
// 文件树初始化完成
|
||||
});
|
||||
|
||||
// 文件树节点点击事件
|
||||
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||
const node = data.node;
|
||||
if (node.original.type != 'folder') {
|
||||
if (onFileSelect) {
|
||||
onFileSelect(node.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return fileTree;
|
||||
}
|
||||
|
||||
// 刷新文件树
|
||||
function refreshFileTree() {
|
||||
if (fileTree) {
|
||||
console.log('刷新文件树');
|
||||
$('#fileTree').jstree('refresh');
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化文件操作按钮事件
|
||||
function initFileOperations(saveFileCallback, deleteFileCallback) {
|
||||
// 保存文件
|
||||
$('#saveFile').click(function() {
|
||||
if (saveFileCallback) {
|
||||
saveFileCallback();
|
||||
}
|
||||
});
|
||||
|
||||
// 删除文件
|
||||
$('#deleteFile').click(function() {
|
||||
if (deleteFileCallback) {
|
||||
deleteFileCallback();
|
||||
}
|
||||
});
|
||||
|
||||
// 刷新文件树
|
||||
$('#refreshTree').click(function() {
|
||||
refreshFileTree();
|
||||
});
|
||||
}
|
||||
|
||||
// 获取文件树实例
|
||||
function getFileTree() {
|
||||
return fileTree;
|
||||
}
|
||||
|
||||
// 导出模块
|
||||
export {
|
||||
initFileTree,
|
||||
refreshFileTree,
|
||||
initFileOperations,
|
||||
getFileTree
|
||||
};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Minified by jsDelivr using Terser v5.15.1.
|
||||
* Original file: /npm/js-base64@3.7.5/base64.js
|
||||
*
|
||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||
*/
|
||||
!function(t,n){var r,e;"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(r=t.Base64,(e=n()).noConflict=function(){return t.Base64=r,e},t.Meteor&&(Base64=e),t.Base64=e)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,(function(){"use strict";var t,n="3.7.5",r="function"==typeof atob,e="function"==typeof btoa,o="function"==typeof Buffer,u="function"==typeof TextDecoder?new TextDecoder:void 0,i="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),c=(t={},f.forEach((function(n,r){return t[n]=r})),t),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,d=String.fromCharCode.bind(String),s="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){return new Uint8Array(Array.prototype.slice.call(t,0))},l=function(t){return t.replace(/=/g,"").replace(/[+\/]/g,(function(t){return"+"==t?"-":"_"}))},h=function(t){return t.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(t){for(var n,r,e,o,u="",i=t.length%3,c=0;c<t.length;){if((r=t.charCodeAt(c++))>255||(e=t.charCodeAt(c++))>255||(o=t.charCodeAt(c++))>255)throw new TypeError("invalid character found");u+=f[(n=r<<16|e<<8|o)>>18&63]+f[n>>12&63]+f[n>>6&63]+f[63&n]}return i?u.slice(0,i-3)+"===".substring(i):u},y=e?function(t){return btoa(t)}:o?function(t){return Buffer.from(t,"binary").toString("base64")}:p,A=o?function(t){return Buffer.from(t).toString("base64")}:function(t){for(var n=[],r=0,e=t.length;r<e;r+=4096)n.push(d.apply(null,t.subarray(r,r+4096)));return y(n.join(""))},b=function(t,n){return void 0===n&&(n=!1),n?l(A(t)):A(t)},g=function(t){if(t.length<2)return(n=t.charCodeAt(0))<128?t:n<2048?d(192|n>>>6)+d(128|63&n):d(224|n>>>12&15)+d(128|n>>>6&63)+d(128|63&n);var n=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return d(240|n>>>18&7)+d(128|n>>>12&63)+d(128|n>>>6&63)+d(128|63&n)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,x=function(t){return t.replace(B,g)},C=o?function(t){return Buffer.from(t,"utf8").toString("base64")}:i?function(t){return A(i.encode(t))}:function(t){return y(x(t))},m=function(t,n){return void 0===n&&(n=!1),n?l(C(t)):C(t)},v=function(t){return m(t,!0)},U=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,F=function(t){switch(t.length){case 4:var n=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return d(55296+(n>>>10))+d(56320+(1023&n));case 3:return d((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return d((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},w=function(t){return t.replace(U,F)},S=function(t){if(t=t.replace(/\s+/g,""),!a.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(3&t.length));for(var n,r,e,o="",u=0;u<t.length;)n=c[t.charAt(u++)]<<18|c[t.charAt(u++)]<<12|(r=c[t.charAt(u++)])<<6|(e=c[t.charAt(u++)]),o+=64===r?d(n>>16&255):64===e?d(n>>16&255,n>>8&255):d(n>>16&255,n>>8&255,255&n);return o},E=r?function(t){return atob(h(t))}:o?function(t){return Buffer.from(t,"base64").toString("binary")}:S,D=o?function(t){return s(Buffer.from(t,"base64"))}:function(t){return s(E(t).split("").map((function(t){return t.charCodeAt(0)})))},R=function(t){return D(T(t))},z=o?function(t){return Buffer.from(t,"base64").toString("utf8")}:u?function(t){return u.decode(D(t))}:function(t){return w(E(t))},T=function(t){return h(t.replace(/[-_]/g,(function(t){return"-"==t?"+":"/"})))},Z=function(t){return z(T(t))},j=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}},I=function(){var t=function(t,n){return Object.defineProperty(String.prototype,t,j(n))};t("fromBase64",(function(){return Z(this)})),t("toBase64",(function(t){return m(this,t)})),t("toBase64URI",(function(){return m(this,!0)})),t("toBase64URL",(function(){return m(this,!0)})),t("toUint8Array",(function(){return R(this)}))},O=function(){var t=function(t,n){return Object.defineProperty(Uint8Array.prototype,t,j(n))};t("toBase64",(function(t){return b(this,t)})),t("toBase64URI",(function(){return b(this,!0)})),t("toBase64URL",(function(){return b(this,!0)}))},P={version:n,VERSION:"3.7.5",atob:E,atobPolyfill:S,btoa:y,btoaPolyfill:p,fromBase64:Z,toBase64:m,encode:m,encodeURI:v,encodeURL:v,utob:x,btou:w,decode:Z,isValid:function(t){if("string"!=typeof t)return!1;var n=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(n)||!/[^\s0-9a-zA-Z\-_]/.test(n)},fromUint8Array:b,toUint8Array:R,extendString:I,extendUint8Array:O,extendBuiltins:function(){I(),O()},Base64:{}};return Object.keys(P).forEach((function(t){return P.Base64[t]=P[t]})),P}));
|
||||
//# sourceMappingURL=/sm/555281732ed54ee1693a772f485329378d8ea5052ffa4370e9c2e9947eb42d22.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
+13
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
+7
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],t):t(CodeMirror)}(function(m){"use strict";var l={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var a={};function d(t,e){e=t.match(a[e=e]||(a[e]=new RegExp("\\s+"+e+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return e?/^\s*(.*?)\s*$/.exec(e[2])[1]:""}function g(t,e){return new RegExp((e?"^":"")+"</\\s*"+t+"\\s*>","i")}function o(t,e){for(var a in t)for(var n=e[a]||(e[a]=[]),l=t[a],o=l.length-1;0<=o;o--)n.unshift(l[o])}m.defineMode("htmlmixed",function(i,t){var c=m.getMode(i,{name:"xml",htmlMode:!0,multilineTagIndentFactor:t.multilineTagIndentFactor,multilineTagIndentPastTag:t.multilineTagIndentPastTag,allowMissingTagName:t.allowMissingTagName}),s={},e=t&&t.tags,a=t&&t.scriptTypes;if(o(l,s),e&&o(e,s),a)for(var n=a.length-1;0<=n;n--)s.script.unshift(["type",a[n].matches,a[n].mode]);function u(t,e){var a,o,r,n=c.token(t,e.htmlState),l=/\btag\b/.test(n);return l&&!/[<>\s\/]/.test(t.current())&&(a=e.htmlState.tagName&&e.htmlState.tagName.toLowerCase())&&s.hasOwnProperty(a)?e.inTag=a+" ":e.inTag&&l&&/>$/.test(t.current())?(a=/^([\S]+) (.*)/.exec(e.inTag),e.inTag=null,l=">"==t.current()&&function(t,e){for(var a=0;a<t.length;a++){var n=t[a];if(!n[0]||n[1].test(d(e,n[0])))return n[2]}}(s[a[1]],a[2]),l=m.getMode(i,l),o=g(a[1],!0),r=g(a[1],!1),e.token=function(t,e){return t.match(o,!1)?(e.token=u,e.localState=e.localMode=null):(a=t,n=r,l=e.localMode.token(t,e.localState),t=a.current(),-1<(e=t.search(n))?a.backUp(t.length-e):t.match(/<\/?$/)&&(a.backUp(t.length),a.match(n,!1)||a.match(t)),l);var a,n,l},e.localMode=l,e.localState=m.startState(l,c.indent(e.htmlState,"",""))):e.inTag&&(e.inTag+=t.current(),t.eol()&&(e.inTag+=" ")),n}return{startState:function(){return{token:u,inTag:null,localMode:null,localState:null,htmlState:m.startState(c)}},copyState:function(t){var e;return t.localState&&(e=m.copyState(t.localMode,t.localState)),{token:t.token,inTag:t.inTag,localMode:t.localMode,localState:e,htmlState:m.copyState(c,t.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(t,e,a){return!t.localMode||/^\s*<\//.test(e)?c.indent(t.htmlState,e,a):t.localMode.indent?t.localMode.indent(t.localState,e,a):m.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||c}}}},"xml","javascript","css"),m.defineMIME("text/html","htmlmixed")});
|
||||
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -0,0 +1 @@
|
||||
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){"use strict";s.defineMode("shell",function(){var o={};function e(e,t){for(var n=0;n<t.length;n++)o[t[n]]=e}var t=["true","false"],n=["if","then","do","else","elif","while","until","for","in","esac","fi","fin","fil","done","exit","set","unset","export","function"],r=["ab","awk","bash","beep","cat","cc","cd","chown","chmod","chroot","clear","cp","curl","cut","diff","echo","find","gawk","gcc","get","git","grep","hg","kill","killall","ln","ls","make","mkdir","openssl","mv","nc","nl","node","npm","ping","ps","restart","rm","rmdir","sed","service","sh","shopt","shred","source","sort","sleep","ssh","start","stop","su","sudo","svn","tee","telnet","top","touch","vi","vim","wall","wc","wget","who","write","yes","zsh"];function i(e,t){if(e.eatSpace())return null;var n,r=e.sol(),i=e.next();if("\\"===i)return e.next(),null;if("'"===i||'"'===i||"`"===i)return t.tokens.unshift(f(i,"`"===i?"quote":"string")),l(e,t);if("#"===i)return r&&e.eat("!")?(e.skipToEnd(),"meta"):(e.skipToEnd(),"comment");if("$"===i)return t.tokens.unshift(u),l(e,t);if("+"===i||"="===i)return"operator";if("-"===i)return e.eat("-"),e.eatWhile(/\w/),"attribute";if("<"==i){if(e.match("<<"))return"operator";r=e.match(/^<-?\s*['"]?([^'"]*)['"]?/);if(r)return t.tokens.unshift((n=r[1],function(e,t){return e.sol()&&e.string==n&&t.tokens.shift(),e.skipToEnd(),"string-2"})),"string-2"}if(/\d/.test(i)&&(e.eatWhile(/\d/),e.eol()||!/\w/.test(e.peek())))return"number";e.eatWhile(/[\w-]/);i=e.current();return"="===e.peek()&&/\w+/.test(i)?"def":o.hasOwnProperty(i)?o[i]:null}function f(i,o){var s="("==i?")":"{"==i?"}":i;return function(e,t){for(var n,r=!1;null!=(n=e.next());){if(n===s&&!r){t.tokens.shift();break}if("$"===n&&!r&&"'"!==i&&e.peek()!=s){r=!0,e.backUp(1),t.tokens.unshift(u);break}if(!r&&i!==s&&n===i)return t.tokens.unshift(f(i,o)),l(e,t);if(!r&&/['"]/.test(n)&&!/['"]/.test(i)){t.tokens.unshift(function(n,r){return function(e,t){return t.tokens[0]=f(n,r),e.next(),l(e,t)}}(n,"string")),e.backUp(1);break}r=!r&&"\\"===n}return o}}s.registerHelper("hintWords","shell",t.concat(n,r)),e("atom",t),e("keyword",n),e("builtin",r);var u=function(e,t){1<t.tokens.length&&e.eat("$");var n=e.next();return/['"({]/.test(n)?(t.tokens[0]=f(n,"("==n?"quote":"{"==n?"def":"string"),l(e,t)):(/\d/.test(n)||e.eatWhile(/\w/),t.tokens.shift(),"def")};function l(e,t){return(t.tokens[0]||i)(e,t)}return{startState:function(){return{tokens:[]}},token:l,closeBrackets:"()[]{}''\"\"``",lineComment:"#",fold:"brace"}}),s.defineMIME("text/x-sh","shell"),s.defineMIME("application/x-sh","shell")});
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,98 @@
|
||||
// 主入口文件 - 整合所有模块
|
||||
|
||||
// 导入WebSocket模块
|
||||
import {
|
||||
wsPublish,
|
||||
initWebSocket,
|
||||
setScannerStateHandler,
|
||||
setScannerDataHandler,
|
||||
setResponseHandler,
|
||||
getWebSocket,
|
||||
topic_control
|
||||
} from './websocket.js';
|
||||
|
||||
// 导入扫描器状态模块
|
||||
import {
|
||||
updateScannerStatus,
|
||||
initScannerControls
|
||||
} from './scanner-status.js';
|
||||
|
||||
// 导入脚本编辑器模块
|
||||
import {
|
||||
initEditor,
|
||||
loadFile,
|
||||
saveFile,
|
||||
deleteCurrentFile
|
||||
} from './script-editor.js';
|
||||
|
||||
// 导入文件树模块
|
||||
import {
|
||||
initFileTree,
|
||||
refreshFileTree
|
||||
} from './file-tree.js';
|
||||
|
||||
// 将刷新文件树函数暴露到全局
|
||||
window.refreshFileTree = refreshFileTree;
|
||||
|
||||
// 文档加载完成后初始化
|
||||
$(document).ready(function() {
|
||||
// 初始化WebSocket连接
|
||||
initWebSocket();
|
||||
|
||||
ChartModule.init();
|
||||
|
||||
// 设置扫描器状态处理函数
|
||||
setScannerStateHandler(function(topic, message) {
|
||||
try {
|
||||
const scannerData = typeof message === 'string' ? JSON.parse(message) : message;
|
||||
updateScannerStatus(scannerData);
|
||||
} catch (e) {
|
||||
showToast('解析扫描器状态消息失败: ' + e.message);
|
||||
}
|
||||
});
|
||||
|
||||
// 设置扫描器数据处理函数
|
||||
setScannerDataHandler(function(topic, message) {
|
||||
try {
|
||||
// 处理扫描器数据,例如更新显示
|
||||
// console.log('扫描器数据:', scannerData);
|
||||
handleDaqData(message);
|
||||
} catch (e) {
|
||||
showToast('解析扫描器数据消息失败: ' + e.message);
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化扫描器控制按钮
|
||||
initScannerControls(wsPublish, topic_control);
|
||||
|
||||
// 初始化脚本编辑器标签页事件
|
||||
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
|
||||
// 初始化文件树
|
||||
initFileTree(function(filePath) {
|
||||
loadFile(filePath);
|
||||
});
|
||||
});
|
||||
|
||||
// 窗口关闭前关闭WebSocket连接
|
||||
$(window).on('beforeunload', function() {
|
||||
const ws = getWebSocket();
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 保存文件按钮点击事件
|
||||
$('#saveFile').click(function() {
|
||||
saveFile();
|
||||
});
|
||||
|
||||
// 删除文件按钮点击事件
|
||||
$('#deleteFile').click(function() {
|
||||
deleteCurrentFile();
|
||||
});
|
||||
|
||||
// 刷新文件树按钮点击事件
|
||||
$('#refreshTree').click(function() {
|
||||
refreshFileTree();
|
||||
});
|
||||
@@ -0,0 +1,661 @@
|
||||
$(document).ready(function() {
|
||||
|
||||
const topic_control = '/dev/control';
|
||||
const topic_status = '/dev/status';
|
||||
const topic_response = '/dev/response';
|
||||
const topic_scanner_status = '/dev/status/scanner';
|
||||
|
||||
// 扫描器状态英文到中文的映射
|
||||
const scannerStateMap = {
|
||||
'stop': '停止',
|
||||
'moving_up': '向上扫描',
|
||||
'moving_down': '向下扫描',
|
||||
'stop_at_upper': '顶部',
|
||||
'stop_at_bottom': '底部',
|
||||
'stop_at_origin': '原点'
|
||||
};
|
||||
|
||||
// Toast初始化
|
||||
const toastEl = document.getElementById('toast');
|
||||
const toast = new bootstrap.Toast(toastEl, {
|
||||
autohide: true,
|
||||
delay: 3000
|
||||
});
|
||||
function showToast(message) {
|
||||
$('.toast-body').text(message);
|
||||
toast.show();
|
||||
}
|
||||
|
||||
// ================== 控制面板相关 ==================
|
||||
// WebSocket客户端配置
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsHost = location.hostname + (location.port ? ':' + location.port : '');
|
||||
const wsuri = wsProtocol + '//' + wsHost + '/ws';
|
||||
console.log('WebSocket URI:', wsuri);
|
||||
// 创建WebSocket连接
|
||||
let ws;
|
||||
let reconnectTimer;
|
||||
|
||||
function msToReadable(ms) {
|
||||
// 严格校验输入:必须是整数且非负
|
||||
if (!Number.isInteger(ms) || ms < 0) {
|
||||
return "--";
|
||||
}
|
||||
|
||||
// 定义时间单位换算(毫秒)
|
||||
const SECOND = 1000;
|
||||
const MINUTE = 60 * SECOND;
|
||||
const HOUR = 60 * MINUTE;
|
||||
const DAY = 24 * HOUR;
|
||||
|
||||
// 计算各时间单位的数值
|
||||
let days = Math.floor(ms / DAY);
|
||||
let remaining = ms % DAY;
|
||||
|
||||
let hours = Math.floor(remaining / HOUR);
|
||||
remaining %= HOUR;
|
||||
|
||||
let minutes = Math.floor(remaining / MINUTE);
|
||||
remaining %= MINUTE;
|
||||
|
||||
let seconds = Math.floor(remaining / SECOND);
|
||||
|
||||
// 构建结果数组(只保留非零单位)
|
||||
const parts = [];
|
||||
if (days > 0) parts.push(`${days}天`);
|
||||
if (hours > 0) parts.push(`${hours}时`);
|
||||
if (minutes > 0) parts.push(`${minutes}分`);
|
||||
// 若前面无内容,至少显示秒(包括0秒)
|
||||
if (seconds > 0 || parts.length === 0) parts.push(`${seconds}秒`);
|
||||
|
||||
// 拼接成最终字符串
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
// 替换 client.publish 为 ws.send
|
||||
function wsPublish(topic, msg) {
|
||||
ws.send(JSON.stringify({
|
||||
action: 'publish',
|
||||
topic: topic,
|
||||
message: msg
|
||||
}));
|
||||
}
|
||||
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket(wsuri);
|
||||
|
||||
ws.onopen = function() {
|
||||
showToast('已连接到WebSocket服务器');
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_status }));
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_scanner_status }));
|
||||
// 清除重连定时器
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
let data;
|
||||
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
return;
|
||||
}
|
||||
const topic = data.topic;
|
||||
const message = data.message;
|
||||
|
||||
if (topic && message) {
|
||||
if (topic.startsWith(topic_response)) {
|
||||
|
||||
} else if (topic.startsWith(topic_scanner_status)) {
|
||||
try {
|
||||
const scannerData = typeof message === 'string' ? JSON.parse(message) : message;
|
||||
// 更新扫描器状态数据
|
||||
$('#scannerId').text(scannerData.id || '--');
|
||||
$('#runTime').text(msToReadable(scannerData.run_time));
|
||||
// 将英文状态映射为中文
|
||||
const chineseState = scannerStateMap[scannerData.state] || scannerData.state || '--';
|
||||
var run_flag = ""
|
||||
if (scannerData.run_flag == true) {
|
||||
run_flag = " 扫描中";
|
||||
} else if (scannerData.run_flag == false) {
|
||||
run_flag = " 停止扫描";
|
||||
}
|
||||
$('#scannerState').text(chineseState + run_flag);
|
||||
$('#scannerPos').text(scannerData.pos ? scannerData.pos.toFixed(2) + ' mm' : '--');
|
||||
$('#scannerSpeed').text(scannerData.speed !== undefined ? scannerData.speed.toFixed(4) : '--');
|
||||
$('#scannerUpperAndLowerPos').text(scannerData.upper_pos ? scannerData.upper_pos.toFixed(2) + '<-->' + scannerData.bottom_pos.toFixed(2) : '--');
|
||||
$('#scannerScanRange').text(scannerData.scan_range ? scannerData.scan_range.toFixed(2) + ' mm' : '--');
|
||||
daq_state = scannerData.daq_online ? '在线' : '离线';
|
||||
daq_temp = scannerData.daq_temp / 10.0;
|
||||
daq_state += scannerData.daq_online ? ` 温度: ${daq_temp.toFixed(1)}°C` : '';
|
||||
$('#daqState').text(daq_state);
|
||||
|
||||
} catch (e) {
|
||||
showToast('解析扫描器状态消息失败: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = function() {
|
||||
showToast('WebSocket连接错误');
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
showToast('WebSocket连接已关闭,正在尝试重连...');
|
||||
// 仅在没有活跃定时器时创建新的重连定时器
|
||||
if (!reconnectTimer) {
|
||||
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||
}
|
||||
};
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
// 初始连接
|
||||
connectWebSocket();
|
||||
|
||||
setInterval(function() {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
wsPublish(topic_control, {cmd: 'status'});
|
||||
}
|
||||
}, 500);
|
||||
|
||||
|
||||
$('#start_scan').click(function() {
|
||||
var msg = {
|
||||
cmd: 'start'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#stop_scan').click(function() {
|
||||
var msg = {
|
||||
cmd: 'stop'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#reset_scan').click(function() {
|
||||
var msg = {
|
||||
cmd: 'reset'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#emer_stop').click(function() {
|
||||
var msg = {
|
||||
cmd: 'emer_stop'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('紧急停止请求已发送!');
|
||||
});
|
||||
|
||||
$('#reboot').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/device/reboot',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$(window).on('beforeunload', function() {
|
||||
ws.close();
|
||||
});
|
||||
|
||||
// ================== 脚本编辑器相关 ==================
|
||||
let scriptTabInited = false;
|
||||
let editor = null;
|
||||
|
||||
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
|
||||
console.log('tab shown', e);
|
||||
const target = $(e.target).attr('data-bs-target');
|
||||
if (target === '#script' && !scriptTabInited) {
|
||||
// 初始化CodeMirror
|
||||
editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
|
||||
mode: 'text/x-python',
|
||||
theme: 'monokai',
|
||||
lineNumbers: true,
|
||||
indentUnit: 4,
|
||||
lineWrapping: true,
|
||||
matchBrackets: true,
|
||||
autoCloseBrackets: true
|
||||
});
|
||||
|
||||
editor.setValue("请选择一个文件");
|
||||
|
||||
// 初始化文件树
|
||||
$('#fileTree').jstree({
|
||||
'core': {
|
||||
'data': {
|
||||
'url': function(node) {
|
||||
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||
return url;
|
||||
},
|
||||
'data': function(node) {
|
||||
return { 'id': node.id };
|
||||
},
|
||||
'dataFilter': function(data) {
|
||||
var json = {};
|
||||
try {
|
||||
json = JSON.parse(data);
|
||||
} catch (e) {
|
||||
return "[]";
|
||||
}
|
||||
if (json.success && Array.isArray(json.data)) {
|
||||
return JSON.stringify(json.data);
|
||||
}
|
||||
return "[]";
|
||||
},
|
||||
'error': function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件列表失败:' + textStatus);
|
||||
}
|
||||
},
|
||||
'themes': {
|
||||
'name': 'default',
|
||||
'responsive': true
|
||||
},
|
||||
'check_callback': true,
|
||||
'multiple': false
|
||||
},
|
||||
'types': {
|
||||
'default': {
|
||||
'icon': 'bi bi-file-text'
|
||||
},
|
||||
'folder': {
|
||||
'icon': 'bi bi-folder'
|
||||
},
|
||||
'python': {
|
||||
'icon': 'bi bi-filetype-py'
|
||||
},
|
||||
'json': {
|
||||
'icon': 'bi bi-filetype-json'
|
||||
},
|
||||
'shell': {
|
||||
'icon': 'bi bi-filetype-sh'
|
||||
}
|
||||
},
|
||||
'plugins': ['types']
|
||||
}).on('ready.jstree', function() {
|
||||
// 文件树初始化完成
|
||||
});
|
||||
|
||||
// 文件树节点点击事件
|
||||
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||
const node = data.node;
|
||||
if (node.original.type != 'folder') {
|
||||
loadFile(node.id);
|
||||
}
|
||||
});
|
||||
|
||||
// 加载文件内容 - 分段读取
|
||||
function loadFile(path) {
|
||||
// 先清空编辑器
|
||||
editor.setValue("");
|
||||
$('#currentFile').text(path);
|
||||
showToast('正在加载文件...');
|
||||
|
||||
// 首先获取文件信息
|
||||
$.get('/api/script/info?path=' + encodeURIComponent(path), function(infoResponse) {
|
||||
if (infoResponse.success) {
|
||||
const fileSize = infoResponse.size;
|
||||
const chunkSize = 4096; // 4K 分段
|
||||
let totalChunks = Math.ceil(fileSize / chunkSize);
|
||||
let loadedChunks = 0;
|
||||
let fileContent = '';
|
||||
|
||||
// 显示加载进度
|
||||
let progressToast = showToast('正在加载文件... (0%)');
|
||||
|
||||
// 分段读取函数
|
||||
function readChunk(offset) {
|
||||
if (offset >= fileSize) {
|
||||
// 所有分块读取完成
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
switch(ext) {
|
||||
case 'py':
|
||||
editor.setOption('mode', 'text/x-python');
|
||||
break;
|
||||
case 'json':
|
||||
editor.setOption('mode', 'application/json');
|
||||
break;
|
||||
case 'sh':
|
||||
editor.setOption('mode', 'text/x-sh');
|
||||
break;
|
||||
case 'html':
|
||||
editor.setOption('mode', 'text/html');
|
||||
break;
|
||||
case 'js':
|
||||
editor.setOption('mode', 'javascript');
|
||||
break;
|
||||
case 'css':
|
||||
editor.setOption('mode', 'css');
|
||||
break;
|
||||
default:
|
||||
editor.setOption('mode', 'text/plain');
|
||||
}
|
||||
editor.setValue(fileContent);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载成功');
|
||||
return;
|
||||
}
|
||||
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path) + '&offset=' + offset + '&size=' + chunkSize, function(response) {
|
||||
if (response.success) {
|
||||
// 使用js-base64库解码
|
||||
const chunkContent = Base64.decode(response.data);
|
||||
fileContent += chunkContent;
|
||||
loadedChunks++;
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.min(100, Math.round((loadedChunks / totalChunks) * 100));
|
||||
showToast('正在加载文件... (' + progress + '%)');
|
||||
|
||||
// 继续读取下一个分块
|
||||
setTimeout(function() {
|
||||
readChunk(response.offset + response.size);
|
||||
}, 10); // 短暂延迟,避免请求过于密集
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
}
|
||||
|
||||
// 开始读取第一个分块
|
||||
readChunk(0);
|
||||
} else {
|
||||
// 如果获取文件信息失败,尝试使用旧的一次性读取方式作为降级方案
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path), function(response) {
|
||||
if (response.success) {
|
||||
// 使用js-base64库解码
|
||||
const content = Base64.decode(response.data);
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
switch(ext) {
|
||||
case 'py':
|
||||
editor.setOption('mode', 'text/x-python');
|
||||
break;
|
||||
case 'json':
|
||||
editor.setOption('mode', 'application/json');
|
||||
break;
|
||||
case 'sh':
|
||||
editor.setOption('mode', 'text/x-sh');
|
||||
break;
|
||||
case 'html':
|
||||
editor.setOption('mode', 'text/html');
|
||||
break;
|
||||
case 'js':
|
||||
editor.setOption('mode', 'javascript');
|
||||
break;
|
||||
case 'css':
|
||||
editor.setOption('mode', 'css');
|
||||
break;
|
||||
default:
|
||||
editor.setOption('mode', 'text/plain');
|
||||
}
|
||||
editor.setValue(content);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载成功');
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
}
|
||||
}).fail(function() {
|
||||
// 如果获取文件信息接口失败,尝试使用旧的一次性读取方式
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path), function(response) {
|
||||
if (response.success) {
|
||||
const content = Base64.decode(response.data);
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
switch(ext) {
|
||||
case 'py':
|
||||
editor.setOption('mode', 'text/x-python');
|
||||
break;
|
||||
case 'json':
|
||||
editor.setOption('mode', 'application/json');
|
||||
break;
|
||||
case 'sh':
|
||||
editor.setOption('mode', 'text/x-sh');
|
||||
break;
|
||||
case 'html':
|
||||
editor.setOption('mode', 'text/html');
|
||||
break;
|
||||
case 'js':
|
||||
editor.setOption('mode', 'javascript');
|
||||
break;
|
||||
case 'css':
|
||||
editor.setOption('mode', 'css');
|
||||
break;
|
||||
default:
|
||||
editor.setOption('mode', 'text/plain');
|
||||
}
|
||||
editor.setValue(content);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载成功');
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function() {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 保存文件 - 分段写入
|
||||
$('#saveFile').click(function() {
|
||||
const path = $('#currentFile').text();
|
||||
const fullContent = editor.getValue();
|
||||
const chunkSize = 4096; // 4K 分段(字节数)
|
||||
let currentChunk = 0;
|
||||
let currentByteOffset = 0;
|
||||
|
||||
showToast('正在保存文件...');
|
||||
|
||||
// 使用TextEncoder API进行更高效的UTF-8字节处理
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
|
||||
// 基于字节数的字符串截取函数 - 优化版本
|
||||
function substrBytes(str, startByte, lengthBytes) {
|
||||
console.time('substrBytes_optimized');
|
||||
|
||||
// 将整个字符串编码为Uint8Array以获取字节数据
|
||||
const bytes = encoder.encode(str);
|
||||
|
||||
// 确保截取范围在有效范围内
|
||||
const endByte = Math.min(startByte + lengthBytes, bytes.length);
|
||||
|
||||
// 截取指定范围的字节
|
||||
const chunkBytes = bytes.subarray(startByte, endByte);
|
||||
|
||||
// 将截取的字节解码回字符串
|
||||
const result = decoder.decode(chunkBytes);
|
||||
|
||||
console.timeEnd('substrBytes_optimized');
|
||||
return result;
|
||||
}
|
||||
|
||||
// 计算字符串的UTF-8字节长度 - 优化版本
|
||||
function getByteLength(str) {
|
||||
console.time('getByteLength_optimized');
|
||||
const length = encoder.encode(str).length;
|
||||
console.timeEnd('getByteLength_optimized');
|
||||
return length;
|
||||
}
|
||||
|
||||
// 分段写入函数
|
||||
function writeChunk(byteOffset) {
|
||||
console.time('writeChunk');
|
||||
console.log('开始处理分块,字节偏移量:', byteOffset);
|
||||
|
||||
const totalBytes = getByteLength(fullContent);
|
||||
if (byteOffset >= totalBytes) {
|
||||
// 所有分块写入完成,请求服务器进行最终校验和重命名
|
||||
$.ajax({
|
||||
url: '/api/script/write/finalize',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
total_size: totalBytes
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('文件保存成功,但最终校验失败:' + response.message);
|
||||
console.warn('文件校验失败,但内容可能已保存:', response.message);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
// 即使最终校验请求失败,我们仍然告知用户文件已保存
|
||||
// 因为分块已经写入,只是可能没有进行最后的重命名和校验
|
||||
showToast('文件内容已保存,但最终处理请求失败');
|
||||
console.warn('最终处理请求失败');
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取当前分块内容(按字节数截取)
|
||||
const chunkContent = substrBytes(fullContent, byteOffset, chunkSize);
|
||||
|
||||
// 使用js-base64库编码
|
||||
console.time('Base64_encode');
|
||||
const encodedContent = Base64.encode(chunkContent);
|
||||
console.timeEnd('Base64_encode');
|
||||
|
||||
console.time('calculateNextOffset');
|
||||
const nextByteOffset = byteOffset + getByteLength(chunkContent);
|
||||
const isFinal = nextByteOffset >= totalBytes;
|
||||
console.timeEnd('calculateNextOffset');
|
||||
|
||||
// 更新进度
|
||||
currentChunk++;
|
||||
// 重新计算总块数(基于字节数)
|
||||
const totalByteChunks = Math.ceil(totalBytes / chunkSize);
|
||||
const progress = Math.min(100, Math.round((currentChunk / totalByteChunks) * 100));
|
||||
showToast('正在保存文件... (' + progress + '%)');
|
||||
|
||||
console.time('prepareAjaxRequest');
|
||||
const ajaxData = JSON.stringify({
|
||||
path: path,
|
||||
content: encodedContent,
|
||||
offset: byteOffset,
|
||||
final: isFinal
|
||||
});
|
||||
console.timeEnd('prepareAjaxRequest');
|
||||
|
||||
console.time('ajaxRequest');
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: ajaxData,
|
||||
success: function(response) {
|
||||
console.timeEnd('ajaxRequest');
|
||||
if (response.success) {
|
||||
// 继续写入下一个分块
|
||||
console.log('分块处理完成,准备处理下一个分块,响应偏移量:', response.offset);
|
||||
setTimeout(function() {
|
||||
writeChunk(response.offset);
|
||||
}, 10); // 短暂延迟,避免请求过于密集
|
||||
} else {
|
||||
showToast('保存文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
console.timeEnd('ajaxRequest');
|
||||
console.log('分段写入失败:', textStatus, errorThrown);
|
||||
showToast('保存文件失败:网络错误');
|
||||
// 如果分段写入失败,尝试使用旧的一次性写入方式作为降级方案
|
||||
console.log('分段写入失败,尝试一次性写入');
|
||||
const fullEncodedContent = Base64.encode(fullContent);
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: fullEncodedContent
|
||||
}),
|
||||
success: function(backupResponse) {
|
||||
if (backupResponse.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('保存文件失败:' + backupResponse.message);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showToast('保存文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
console.timeEnd('writeChunk');
|
||||
|
||||
}
|
||||
|
||||
// 开始写入第一个分块
|
||||
writeChunk(currentByteOffset);
|
||||
});
|
||||
|
||||
// 删除文件
|
||||
$('#deleteFile').click(function() {
|
||||
if (confirm('确定要删除这个文件吗?')) {
|
||||
const path = $('#currentFile').text();
|
||||
$.ajax({
|
||||
url: '/api/script/delete',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件删除成功');
|
||||
$('#currentFile').text('未选择文件');
|
||||
editor.setValue('');
|
||||
$('#saveFile, #deleteFile').prop('disabled', true);
|
||||
$('#fileTree').jstree('refresh');
|
||||
} else {
|
||||
showToast('删除文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('删除文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 刷新文件树
|
||||
$('#refreshTree').click(function() {
|
||||
console.log('刷新文件树');
|
||||
$('#fileTree').jstree('refresh');
|
||||
});
|
||||
|
||||
scriptTabInited = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
// 扫描器状态管理和显示模块
|
||||
|
||||
// 扫描器状态英文到中文的映射
|
||||
const scannerStateMap = {
|
||||
'stop': '停止',
|
||||
'moving_up': '向上扫描',
|
||||
'moving_down': '向下扫描',
|
||||
'stop_at_upper': '顶部',
|
||||
'stop_at_bottom': '底部',
|
||||
'stop_at_origin': '原点'
|
||||
};
|
||||
|
||||
// 将毫秒转换为可读的时间格式
|
||||
function msToReadable(ms) {
|
||||
// 严格校验输入:必须是整数且非负
|
||||
if (!Number.isInteger(ms) || ms < 0) {
|
||||
return "--";
|
||||
}
|
||||
|
||||
// 定义时间单位换算(毫秒)
|
||||
const SECOND = 1000;
|
||||
const MINUTE = 60 * SECOND;
|
||||
const HOUR = 60 * MINUTE;
|
||||
const DAY = 24 * HOUR;
|
||||
|
||||
// 计算各时间单位的数值
|
||||
let days = Math.floor(ms / DAY);
|
||||
let remaining = ms % DAY;
|
||||
|
||||
let hours = Math.floor(remaining / HOUR);
|
||||
remaining %= HOUR;
|
||||
|
||||
let minutes = Math.floor(remaining / MINUTE);
|
||||
remaining %= MINUTE;
|
||||
|
||||
let seconds = Math.floor(remaining / SECOND);
|
||||
|
||||
// 构建结果数组(只保留非零单位)
|
||||
const parts = [];
|
||||
if (days > 0) parts.push(`${days}天`);
|
||||
if (hours > 0) parts.push(`${hours}时`);
|
||||
if (minutes > 0) parts.push(`${minutes}分`);
|
||||
// 若前面无内容,至少显示秒(包括0秒)
|
||||
if (seconds > 0 || parts.length === 0) parts.push(`${seconds}秒`);
|
||||
|
||||
// 拼接成最终字符串
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
// 更新扫描器状态显示
|
||||
function updateScannerStatus(scannerData) {
|
||||
try {
|
||||
// 更新扫描器状态数据
|
||||
$('#scannerId').text(scannerData.id || '--');
|
||||
$('#runTime').text(msToReadable(scannerData.run_time));
|
||||
// 将英文状态映射为中文
|
||||
const chineseState = scannerStateMap[scannerData.state] || scannerData.state || '--';
|
||||
let run_flag = "";
|
||||
if (scannerData.run_flag == true) {
|
||||
run_flag = " 扫描中";
|
||||
} else if (scannerData.run_flag == false) {
|
||||
run_flag = " 停止扫描";
|
||||
}
|
||||
$('#scannerState').text(chineseState + run_flag);
|
||||
$('#scannerPos').text(scannerData.pos ? scannerData.pos.toFixed(2) + ' mm' : '--');
|
||||
$('#scannerSpeed').text(scannerData.speed !== undefined ? scannerData.speed.toFixed(4) : '--');
|
||||
$('#scannerUpperAndLowerPos').text(scannerData.upper_pos ? scannerData.upper_pos.toFixed(2) + '<-->' + scannerData.bottom_pos.toFixed(2) : '--');
|
||||
$('#scannerScanRange').text(scannerData.scan_range ? scannerData.scan_range.toFixed(2) + ' mm' : '--');
|
||||
|
||||
let daq_state = scannerData.daq_online ? '在线' : '离线';
|
||||
let daq_temp = scannerData.daq_temp / 10.0;
|
||||
daq_state += scannerData.daq_online ? ` 温度: ${daq_temp.toFixed(1)}°C` : '';
|
||||
$('#daqState').text(daq_state);
|
||||
} catch (e) {
|
||||
showToast('解析扫描器状态消息失败: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化扫描器控制按钮事件
|
||||
function initScannerControls(wsPublish, topic_control) {
|
||||
// 开始扫描
|
||||
$('#start_scan').click(function() {
|
||||
var msg = {
|
||||
cmd: 'start'
|
||||
};
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
// 停止扫描
|
||||
$('#stop_scan').click(function() {
|
||||
var msg = {
|
||||
cmd: 'stop'
|
||||
};
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
// 重置扫描器
|
||||
$('#reset_scan').click(function() {
|
||||
var msg = {
|
||||
cmd: 'reset'
|
||||
};
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
// 紧急停止
|
||||
$('#emer_stop').click(function() {
|
||||
var msg = {
|
||||
cmd: 'emer_stop'
|
||||
};
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('紧急停止请求已发送!');
|
||||
});
|
||||
|
||||
// 设备重启
|
||||
$('#reboot').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/device/reboot',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 导出模块
|
||||
export {
|
||||
scannerStateMap,
|
||||
msToReadable,
|
||||
updateScannerStatus,
|
||||
initScannerControls
|
||||
};
|
||||
@@ -0,0 +1,331 @@
|
||||
// 脚本编辑器模块
|
||||
|
||||
let editor = null;
|
||||
let currentFile = null;
|
||||
|
||||
// 初始化CodeMirror编辑器
|
||||
function initEditor() {
|
||||
if (!editor) {
|
||||
editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
|
||||
mode: 'text/x-python',
|
||||
theme: 'monokai',
|
||||
lineNumbers: true,
|
||||
indentUnit: 4,
|
||||
lineWrapping: true,
|
||||
matchBrackets: true,
|
||||
autoCloseBrackets: true
|
||||
});
|
||||
|
||||
editor.setValue("请选择一个文件");
|
||||
}
|
||||
return editor;
|
||||
}
|
||||
|
||||
// 根据文件扩展名设置编辑器模式
|
||||
function setEditorMode(ext) {
|
||||
if (!editor) return;
|
||||
|
||||
const modeMap = {
|
||||
'py': 'text/x-python',
|
||||
'json': 'application/json',
|
||||
'sh': 'text/x-sh',
|
||||
'html': 'text/html',
|
||||
'js': 'javascript',
|
||||
'css': 'css'
|
||||
};
|
||||
|
||||
editor.setOption('mode', modeMap[ext] || 'text/plain');
|
||||
}
|
||||
|
||||
// 加载文件内容 - 分段读取
|
||||
function loadFile(path) {
|
||||
if (!editor) initEditor();
|
||||
|
||||
// 先清空编辑器
|
||||
editor.setValue("");
|
||||
$('#currentFile').text(path);
|
||||
currentFile = path;
|
||||
showToast('正在加载文件...');
|
||||
|
||||
// 首先获取文件信息
|
||||
$.get('/api/script/info?path=' + encodeURIComponent(path), function(infoResponse) {
|
||||
if (infoResponse.success) {
|
||||
const fileSize = infoResponse.size;
|
||||
const chunkSize = 4096; // 4K 分段
|
||||
let totalChunks = Math.ceil(fileSize / chunkSize);
|
||||
let loadedChunks = 0;
|
||||
let fileContent = '';
|
||||
|
||||
// 显示加载进度
|
||||
showToast('正在加载文件... (0%)');
|
||||
|
||||
// 分段读取函数
|
||||
function readChunk(offset) {
|
||||
if (offset >= fileSize) {
|
||||
// 所有分块读取完成
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
setEditorMode(ext);
|
||||
editor.setValue(fileContent);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载成功');
|
||||
return;
|
||||
}
|
||||
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path) + '&offset=' + offset + '&size=' + chunkSize, function(response) {
|
||||
if (response.success) {
|
||||
// 使用js-base64库解码
|
||||
const chunkContent = Base64.decode(response.data);
|
||||
fileContent += chunkContent;
|
||||
loadedChunks++;
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.min(100, Math.round((loadedChunks / totalChunks) * 100));
|
||||
showToast('正在加载文件... (' + progress + '%)');
|
||||
|
||||
// 继续读取下一个分块
|
||||
setTimeout(function() {
|
||||
readChunk(response.offset + response.size);
|
||||
}, 10); // 短暂延迟,避免请求过于密集
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
}
|
||||
|
||||
// 开始读取第一个分块
|
||||
readChunk(0);
|
||||
} else {
|
||||
// 如果获取文件信息失败,尝试使用旧的一次性读取方式作为降级方案
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path), function(response) {
|
||||
if (response.success) {
|
||||
const content = Base64.decode(response.data);
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
setEditorMode(ext);
|
||||
editor.setValue(content);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载成功');
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
}
|
||||
}).fail(function() {
|
||||
// 如果获取文件信息接口失败,尝试使用旧的一次性读取方式
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path), function(response) {
|
||||
if (response.success) {
|
||||
const content = Base64.decode(response.data);
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
setEditorMode(ext);
|
||||
editor.setValue(content);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
showToast('文件加载成功');
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function() {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 保存文件 - 分段写入
|
||||
function saveFile() {
|
||||
if (!editor || !currentFile) {
|
||||
showToast('请先选择一个文件');
|
||||
return;
|
||||
}
|
||||
|
||||
const path = currentFile;
|
||||
const fullContent = editor.getValue();
|
||||
const chunkSize = 4096; // 4K 分段(字节数)
|
||||
let currentChunk = 0;
|
||||
let currentByteOffset = 0;
|
||||
|
||||
showToast('正在保存文件...');
|
||||
|
||||
// 使用TextEncoder API进行更高效的UTF-8字节处理
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
|
||||
// 基于字节数的字符串截取函数 - 优化版本
|
||||
function substrBytes(str, startByte, lengthBytes) {
|
||||
// 将整个字符串编码为Uint8Array以获取字节数据
|
||||
const bytes = encoder.encode(str);
|
||||
|
||||
// 确保截取范围在有效范围内
|
||||
const endByte = Math.min(startByte + lengthBytes, bytes.length);
|
||||
|
||||
// 截取指定范围的字节
|
||||
const chunkBytes = bytes.subarray(startByte, endByte);
|
||||
|
||||
// 将截取的字节解码回字符串
|
||||
const result = decoder.decode(chunkBytes);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 计算字符串的UTF-8字节长度 - 优化版本
|
||||
function getByteLength(str) {
|
||||
return encoder.encode(str).length;
|
||||
}
|
||||
|
||||
// 分段写入函数
|
||||
function writeChunk(byteOffset) {
|
||||
const totalBytes = getByteLength(fullContent);
|
||||
if (byteOffset >= totalBytes) {
|
||||
// 所有分块写入完成,请求服务器进行最终校验和重命名
|
||||
$.ajax({
|
||||
url: '/api/script/write/finalize',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
total_size: totalBytes
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('文件保存成功,但最终校验失败:' + response.message);
|
||||
console.warn('文件校验失败,但内容可能已保存:', response.message);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
// 即使最终校验请求失败,我们仍然告知用户文件已保存
|
||||
showToast('文件内容已保存,但最终处理请求失败');
|
||||
console.warn('最终处理请求失败');
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取当前分块内容(按字节数截取)
|
||||
const chunkContent = substrBytes(fullContent, byteOffset, chunkSize);
|
||||
|
||||
// 使用js-base64库编码
|
||||
const encodedContent = Base64.encode(chunkContent);
|
||||
|
||||
const nextByteOffset = byteOffset + getByteLength(chunkContent);
|
||||
const isFinal = nextByteOffset >= totalBytes;
|
||||
|
||||
// 更新进度
|
||||
currentChunk++;
|
||||
const totalByteChunks = Math.ceil(totalBytes / chunkSize);
|
||||
const progress = Math.min(100, Math.round((currentChunk / totalByteChunks) * 100));
|
||||
showToast('正在保存文件... (' + progress + '%)');
|
||||
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: encodedContent,
|
||||
offset: byteOffset,
|
||||
final: isFinal
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
// 继续写入下一个分块
|
||||
setTimeout(function() {
|
||||
writeChunk(response.offset);
|
||||
}, 10); // 短暂延迟,避免请求过于密集
|
||||
} else {
|
||||
showToast('保存文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
console.log('分段写入失败:', textStatus, errorThrown);
|
||||
showToast('保存文件失败:网络错误');
|
||||
// 如果分段写入失败,尝试使用旧的一次性写入方式作为降级方案
|
||||
console.log('分段写入失败,尝试一次性写入');
|
||||
const fullEncodedContent = Base64.encode(fullContent);
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: fullEncodedContent
|
||||
}),
|
||||
success: function(backupResponse) {
|
||||
if (backupResponse.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('保存文件失败:' + backupResponse.message);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showToast('保存文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 开始写入第一个分块
|
||||
writeChunk(currentByteOffset);
|
||||
}
|
||||
|
||||
// 删除当前文件
|
||||
function deleteCurrentFile() {
|
||||
if (!currentFile) {
|
||||
showToast('请先选择一个文件');
|
||||
return;
|
||||
}
|
||||
|
||||
if (confirm('确定要删除这个文件吗?')) {
|
||||
const path = currentFile;
|
||||
$.ajax({
|
||||
url: '/api/script/delete',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件删除成功');
|
||||
$('#currentFile').text('未选择文件');
|
||||
if (editor) editor.setValue('');
|
||||
$('#saveFile, #deleteFile').prop('disabled', true);
|
||||
currentFile = null;
|
||||
// 通知文件树刷新
|
||||
if (window.refreshFileTree) {
|
||||
window.refreshFileTree();
|
||||
}
|
||||
} else {
|
||||
showToast('删除文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('删除文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前编辑器实例
|
||||
function getEditor() {
|
||||
return editor;
|
||||
}
|
||||
|
||||
// 获取当前打开的文件路径
|
||||
function getCurrentFile() {
|
||||
return currentFile;
|
||||
}
|
||||
|
||||
// 导出模块
|
||||
export {
|
||||
initEditor,
|
||||
setEditorMode,
|
||||
loadFile,
|
||||
saveFile,
|
||||
deleteCurrentFile,
|
||||
getEditor,
|
||||
getCurrentFile
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
// 工具函数模块
|
||||
const UtilsModule = (function() {
|
||||
// Toast初始化
|
||||
const toastEl = document.getElementById('toast');
|
||||
const toast = new bootstrap.Toast(toastEl, {
|
||||
autohide: true,
|
||||
delay: 3000
|
||||
});
|
||||
|
||||
// 显示Toast提示
|
||||
function showToast(message) {
|
||||
$('.toast-body').text(message);
|
||||
toast.show();
|
||||
}
|
||||
|
||||
// 暴露公共方法
|
||||
return {
|
||||
showToast: showToast
|
||||
};
|
||||
})();
|
||||
|
||||
// 将需要在其他模块中直接使用的函数暴露到全局
|
||||
window.showToast = UtilsModule.showToast;
|
||||
@@ -0,0 +1,148 @@
|
||||
// WebSocket连接和消息处理模块
|
||||
const topic_control = '/dev/control';
|
||||
const topic_status = '/dev/status';
|
||||
const topic_response = '/dev/response';
|
||||
const topic_scanner_status = '/dev/status/scanner';
|
||||
const topic_scanner_data = '/dev/data/scanner';
|
||||
|
||||
let ws;
|
||||
let reconnectTimer;
|
||||
let scannerStateHandler = null;
|
||||
let scannerDataHandler = null;
|
||||
let responseHandler = null;
|
||||
|
||||
// 替换 client.publish 为 ws.send
|
||||
function wsPublish(topic, msg) {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({
|
||||
action: 'publish',
|
||||
topic: topic,
|
||||
message: msg
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function connectWebSocket() {
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsHost = location.hostname + (location.port ? ':' + location.port : '');
|
||||
const wsuri = wsProtocol + '//' + wsHost + '/ws';
|
||||
console.log('WebSocket URI:', wsuri);
|
||||
|
||||
ws = new WebSocket(wsuri);
|
||||
|
||||
ws.onopen = function() {
|
||||
showToast('已连接到WebSocket服务器');
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_status }));
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_scanner_status }));
|
||||
// 清除重连定时器
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
let data;
|
||||
//处理二进制数据
|
||||
if (event.data instanceof Blob) {
|
||||
console.log('收到二进制数据:', event.data.size);
|
||||
//处理Blob数据
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = function() {
|
||||
const arrayBuffer = reader.result;
|
||||
console.log('ArrayBuffer:', arrayBuffer);
|
||||
if (scannerDataHandler) {
|
||||
scannerDataHandler(topic_scanner_data, arrayBuffer);
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(event.data);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (e) {
|
||||
console.log('原始消息:', typeof event.data, event.data);
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
return;
|
||||
}
|
||||
const topic = data.topic;
|
||||
const message = data.message;
|
||||
|
||||
if (topic && message) {
|
||||
if (topic.startsWith(topic_response)) {
|
||||
if (responseHandler) {
|
||||
responseHandler(topic, message);
|
||||
}
|
||||
} else if (topic.startsWith(topic_scanner_status)) {
|
||||
if (scannerStateHandler) {
|
||||
scannerStateHandler(topic, message);
|
||||
}
|
||||
} else if (topic.startsWith(topic_scanner_data)) {
|
||||
if (scannerDataHandler) {
|
||||
scannerDataHandler(topic, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = function() {
|
||||
showToast('WebSocket连接错误');
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
showToast('WebSocket连接已关闭,正在尝试重连...');
|
||||
// 仅在没有活跃定时器时创建新的重连定时器
|
||||
if (!reconnectTimer) {
|
||||
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||
}
|
||||
};
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
// 设置扫描器状态处理器
|
||||
function setScannerStateHandler(handler) {
|
||||
scannerStateHandler = handler;
|
||||
}
|
||||
|
||||
// 设置扫描器数据处理器
|
||||
function setScannerDataHandler(handler) {
|
||||
scannerDataHandler = handler;
|
||||
}
|
||||
|
||||
// 设置响应处理器
|
||||
function setResponseHandler(handler) {
|
||||
responseHandler = handler;
|
||||
}
|
||||
|
||||
// 初始化WebSocket连接
|
||||
function initWebSocket() {
|
||||
connectWebSocket();
|
||||
|
||||
// 定时发送状态请求
|
||||
setInterval(function() {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
wsPublish(topic_control, {cmd: 'status'});
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
// 获取WebSocket实例
|
||||
function getWebSocket() {
|
||||
return ws;
|
||||
}
|
||||
|
||||
// 导出模块
|
||||
export {
|
||||
wsPublish,
|
||||
initWebSocket,
|
||||
setScannerStateHandler,
|
||||
setScannerDataHandler,
|
||||
setResponseHandler,
|
||||
getWebSocket,
|
||||
topic_control,
|
||||
topic_status,
|
||||
topic_response,
|
||||
topic_scanner_status
|
||||
};
|
||||
Reference in New Issue
Block a user