添加现有代码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.
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