Skip to content

Subscribing and notifications

An agent subscribed to a node receives a notification each time an item is published in it, or retracted from it. Register a callback to handle them.

Receiving the items

Register a callback with set_on_item_published(). It is called with each notification: an XMPP message (slixmpp.Message), with the node and the item in message["pubsub_event"]["items"]:

from spade.agent import Agent
from spade_pubsub import PubSubMixin


class SubscriberAgent(PubSubMixin, Agent):
    def on_item(self, message):
        items = message["pubsub_event"]["items"]
        item = items["item"]
        print(f"Node {items['node']}, item {item['id']}: {item['payload'].text}")

    async def setup(self):
        self.pubsub.set_on_item_published(self.on_item)
        await self.pubsub.subscribe("pubsub.localhost", "news")
Value What it is
message["pubsub_event"]["items"]["node"] The name of the node.
message["pubsub_event"]["items"]["item"]["id"] The ID of the item.
message["pubsub_event"]["items"]["item"]["payload"] The payload: the XML element published (.text for a text).
message["from"] The PubSub service.

The callback can also be a coroutine (async def on_item(self, message)), e.g. to send a message or to call other PubSub operations.

One callback for every node

The callback receives the notifications of all the nodes the agent is subscribed to: check message["pubsub_event"]["items"]["node"] to tell them apart. Calling set_on_item_published() again adds another callback (both are called).

From a callback to a behaviour

To handle the items in a behaviour, put them in an asyncio.Queue in the callback, and await queue.get() in the behaviour.

Register the callback before subscribing, so that no notification is missed. Depending on the node, the service may also send the last item (or all the items) when the agent subscribes.

Retracted items

def on_retracted(self, message):
    items = message["pubsub_event"]["items"]
    print(f"Item {items['retract']['id']} retracted from node {items['node']}")

self.pubsub.set_on_item_retracted(on_retracted)

The callback of set_on_item_retracted() is called when an item is retracted from a node the agent is subscribed to, and the service notifies it (see Retracting an item).

Subscribing to a node

subid = await self.agent.pubsub.subscribe(PUBSUB, "news")

subscribe() returns the subscription ID given by the service (or None if it gives none, or if the subscription was refused). Keep it to unsubscribe if the service gives one.

Who can subscribe depends on the node configuration (pubsub#access_model): anyone, in the XMPP server of SPADE. An agent subscribes its own JID: the service refuses to subscribe another one (subscription_jid), unless it is allowed to manage subscriptions.

Unsubscribing

await self.agent.pubsub.unsubscribe(PUBSUB, "news", subid=subid)

After unsubscribing, the agent receives no more notifications from the node.