Renamed variables, clarified structure

This commit is contained in:
Jarno Rankinen 2023-01-17 21:05:31 +02:00
parent a4a19458f6
commit 3fd6669687
3 changed files with 35 additions and 23 deletions

View File

@ -1,13 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../static/tabledata.css">
<script src="../static/tabledata.js"></script>
<link rel="stylesheet" href="/static/tabledata.css">
<script src="/static/tabledata.js"></script>
<meta charset="UTF-8">
<title>Enervent Pingvin Kotilämpö</title>
</head>
<body onload="getData()">
<table id="coils">
<table id="data">
<caption>Coil values at <span id="time"></span></caption>
<thead><th>Address</th><th>Value</th><th>Symbol</th><th>Description</th></thead>
<tbody id="coildata"></tbody>

View File

@ -4,7 +4,7 @@
.val {
text-align: center;
}
#coils {
#data {
padding: 2pt;
border-collapse: collapse;
}

View File

@ -13,30 +13,42 @@ function getData() {
S = zeroPad(now.getSeconds())
document.getElementById('time').innerHTML = `${Y}-${m}-${d} ${H}:${M}:${S}`
error = false
// The same index.html is used for both coil and register data,
// change api url based on which we're looking at
if (document.location.pathname == "/coils/") {
url = "/api/v1/coils"
}
else if (document.location.pathname == "/registers/") {
url = "/api/v1/registers"
}
error = false
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`Error fetching data: ${response.status}`)
}
return response.json()
})
.then((coils) => {
document.getElementById('coildata').innerHTML = "";
for (n=0; n<coils.length; n++) {
tablerow = `<tr><td class="addr" id="addr_${coils[n].address}">${coils[n].address}</td>\
<td class ="val" id="value_${coils[n].address}">${Number(coils[n].value)}</td>\
<td class="symbol" id="symbol_${coils[n].address}">${coils[n].symbol}</td>\
<td class="desc" id="description_${coils[n].address}">${coils[n].description}</td></tr>`
document.getElementById('coildata').innerHTML += tablerow
}
});
else {
document.getElementById("data").innerHTML = 'Page not found'
error = true
}
if (!error) {
// Fetch data from API
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`Error fetching data: ${response.status}`)
}
return response.json()
})
.then((data) => {
// Populate table
document.getElementById('coildata').innerHTML = "";
for (n=0; n<data.length; n++) {
tablerow = `<tr><td class="addr" id="addr_${data[n].address}">${data[n].address}</td>\
<td class ="val" id="value_${data[n].address}">${Number(data[n].value)}</td>\
<td class="symbol" id="symbol_${data[n].address}">${data[n].symbol}</td>\
<td class="desc" id="description_${data[n].address}">${data[n].description}</td></tr>`
document.getElementById('coildata').innerHTML += tablerow
}
});
}
if (!error) setTimeout(getData, 5*1000);
// Using setTimeout instead of setInterval to avoid possible connection issues
// There's no need to update exactly every 5 seconds, the skew is fine
setTimeout(getData, 5*1000);
}