-
Notifications
You must be signed in to change notification settings - Fork 1
ListenerAgent
The ListenerAgent subscribes to all topics and is useful for testing that agents being developed are publishing correctly. It also provides a template for building other agents as it expresses the requirements of a platform agent.
ListenerAgent publishes a heartbeat message so it will use the PublishMixin. It also extends BaseAgent to get the default functionality. When creating agents, Mixins should be first in the class definition.
class ListenerAgent(PublishMixin, BaseAgent):
'''Listens to everything and publishes a heartbeat according to the
heartbeat period specified in the settings module.
'''
ListenerAgent subscribes to all topics by using volttron.lite.matching. This package contains decorators for simplifying subscriptions. ListenerAgent uses match_all to receive all messages:
@matching.match_all
def on_match(self, topic, headers, message, match):
'''Use match_all to receive all messages and print them out.'''
print "Topic: {topic}, Headers: {headers}, Message: {message}".format(
topic=topic, headers=headers, message=message)
ListenerAgent uses the @periodic decorator to execute the pubheartbeat method every HEARTBEAT_PERIOD seconds where HEARTBEAT_PERIOD is specified in the settings.py file. In order to publish, it creates a Header object to set the ContentType of the message, the time the event was created, and the id of the agent sending it. This allows other agents to filter out messages of a certain type or from a certain agent. It also allows them to interpret the content appropriately. The message it then published out on the heartbeat topic.
# Demonstrate periodic decorator and settings access
@periodic(settings.HEARTBEAT_PERIOD)
def publish_heartbeat(self):
'''Send heartbeat message every HEARTBEAT_PERIOD seconds.
HEARTBEAT_PERIOD is set and can be adjusted in the settings module.
'''
now = datetime.utcnow().isoformat(' ') + 'Z'
headers = {
'AgentID': self._agent_id,
headers_mod.CONTENT_TYPE: headers_mod.CONTENT_TYPE.PLAIN_TEXT,
headers_mod.DATE: now,
}
self.publish('heartbeat/listeneragent', headers, now)