RTU/test/web_root/js/monitor.js

72 lines
1.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* monitor.js — 数据监控器
* 环形缓冲记录所有 WebSocket 收发消息15 分钟自动清理超时记录
*/
var MonitorRing = (function() {
var records = [];
var MAX_RECORDS = 500;
var TTL_MS = 900000; // 15 分钟
var cleanTimer = null;
function push(dir, raw) {
var now = Date.now();
records.push({
time: now,
dir: dir, // '↑' 上行发送, '↓' 下行接收
data: raw
});
// 超出上限时截掉旧数据
while (records.length > MAX_RECORDS) {
records.shift();
}
}
function getAll() {
return records.slice();
}
function count() {
return records.length;
}
function cleanOld() {
var cutoff = Date.now() - TTL_MS;
var i = 0;
while (i < records.length && records[i].time < cutoff) {
i++;
}
if (i > 0) {
records.splice(0, i);
}
}
function clear() {
records = [];
}
// 每 60 秒自动清理
function startAutoClean() {
if (cleanTimer) return;
cleanTimer = setInterval(cleanOld, 60000);
}
function stopAutoClean() {
if (cleanTimer) {
clearInterval(cleanTimer);
cleanTimer = null;
}
}
// 启动自动清理
startAutoClean();
return {
push: push,
getAll: getAll,
count: count,
cleanOld: cleanOld,
clear: clear
};
})();