Mostra l'agente e la sua fotocamera
La prima versione della vista si collega a Feeder e mostra il suo nome, la sua descrizione e i fotogrammi della sua fotocamera man mano che arrivano.
Un agente finto
Mentre sviluppi, Feeder è un agente finto che definisci nel tuo file e che connectToHost fa girare nella tua pagina:
const feeder = {
name: 'Feeder',
profile: { description: 'A camera at a bird feeder, in a garden.' },
data: { camera: { every: 100, value: frameAt } },
};
const agent = await connectToHost({ fake: { agent: feeder } });fake: { agent }crea un agente invece di un mondo (fake: { world }). Una vista li legge tutti e due con la stessa API.dataassocia a ogni nome che l'agente mostra il suo valore. Feeder mostra solocamerae l'agente finto ne calcola il valore chiamandoframeAt(time)ogni 100 ms (dieci volte al secondo).frameAtdisegna un pettirosso alla mangiatoia come SVG e lo restituisce come URIdata:. La vista tratta allo stesso modo i fotogrammi di un agente vero perché anche questi arrivano indatacome stringhe pronte perimg.src.
Dentro la webapp chiami connectToHost() senza fake e la sua Promise si risolve con l'agente che la persona ha aperto nella webapp.
Disegna l'agente
agent.subscribe(listener) chiama listener subito e poi dopo ogni cambiamento dell'agente (anche un nuovo fotogramma della fotocamera conta come cambiamento).
agent.subscribe((node) => {
title.textContent = node.name;
description.textContent = node.profile.description ?? '';
const frame = node.data.camera;
if (frame) picture.src = frame;
});node.profile.descriptionè la descrizione nel profilo dell'agente e valenullquando manca.node.data.cameraè un URL o un data URI pronto per losrcdi un<img>. Prima che arrivi il primo fotogramma il campo manca e la didascalia dice "Waiting for the first picture…".node.statusvale'connecting'mentre l'agente si collega e poi diventa'online'. Finché lo stato è'connecting', la didascalia dice "Connecting to Feeder…".
In React l'hook useWorld fa la sottoscrizione al posto tuo e a ogni cambiamento rifà il render del componente con l'agente più recente. L'esempio chiama la variabile agent invece di world:
const { world: agent, error } = useWorld({ fake: { agent: feeder } });Il codice
import { useWorld } from './useWorld.js';
// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
const x = 170 + 70 * Math.sin(time / 800);
const y = 120 - Math.abs(25 * Math.sin(time / 300));
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}
// A fake agent to build with. Its camera sends a new picture every 100 ms.
const feeder = {
name: 'Feeder',
profile: { description: 'A camera at a bird feeder, in a garden.' },
data: { camera: { every: 100, value: frameAt } },
};
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: feeder } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!agent) return <p>Connecting…</p>;
// `data.camera` is an image source, ready for an <img>. It is missing until the first picture arrives.
const frame = agent.data.camera;
let caption = frame ? `Live from ${agent.name}'s camera` : 'Waiting for the first picture…';
if (agent.status === 'connecting') caption = `Connecting to ${agent.name}…`;
return (
<>
<h1>{agent.name}</h1>
<p>{agent.profile.description}</p>
{frame && <img src={frame} alt={`${agent.name}'s camera`} width="320" height="180" />}
<p>{caption}</p>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
const x = 170 + 70 * Math.sin(time / 800);
const y = 120 - Math.abs(25 * Math.sin(time / 300));
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}
// A fake agent to build with. Its camera sends a new picture every 100 ms.
const feeder = {
name: 'Feeder',
profile: { description: 'A camera at a bird feeder, in a garden.' },
data: { camera: { every: 100, value: frameAt } },
};
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: feeder } });
// The page shows the name of the agent, what it is and its camera.
const title = document.createElement('h1');
const description = document.createElement('p');
const picture = document.createElement('img');
picture.width = 320;
picture.height = 180;
const caption = document.createElement('p');
document.body.append(title, description, picture, caption);
// Called at once, then after every change of the agent, a new picture included.
agent.subscribe((node) => {
title.textContent = node.name;
description.textContent = node.profile.description ?? '';
// `data.camera` is an image source, ready for an <img>. It is missing until the first picture arrives.
const frame = node.data.camera;
picture.hidden = !frame;
if (frame) picture.src = frame;
if (node.status === 'connecting') caption.textContent = `Connecting to ${node.name}…`;
else caption.textContent = frame ? `Live from ${node.name}'s camera` : 'Waiting for the first picture…';
});L'uccello si muove e l'orologio nell'angolo va avanti perché ogni fotogramma è un'immagine nuova.
Prossimi passi
Ognuno dei dieci fotogrammi al secondo ridisegna ancora tutta la vista. Nel passo 2: Segui le immagini della fotocamera la fotocamera riceve un listener tutto suo.
I dati del mondo tratta data per intero e subscribe ha una sua pagina nel riferimento.