Un grafico di un numero nel tempo
Un grafico di un numero nel tempo ha bisogno dei valori precedenti oltre che del più recente. In data c'è invece solo il valore più recente di ogni nome. dataHistory(name) restituisce i valori recenti di un nome dal più vecchio al più recente con il momento di ciascuno. Nell'esempio la serra invia una nuova temperatura due volte al secondo e la vista disegna la cronologia come una linea che ridisegna a ogni nuovo valore.
jsx
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// In the fake greenhouse, the temperature changes twice a second.
const greenhouse = {
name: 'Greenhouse',
data: { temperature: { every: 500, value: (time) => Math.round((22 + 2 * Math.sin(time / 3000)) * 10) / 10 } },
};
// The range of the chart, in °C, and its size.
const LOW = 18;
const HIGH = 26;
const WIDTH = 300;
const HEIGHT = 100;
// Turns the readings into the points of an SVG line, the oldest on the left and the newest on the right.
function pointsOf(history) {
const step = WIDTH / Math.max(history.length - 1, 1);
return history.map((reading, index) => `${index * step},${HEIGHT - ((reading.value - LOW) / (HIGH - LOW)) * HEIGHT}`).join(' ');
}
// A line of the recent temperatures.
function TemperatureChart({ world }) {
const [history, setHistory] = useState([]);
useEffect(() => {
// dataHistory() gives the recent values of one name, oldest first (await it).
const load = async () => setHistory(await world.dataHistory('temperature'));
load();
// Load them again at every new reading.
return world.onData('temperature', load);
// This runs once, because `dataHistory` and `onData` work from any copy of `world`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} width={WIDTH} height={HEIGHT} style={{ border: '1px solid #8888' }}>
<polyline points={pointsOf(history)} fill="none" stroke="#d35400" strokeWidth="2" />
</svg>
<p>The last {history.length} readings, from {LOW} to {HIGH} °C.</p>
</>
);
}
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: greenhouse } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<h2>{world.name}</h2>
<p>Temperature now: {world.data.temperature} °C</p>
<TemperatureChart world={world} />
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// In the fake greenhouse, the temperature changes twice a second.
const greenhouse = {
name: 'Greenhouse',
data: { temperature: { every: 500, value: (time) => Math.round((22 + 2 * Math.sin(time / 3000)) * 10) / 10 } },
};
// The range of the chart, in °C, and its size.
const LOW = 18;
const HIGH = 26;
const WIDTH = 300;
const HEIGHT = 100;
// Turns the readings into the points of an SVG line, the oldest on the left and the newest on the right.
function pointsOf(history) {
const step = WIDTH / Math.max(history.length - 1, 1);
return history.map((reading, index) => `${index * step},${HEIGHT - ((reading.value - LOW) / (HIGH - LOW)) * HEIGHT}`).join(' ');
}
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: greenhouse } });
const title = document.createElement('h2');
const reading = document.createElement('p');
const SVG = 'http://www.w3.org/2000/svg';
const chart = document.createElementNS(SVG, 'svg');
chart.setAttribute('viewBox', `0 0 ${WIDTH} ${HEIGHT}`);
chart.setAttribute('width', WIDTH);
chart.setAttribute('height', HEIGHT);
chart.style.border = '1px solid #8888';
const line = document.createElementNS(SVG, 'polyline');
line.setAttribute('fill', 'none');
line.setAttribute('stroke', '#d35400');
line.setAttribute('stroke-width', '2');
chart.append(line);
const caption = document.createElement('p');
document.body.append(title, reading, chart, caption);
world.subscribe((node) => {
title.textContent = node.name;
reading.textContent = `Temperature now: ${node.data.temperature} °C`;
});
async function drawChart() {
// dataHistory() gives the recent values of one name, oldest first (await it).
const history = await world.dataHistory('temperature');
line.setAttribute('points', pointsOf(history));
caption.textContent = `The last ${history.length} readings, from ${LOW} to ${HIGH} °C.`;
}
drawChart();
// Draw it again at every new reading.
world.onData('temperature', drawChart);Come funziona
- La webapp conserva per te fino agli ultimi 200 valori di ogni nome e
await world.dataHistory('temperature')li restituisce come[{ value, time }, …]dal più vecchio al più recente. Usa sempreawaitperché nella webapp la chiamata restituisce unaPromise. world.onData('temperature', load)chiamaloada ogni nuovo valore eloadridisegna il grafico dalla cronologia.- Il grafico è una sola
<polyline>SVG.pointsOfdispone i valori dal più vecchio sul bordo sinistro al più recente sul bordo destro e daLOWin basso aHIGHin alto.
Vedi anche
- Chart: un componente per i grafici.
dataHistoryeonData.- Segui i dati veloci senza rallentare.