Publishing items¶
An item is a piece of information published in a node. The service stores it (depending on the node configuration) and sends it to every subscriber of the node.
Who can publish in a node depends on its configuration (pubsub#publish_model): by default, only its owner (and the
agents that the owner makes publishers). In the XMPP server of SPADE, only the owner publishes.
Publishing an item¶
publish() returns the ID of the item, given by the service, or None if the service refused it (see
Errors).
To choose the ID of the item, pass it as fourth argument. Publishing again an item with the same ID replaces it:
await self.agent.pubsub.publish(PUBSUB, "weather", "Sunny, 25 ºC", "valencia")
await self.agent.pubsub.publish(PUBSUB, "weather", "Cloudy, 22 ºC", "valencia") # replaces it
The payload¶
The payload of an item is an XML element:
- A text is sent inside a
<payload xmlns="spade.pubsub"/>element, and the subscribers read it in itstext. - An XML element (
xml.etree.ElementTree.Element) is sent as it is. Use it to publish structured data, or to interoperate with other XMPP applications that expect a format (e.g. an Atom entry):
from xml.etree.ElementTree import Element, SubElement
reading = Element("{urn:example:sensors}reading", attrib={"unit": "celsius"})
SubElement(reading, "{urn:example:sensors}value").text = "21.5"
await self.agent.pubsub.publish(PUBSUB, "sensors", reading)
Publishing objects
To publish a Python object, serialize it to a text, e.g. with json.dumps(), and read it with json.loads() in
the subscribers.
Reading the items of a node¶
items = await self.agent.pubsub.get_items(PUBSUB, "news")
for item_id, payload in items:
print(item_id, payload.text)
get_items() returns a list of tuples (id, payload), where payload is the XML element published: an empty list if
the node has no items, or if the agent cannot read them. Who can read the items depends on the node configuration
(pubsub#access_model). In the XMPP server of SPADE, the owner and the subscribers of the node can.
Retracting an item¶
retract() removes an item from the node. With notify=True, the subscribers are notified of the retraction (see
Retracted items). Without it, the node configuration (pubsub#notify_retract)
decides: the XMPP server of SPADE always notifies them.
Notifications without items¶
notify() publishes without an item: the subscribers are notified, but nothing is stored. Only transient,
notification-only nodes accept it (pubsub#persist_items and pubsub#deliver_payloads false): other nodes,
including the nodes of the XMPP server of SPADE, answer with an item-required error.