graphicek/client/js/index.js

92 lines
2.0 KiB
JavaScript

const { html, render } = lighterhtml;
const $container = document.getElementById("sensors-container");
function load() {
fetch("/api/sensors")
.then((r) => r.json())
.then((sensors) => {
const components = sensors.map((sensor) => createSensor(sensor));
components.forEach((component) =>
$container.appendChild(component.container)
);
});
}
function createSensor(sensor) {
const container = document.createElement("div");
container.className = "sensor";
const header = document.createElement("div");
header.className = "header";
const body = document.createElement("div");
body.className = "body";
const renderHeader = () => {
render(
header,
html`
<div class="name">${sensor.config?.name ?? sensor.sensor}</div>
<div class="actions">
<button class="config">Config</button>
<button class="refresh" onClick=${refreshValues}>Refresh</button>
</div>
`
);
};
const renderBody = (range, values) => {
const { from, to } = range;
Plotly.newPlot(
body,
[
{
type: "lines",
x: values.map((v) => new Date(v.timestamp * 1000)),
y: values.map((v) => v.value),
},
],
{
xaxis: { range: [from, to], type: "date" },
margin: {
l: 50,
r: 20,
b: 60,
t: 20,
pad: 5,
},
},
{
responsive: true,
}
);
};
const refreshValues = () => {
const from = new Date(Date.now() - 5 * 24 * 3600 * 1000);
const to = new Date();
fetch(
`/api/sensors/${sensor.sensor}/values?from=${Math.round(
from.getTime() / 1000
)}&to=${Math.round(to.getTime() / 1000)}`
)
.then((r) => r.json())
.then((values) => renderBody({ from, to }, values));
};
renderHeader();
refreshValues();
container.appendChild(header);
container.appendChild(body);
return {
container,
};
}
load();