ws-siemens/static/script.js
Gašper Dobrovoljc 0c0d82db42
Initial commit
2023-03-13 14:50:49 +01:00

83 lines
1.5 KiB
JavaScript

const dataNode = document.getElementById('data');
const ctx = document.getElementById('chart');
const table = document.getElementById('table');
const target = document.getElementById('target');
const socket = new WebSocket('ws://127.0.0.1:1234');
socket.addEventListener('open', (e) => {
console.log('connection opened');
});
socket.addEventListener('close', (e) => {
console.log('connection closed');
});
Chart.defaults.set('plugins.streaming', {
duration: 20000,
});
const data = [];
const labels = [];
const targets = [];
const chart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [
{
label: 'Value',
data: data,
borderWidth: 1,
},
{
label: 'Target',
data: targets,
borderWidth: 1,
},
],
},
options: {
animations: false,
scales: {
y: {
beginAtZero: true,
},
},
},
});
chart.resize(1300, 600);
function updateTable(data) {
if (table.rows.length == 20) {
table.rows[table.rows.length - 1].remove();
}
const tr = table.insertRow(1);
tr.innerHTML = `
<td>${new Date().toLocaleString()}</td>
<td>${data}</td>
`;
}
socket.addEventListener('message', (e) => {
const value = Math.round(parseInt(e.data) / 2.83) / 100;
dataNode.innerText = value;
data.push(value);
labels.push(new Date().toLocaleString());
if (data.length > 100) {
data.shift();
labels.shift();
targets.shift();
}
chart.update();
updateTable(value);
targets.push(target.value);
});