Weather station¶
A rooftop thermometer has no model to run but produces data that other agents want. In UNaIVERSE such a device is an agent without a processor (proc=None) that owns a stream and writes a sample into it every few seconds. This example builds a small world named WeatherNet with the station as its world master and every other member as a listener. The station broadcasts each reading once on a pubsub stream and every listener receives it at the same time.
The sources are in examples-src/weather-station/.
The station¶
"""The station owns one pubsub stream and writes a reading into it every DELTA seconds."""
import math
import random
import time
import torch
from unaiverse.agent import Agent, action
from unaiverse.streams import Stream, DataProps
DELTA = 5.0 # Seconds between two readings
def read_temperature() -> float:
"""A simulated sensor: replace it with the driver of a real one."""
return 18. + 4. * math.sin(time.time() / 600.) + random.gauss(0., 0.2)
class WAgent(Agent):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.stream = None
self.invited = set()
self.last_reading_at = 0.
def accept_new_role(self, role: int) -> None:
super().accept_new_role(role)
# One tensor of shape (1, 1) per reading, broadcast to the subscribers of the world
self.stream = Stream.create(stream=Stream(props=DataProps(name="temperature", data_type="tensor",
tensor_shape=(1, 1),
tensor_dtype=torch.float32,
data_desc="air temperature in degrees Celsius")),
group="weather", public=False, pubsub=True, delta=DELTA)
self.add_streams([self.stream])
self.update_streams_in_profile()
async def on_tick(self) -> None:
await super().on_tick()
now = time.monotonic()
if self.stream is not None and now - self.last_reading_at >= DELTA:
self.stream.set(torch.tensor([[read_temperature()]]))
self.last_reading_at = now
@action
async def invite_new_listeners(self) -> bool:
"""Asks the listeners found and not yet invited to subscribe to the readings."""
new = [p for p in self.get_agents_by_role("listener") if p not in self.invited]
if not new:
return False
_, private_peer_id = self.get_peer_ids()
net_hash = next(iter(self.find_streams(private_peer_id, "weather").keys()), None)
if net_hash is None or not await self.send_subscribe(new, stream_hashes=[net_hash]):
return False
self.invited.update(new)
return True
The station creates its stream in accept_new_role. This method runs once the world has assigned the role. Stream.create takes a plain Stream that describes its data and determines how the stream travels:
| Argument | Value here | Meaning |
|---|---|---|
group, name |
weather, temperature |
the stream is known as temperature@weather |
public |
False |
it lives in the network of the world, not in the public one |
pubsub |
True |
one broadcast per sample reaches every subscriber in place of one copy per recipient |
delta |
5.0 |
the minimum interval between two samples, in seconds |
add_streams makes the stream an owned stream of the agent and update_streams_in_profile publishes it in the profile for the other members to see. on_tick runs at every tick of an agent in a world right before its behavior acts. The station writes a new reading there every DELTA seconds. The SDK then sends each new sample of an owned pubsub stream to its subscribers.
read_temperature stands for the sensor. Replace it with the driver of a real sensor. The station needs only a function that returns a number.
Subscribing the listeners¶
A listener does not pick the stream by itself. The station asks it to subscribe:
sequenceDiagram
participant S as RooftopStation (station)
participant L as KitchenDisplay (listener)
L->>S: connect_by_role(role=station)
S->>S: find_agents(role=listener)
S->>L: send_subscribe(stream temperature@weather)
L->>L: subscribe (adds the stream, joins its topic)
loop every 5 s
S-->>L: reading (pubsub)
end
invite_new_listeners finds the net hash of its own stream with find_streams and calls send_subscribe with the listeners not invited yet. On the listener side the request fires the self-loop of state listening that runs the built-in action subscribe. This transition has ready=False and fires only on request. subscribe accepts only streams that match an input of the processor of the listener. This is why run_listener.py declares proc_inputs with tensors of shape (1, 1) even though the listener has no processor.
The listener¶
"""The listener prints every new reading of the station it is subscribed to."""
from unaiverse.agent import Agent
from unaiverse.utils.logger import log
class WAgent(Agent):
async def on_tick(self) -> None:
await super().on_tick()
for station in self.get_agents_by_role("station"):
for streams in self.find_streams(station, "weather").values():
for stream in streams.values():
# requested_by: each new sample is returned once to this caller
reading = stream.get(requested_by="listener")
if reading is not None:
log.user(f"Temperature: {reading.item():.1f} °C")
stream.get(requested_by="listener") returns the newest sample the first time a given caller asks for it and then returns None until a newer sample arrives. log.user writes on the USER channel of the logger. This channel is one of the three that are always printed (Configuration).
The world and the runners¶
"""A small weather network: one station streams its readings, every listener receives them."""
import os
import sys
from unaiverse.world import World
from unaiverse.hsm import HybridStateMachine
from unaiverse.networking.node.profile import NodeProfile
class WWorld(World):
def __init__(self, **kwargs):
super().__init__(world_folder=os.path.dirname(os.path.abspath(__file__)), **kwargs)
def assign_role(self, profile: NodeProfile, is_world_master: bool) -> str | None:
return "station" if is_world_master else "listener"
def create_behav_files(self) -> None:
assert self.world_folder is not None
sys.path.append(self.world_folder)
# Station: every few seconds, look for new listeners and ask them to subscribe to the readings
from .station import WAgent as Station
dummy = Station(proc=None)
behav = HybridStateMachine(dummy)
behav.set_role("station")
behav.set_welcome_message("You are the weather station of this world.")
behav.add_state("idle", waiting_time=5.0, blocking=False)
behav.add_state("found", blocking=False)
behav.add_transit("idle", "found", action="find_agents",
args={"role": "listener", "handshake_completed": True})
behav.add_transit("found", "idle", action="invite_new_listeners")
behav.add_transit("found", "idle", action="nop", delay=5.0)
behav.save(os.path.join(self.world_folder, "station.json"), only_if_changed=dummy)
# Listener: connect to the station and accept its subscription request
from .listener import WAgent as Listener
dummy = Listener(proc=None)
behav = HybridStateMachine(dummy)
behav.set_role("listener")
behav.set_welcome_message("Readings from the station will appear here.")
behav.add_state("init", waiting_time=2.0, blocking=False)
behav.add_state("station_found", blocking=True, msg="Connecting to the station...")
behav.add_state("listening", blocking=True)
behav.add_state("lost", blocking=False, msg="Lost the station, trying again in a minute.")
behav.add_transit("init", "station_found", action="connect_by_role", args={"role": "station"})
behav.add_transit("station_found", "listening", action="connected", args={"handshake_completed": True})
behav.add_transit("station_found", "lost", action="disconnected", delay=5.0, teleport=True)
behav.add_transit("listening", "listening", action="subscribe", ready=False)
behav.add_transit("listening", "lost", action="disconnected", teleport=True)
behav.add_transit("lost", "init", action="nop", delay=60.0, teleport=True)
behav.save(os.path.join(self.world_folder, "listener.json"), only_if_changed=dummy)
python run_world.py # WeatherNet
python run_station.py # RooftopStation, the world master
python run_listener.py # KitchenDisplay, and any other listener
Checked on the network
The three scripts ran on the network and the listener printed a new reading every 5 seconds. When the station invites a listener that is still connecting, the listener refuses that first request with Requested action (subscribe) not found and the station invites it again a few seconds later.