添加现有代码V1.6
This commit is contained in:
@@ -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
|
||||
};
|
||||
})();
|
||||
Reference in New Issue
Block a user