const thermocoupleTypeTable = ["uV", "B", "E", "J", "K", "N", "R", "S", "T"];
const elements = {
read: {
vdd: document.getElementById("vdd"),
vref: document.getElementById("vref"),
vadj: document.getElementById("vadj"),
ts: document.getElementById("timestamp"),
table: document.getElementById("data"),
},
config: {
table: document.getElementById("thermocouple"),
},
};
let readOldChannelCount = 0;
let configOldChannelCount = 0;
async function fetchData(url) {
const response = await fetch(url);
return response.json();
}
function clearTableBody(tableType) {
const table = elements[tableType].table;
const tbody = table.querySelector("tbody");
if (tbody) {
tbody.innerHTML = "";
} else {
// If tbody doesn't exist, recreate it
const newTbody = document.createElement("tbody");
table.appendChild(newTbody);
}
}
function updateTable(data, tableType, oldChannelCount, updateFunction) {
clearTableBody(tableType);
oldChannelCount = 0;
data.channels.forEach((channel) => {
updateFunction(channel, tableType);
oldChannelCount++;
});
}
function updateReadTable(channel, tableType) {
const { value, id } = channel;
const row = elements[tableType].table.querySelector("tbody").insertRow(-1);
row.insertCell(0).innerText = id;
row.insertCell(1).innerText = value.toFixed(2);
}
function updateConfigTable(channel, tableType) {
const { id, thermocouple, gain, offset, filter } = channel;
const row = elements[tableType].table.querySelector("tbody").insertRow(-1);
row.insertCell(0).innerText = id;
row.insertCell(1).innerText = thermocoupleTypeTable[thermocouple];
row.insertCell(2).innerText = gain;
row.insertCell(3).innerText = offset;
row.insertCell(4).innerText = filter.sample_size;
row.insertCell(5).innerText = filter.type;
}
function updateOthers(data) {
const { ratio, time } = data;
elements.read.ts.innerText = time;
elements.read.vref.innerHTML = `VREF: ${ratio.vref}`;
elements.read.vadj.innerHTML = `VADJ: ${ratio.vadj.toFixed(4)}`;
elements.read.vdd.innerHTML = `VDD: ${ratio.pivdd.toFixed(4)}`;
}
async function updateRead() {
const data = await fetchData("/v1/data");
updateTable(data, "read", readOldChannelCount, updateReadTable);
updateOthers(data);
}
async function updateConfig() {
const data = await fetchData("/v1/config/channels");
updateTable(data, "config", configOldChannelCount, updateConfigTable);
}
updateRead();
updateConfig();
setInterval(updateRead, 1000);
setInterval(updateConfig, 10000);
// websocket demo
const ws = new WebSocket("ws://" + window.location.host + "/ws");
ws.onopen = (e) => {
console.log("Connection open");
ws.send("ALL");
};
ws.onmessage = (e) => {
console.log("msg recv: " + e.data);
};
ws.onclose = (e) => {
console.log("Connection close");
};