Repository navigation
Expand file tree
/
Copy pathdashboard.js
More file actions
258 lines (234 loc) · 8.24 KB
/
Copy pathdashboard.js
File metadata and controls
258 lines (234 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// dashboard.js (v3)
// - Eje temporal real (fecha + hora)
// - Filtros con datetime-local (zoom por fecha y hora)
// - Segundo eje Y para Latencia
// - Cache-busting al leer data.json
// - Modo oscuro que ajusta ejes/grillas
// - Zoom/pan opcional (si chartjs-plugin-zoom esta cargado)
let datos = [];
let chart = null;
let modoOscuro = false;
// Parse "YYYY-MM-DD HH:mm:ss" a Date local
function parseFechaHora(s) {
return new Date(s.replace(' ', 'T'));
}
// Cargar data.json con cache-busting y manejo de errores
async function cargarDatos() {
try {
const url = 'data.json?t=' + Date.now();
const resp = await fetch(url, { cache: 'no-store' });
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const raw = await resp.json();
// Asegurar orden cronologico
raw.sort((a, b) => parseFechaHora(a.FechaHora) - parseFechaHora(b.FechaHora));
datos = raw;
if (datos.length > 0) {
mostrarUltimoResultado();
construirGrafico(datos);
} else {
document.getElementById('ultimoDetalle').textContent = 'Sin datos disponibles.';
construirGrafico([]);
}
} catch (e) {
console.error('Error cargando data.json:', e);
document.getElementById('ultimoDetalle').textContent = 'Error cargando datos.';
construirGrafico([]);
}
}
// Mostrar ultimo registro
function mostrarUltimoResultado() {
const u = datos[datos.length - 1];
const html =
'Fecha: ' + u.FechaHora + '<br>' +
'Descarga: ' + Number(u.Download).toFixed(2) + ' Mbps<br>' +
'Subida: ' + Number(u.Upload).toFixed(2) + ' Mbps<br>' +
'Latencia: ' + Number(u.Latency).toFixed(2) + ' ms';
document.getElementById('ultimoDetalle').innerHTML = html;
}
// Construir/actualizar grafico
function construirGrafico(arr) {
const ctx = document.getElementById('speedChart').getContext('2d');
if (chart) chart.destroy();
if (!arr || arr.length === 0) {
chart = new Chart(ctx, { type: 'line', data: { datasets: [] }, options: { responsive: true } });
aplicarTema();
return;
}
const puntosDescarga = arr.map(r => ({ x: parseFechaHora(r.FechaHora), y: Number(r.Download) }));
const puntosSubida = arr.map(r => ({ x: parseFechaHora(r.FechaHora), y: Number(r.Upload) }));
const puntosLatencia = arr.map(r => ({ x: parseFechaHora(r.FechaHora), y: Number(r.Latency) }));
// Linea de referencia en 10 Mbps
const thresholdPlugin = {
id: 'thresholdLine',
afterDatasetsDraw(c) {
const { ctx, scales } = c;
const yScale = scales.yMbps; if (!yScale) return;
const y = yScale.getPixelForValue(10);
ctx.save();
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
ctx.strokeStyle = getTheme().gridStrong;
ctx.beginPath();
ctx.moveTo(scales.x.left, y);
ctx.lineTo(scales.x.right, y);
ctx.stroke();
ctx.setLineDash([]);
ctx.font = '10px sans-serif';
ctx.fillStyle = getTheme().tick;
ctx.fillText('Umbral 10 Mbps', scales.x.left + 6, y - 4);
ctx.restore();
}
};
chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{ label: 'Descarga (Mbps)', data: puntosDescarga, yAxisID: 'yMbps', borderWidth: 1.5, tension: 0.1, pointRadius: 2, pointHoverRadius: 4 },
{ label: 'Subida (Mbps)', data: puntosSubida, yAxisID: 'yMbps', borderWidth: 1.5, tension: 0.1, pointRadius: 1, pointHoverRadius: 3 },
{ label: 'Latencia (ms)', data: puntosLatencia, yAxisID: 'yMs', borderWidth: 1.5, tension: 0.1, pointRadius: 1, pointHoverRadius: 3 }
]
},
options: {
parsing: false,
responsive: true,
maintainAspectRatio: false,
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { position: 'top', labels: { color: getTheme().tick } },
decimation: { enabled: false },
tooltip: {
callbacks: {
title(items) {
const d = items[0].parsed.x;
return new Date(d).toLocaleString();
},
label(ctx) {
const v = Number(ctx.parsed.y).toFixed(2);
return ctx.dataset.label.includes('Latencia') ? `${ctx.dataset.label}: ${v} ms`
: `${ctx.dataset.label}: ${v} Mbps`;
}
}
},
// Zoom/pan si plugin esta disponible
zoom: {
zoom: {
wheel: { enabled: true, modifierKey: 'ctrl' },
pinch: { enabled: true },
mode: 'x'
},
pan: { enabled: true, modifierKey: 'shift', mode: 'x' }
}
},
scales: {
x: {
type: 'time',
time: {
parser: 'yyyy-MM-dd HH:mm:ss',
tooltipFormat: 'yyyy-MM-dd HH:mm:ss',
displayFormats: {
minute: 'yyyy-MM-dd HH:mm',
hour: 'yyyy-MM-dd HH:mm',
day: 'yyyy-MM-dd'
}
},
ticks: { color: getTheme().tick, maxRotation: 45, minRotation: 0 },
grid: { color: getTheme().grid }
},
yMbps: {
beginAtZero: true,
title: { display: true, text: 'Mbps' },
ticks: { color: getTheme().tick },
grid: { color: getTheme().grid }
},
yMs: {
position: 'right',
beginAtZero: true,
title: { display: true, text: 'ms' },
ticks: { color: getTheme().tick },
grid: { color: getTheme().gridFaint, drawOnChartArea: false }
}
}
},
plugins: [thresholdPlugin]
});
aplicarTema();
}
// Filtrar por fecha y hora (inputs datetime-local)
function filtrarDatos() {
const startVal = document.getElementById('startDateTime').value;
const endVal = document.getElementById('endDateTime').value;
if (!startVal || !endVal) {
alert('Selecciona fecha y hora en ambos campos.');
return;
}
// datetime-local: "YYYY-MM-DDTHH:mm" o "YYYY-MM-DDTHH:mm:ss"
const startDt = new Date(startVal.length === 16 ? startVal + ':00' : startVal);
const endDt = new Date(endVal.length === 16 ? endVal + ':59' : endVal); // inclusivo al minuto
const filtrado = datos.filter(item => {
const dt = parseFechaHora(item.FechaHora);
return dt >= startDt && dt <= endDt;
});
if (filtrado.length > 0) {
construirGrafico(filtrado);
const u = filtrado[filtrado.length - 1];
const html =
'Fecha: ' + u.FechaHora + '<br>' +
'Descarga: ' + Number(u.Download).toFixed(2) + ' Mbps<br>' +
'Subida: ' + Number(u.Upload).toFixed(2) + ' Mbps<br>' +
'Latencia: ' + Number(u.Latency).toFixed(2) + ' ms';
document.getElementById('ultimoDetalle').innerHTML = html;
} else {
construirGrafico([]);
document.getElementById('ultimoDetalle').textContent = 'Sin datos en este rango.';
}
}
// Resetear filtro a todo el rango cargado
function resetearFiltro() {
construirGrafico(datos);
mostrarUltimoResultado();
const s = document.getElementById('startDateTime');
const e = document.getElementById('endDateTime');
if (s) s.value = '';
if (e) e.value = '';
resetearZoom();
}
// Resetear zoom (si plugin esta disponible)
function resetearZoom() {
if (chart && typeof chart.resetZoom === 'function') {
chart.resetZoom();
}
}
// Modo oscuro
function toggleModoOscuro() {
modoOscuro = !modoOscuro;
document.body.classList.toggle('dark-mode', modoOscuro);
aplicarTema();
}
// Paletas para claro/oscuro
function getTheme() {
if (modoOscuro) {
return { tick: '#e6e6e6', grid: '#3a3a3a', gridFaint: '#2b2b2b', gridStrong: '#666666' };
}
return { tick: '#333333', grid: '#e5e5e5', gridFaint: '#f2f2f2', gridStrong: '#999999' };
}
// Aplicar colores del tema a ejes/leyenda
function aplicarTema() {
if (!chart) return;
const t = getTheme();
const o = chart.options;
o.scales.x.ticks.color = t.tick;
o.scales.x.grid.color = t.grid;
o.scales.yMbps.ticks.color = t.tick;
o.scales.yMbps.grid.color = t.grid;
o.scales.yMs.ticks.color = t.tick;
o.scales.yMs.grid.color = t.gridFaint;
o.plugins.legend.labels.color = t.tick;
chart.update('none');
}
// Exponer funciones para los botones del HTML
window.filtrarDatos = filtrarDatos;
window.resetearFiltro = resetearFiltro;
window.resetearZoom = resetearZoom;
window.toggleModoOscuro = toggleModoOscuro;
// Cargar al inicio
cargarDatos();