volttron.platform.agent package

Submodules

volttron.platform.agent.bacnet_proxy_reader module

class volttron.platform.agent.bacnet_proxy_reader.BACnetReader(vip, bacnet_proxy_identity, iam_response_fn=None, config_response_fn=None, batch_size=20)[source]

Bases: object

The BACnetReader

get_iam(device_id, callback, address=None, timeout=10)[source]
read_device_description(address, device_id)[source]

Reads the device name from the specified address and device_id

Parameters:
  • address – Address of the bacnet device
  • device_id – The device id of the bacnet device.
Returns:

The device desciption or an empty string

read_device_name(address, device_id)[source]

Reads the device name from the specified address and device_id

Parameters:
  • address – Address of the bacnet device
  • device_id – The device id of the bacnet device.
Returns:

The device name or the string “MISSING DEVICE NAME”

read_device_properties(target_address, device_id, filter=None)[source]

Starts the processes of reading a device’s meta data.

The device will first be queried for all of it’s objects. For each of the returned indexes only the properties that have a presentValue as a property will be used. Processing of the objects will continue in batches until all of the device points have been received.

Data will ultimately be written through the self._emit_reresponses function. The self._response_function that was set in the constructor of the object will be used to return the data to the caller.

Parameters:
  • target_address – The address of the bacnet device
  • device_id – The device_id of the bacnet device
  • filter – A list of two-tuples with (bacnet_type, [index]) where the bacnet_type is one of the bacnet_type strings and the [index] is an array of indexes to return.
start_whois(low_device_id=None, high_device_id=None, target_address=None)[source]
stop_iam_responses()[source]

volttron.platform.agent.base module

VOLTTRON platform™ base agent and helper classes/functions.

volttron.platform.agent.base.periodic(period, *args, **kwargs)[source]

Decorator to set a method up as a periodic callback.

The decorated method will be called with the given arguments every period seconds while the agent is executing its run loop.

class volttron.platform.agent.base.BaseAgent(subscribe_address, **kwargs)[source]

Bases: volttron.platform.agent.base.AgentBase

Base class for creating VOLTTRON platform™ agents.

This class can be used as is, but it won’t do much. It will sit and do nothing but listen for messages and exit when the platform shutdown message is received. That is it.

LOOP_INTERVAL = 60
closed

Return whether the subscription channel is closed.

finish()[source]

Finish for the agent execution loop.

Extend this method with code that must run once after the main loop. Be sure to call the base class implementation from the overridden method.

handle_sub_message(block=False)[source]

Handle incoming messages on the subscription socket.

Receives a multipart message containing a topic, headers, and zero or more message parts. For each prefix (key) in subscriptions map matching the beginning of the topic, the associated callback will be called if either no test is associated with the callback or the test function returns a value evaluating to True.

See the class documentation for more information on the signature for test and callback functions.

loop()[source]

Main agent execution loop.

This method should rarely need to be overridden. Instead, override the step method to customize execution behavior. The default implementation loops until self.closed() returns True calling self.step() each iteration.

periodic_timer(period, function, *args, **kwargs)[source]

Create a periodic timer to call function every period seconds.

Like the timer method except that the timer is automatically rearmed after the function completes.

poll(timeout=None)[source]

Polls for events while handling timers.

poll() will wait up to timeout seconds for sockets or files registered with self.reactor to become ready. A timeout of None will cause poll to wait an infinite amount of time. While waiting for poll events, scheduled events will be handled, potentially causing the wait time to slip a bit.

run()[source]

Entry point for running agent.

Subclasses should not override this method. Instead, the setup, step, and finish methods should be overridden to customize behavior.

schedule(time, event)[source]

Schedule an event to run at the given wall time.

time must be a datetime object or a Unix time value as returned by time.time(). event must be a callable accepting a single argument, the time the event was scheduled to run, and must return a time to be scheduled next or None to not reschedule. sched.Event and sched.RecurringEvent are examples of this interface and may be used here. Generators send functions are also be good candidates for event functions.

setup()[source]

Setup for the agent execution loop.

Extend this method with code that must run once before the main loop. Be sure to call the base class implementation from the overridden method.

step(timeout=None)[source]

Performs a single step in the main agent loop.

Override this method to customize agent behavior. The default method blocks indefinitely until at least one socket in the reactor is ready and then run each associated callback. The method can be called from the overridden method in a subclass with the behavior customized by passing in different timeout. timeout is the maximum number of seconds (can be fractional) to wait or None to wait indefinitely. Returns the number of events fired or zero if a timeout occured.

subscribe(prefix, callback=None, test=None)[source]

Subscribe to topic and register callback.

Subscribes to topics beginning with prefix. If callback is supplied, it should be a function taking four arguments, callback(topic, headers, message, match), where topic is the full message topic, headers is a case-insensitive dictionary (mapping) of message headers, message is a possibly empty list of message parts, and match is the return value of the test function or None if test is None.

If test is given, it should be a function taking two arguments, test(topic, prefix), where topic is the complete topic of the incoming message and prefix is the string which caused the subscription match. The test function should return a true value if the callback should be called or a false value otherwise. The result of the test will be passed into the callback function where the results can be used.

Returns and ID number which can be used later to unsubscribe.

timer(interval, function, *args, **kwargs)[source]

Create a timer to call function after interval seconds.

interval is specified in seconds and can include fractional part. function is a function that takes the optional args and kwargs. Returns a timer object that can be used to modify the callback parameters or to cancel using the cancel() method.

unsubscribe(handler_id, prefix=None)[source]

Remove subscription handler by its ID.

Remove all handlers matching the given handler ID, which is the ID returned by the subscribe method. If all handlers for a topic prefix are removed, the topic is also unsubscribed.

unsubscribe_all(prefix)[source]

Remove all handlers for the given prefix and unsubscribe.

If prefix is None, unsubscribe from all topics and remove all handlers. Otherwise, unsubscribe from the given topic and remove all handlers for that topic prefix.

class volttron.platform.agent.base.PublishMixin(publish_address, **kwargs)[source]

Bases: volttron.platform.agent.base.AgentBase

Agent mix-in for publishing to the VOLTTRON publish socket.

Connects the agent to the publish channel and provides several publish methods.

Include before BaseAgent class in subclass list.

ping_back(callback, timeout=None, period=1)[source]
publish(topic, headers, *msg_parts, **kwargs)[source]

Publish a message to the publish channel. Adds volttron platform version compatibility information to header as variables min_compatible_version and max_compatible version

publish_ex(topic, headers, *msg_tuples, **kwargs)[source]

Publish messages given as (content-type, message) tuples. Adds volttron platform version compatibility information to header as variables min_compatible_version and max_compatible version

publish_json(topic, headers, *msg_parts, **kwargs)[source]

Publish JSON encoded message. Adds volttron platform version compatibility information to header as variables min_compatible_version and max_compatible version

volttron.platform.agent.base_aggregate_historian module

volttron.platform.agent.base_historian module

volttron.platform.agent.base_tagging module

volttron.platform.agent.base_weather module

volttron.platform.agent.cron module

volttron.platform.agent.driven module

VOLTTRON platform™ abstract agent for to drive VOLTTRON Nation apps.

class volttron.platform.agent.driven.AbstractDrivenAgent(out=None, **kwargs)[source]

Bases: object

classmethod output_format(input_object)[source]

The output object takes the resulting input object as a argument so that it may give correct topics to it’s outputs if needed.

output schema description

{TableName1: {name1:OutputDescriptor1, name2:OutputDescriptor2,…},….}

eg: {‘OAT’: {‘Timestamp’:OutputDescriptor(‘timestamp’, ‘foo/bar/timestamp’),’OAT’:OutputDescriptor(‘OutdoorAirTemperature’, ‘foo/bar/oat’)},
‘Sensor’: {‘SomeValue’:OutputDescriptor(‘integer’, ‘some_output/value’), ‘SomeOtherValue’:OutputDescriptor(‘boolean’, ‘some_output/value), ‘SomeString’:OutputDescriptor(‘string’, ‘some_output/string)}}

Should always call the parent class output_format and update the dictionary returned from the parent.

result = super().output_format(input_object) my_output = {…} result.update(my_output) return result

run(time, inputs)[source]

Do work for each batch of timestamped inputs time- current time inputs - dict of point name -> value

Must return a results object.

shutdown()[source]

Override this to add shutdown routines.

class volttron.platform.agent.driven.ConversionMapper(**kwargs)[source]

Bases: object

process_row(row_dict)[source]
setup_conversion_map(conversion_map_config, field_names)[source]
class volttron.platform.agent.driven.Results(terminate=False)[source]

Bases: object

command(point, value, device=None)[source]
insert_table_row(table, row)[source]
log(message, level=10)[source]
terminate(terminate)[source]

volttron.platform.agent.exit_codes module

volttron.platform.agent.green module

VOLTTRON platform™ greenlet coroutine helper classes/functions.

These utilities are meant to be used with the BaseAgent and greenlet to provide synchronization between light threads (coroutines).

exception volttron.platform.agent.green.Timeout[source]

Bases: exceptions.Exception

Raised in the greenlet when waiting on a channel times out.

class volttron.platform.agent.green.WaitQueue(create_timer)[source]

Bases: object

A holder for tasklets waiting on asynchronous data.

kill_all()[source]

Kill all the tasks in the queue.

notify(data, n=1)[source]

Notify n waiting tasks of the arrival of data.

notify_all(data)[source]

Notify all waiting tasks of the arrival of data.

wait(timeout=None)[source]

Wait for data to become available and return it

If timeout is None, wait indefinitely. Otherwise, timeout if the task hasn’t been notified within timeout seconds.

volttron.platform.agent.green.sleep(timeout, create_timer)[source]

Yield execution for timeout seconds.

volttron.platform.agent.json module

Wrapper around UJSON to protect against NaN values and also to increase the performance involved in serialization and deserialization of data.

volttron.platform.agent.json.dumps(data, **kwargs)[source]
volttron.platform.agent.json.loads(s, **kwargs)[source]

volttron.platform.agent.known_identities module

volttron.platform.agent.matching module

VOLTTRON platform™ topic matching for agent callbacks.

Declaratively attach topic prefix and additional tests for topic matching to agent methods allowing for automated callback registration and topic subscription.

Example:

class MyAgent(BaseAgent):
    @match_regex('topic1/(sub|next|part)/title[1-9]')
    def on_subtopic(topic, headers, message, match):
        # This is only executed if topic matches regex
        ...

    @match_glob('root/sub/*/leaf')
    def on_leafnode(topic, headers, message, match):
        # This is only executed if topic matches glob
        ...

    @match_exact('building/xyz/unit/condenser')
    @match_start('campus/PNNL')
    @match_end('unit/blower')
    def on_multimatch(topic, headers, message, match):
        # Multiple matchers can be attached to a method
        ...
volttron.platform.agent.matching.iter_match_tests(obj)[source]

Iterate match tests attached to the methods of an object.

Each iterated item is the 3-tuple (prefix, method, test) where prefix and test are the same as in match_test() and method is the method to which the test was attached (and is the expected callback).

volttron.platform.agent.matching.match_all(func)[source]

Wildcard matcher to register callback for every message.

volttron.platform.agent.matching.match_contains(substring, prefix='')[source]

Return a match decorator to match a component of a topic.

volttron.platform.agent.matching.match_end(suffix, prefix='')[source]

Return a match decorator to match the end of a topic.

volttron.platform.agent.matching.match_exact(topic)[source]

Return a match decorator to match a topic exactly.

volttron.platform.agent.matching.match_glob(pattern)[source]

Return a match decorator for the given glob pattern.

volttron.platform.agent.matching.match_headers(required_headers)[source]

Only call function if required headers match.

match_headers takes a single argument, required_headers, that is a dictionary containing the required headers and values that must match for the wrapped handler function to be called.

This decorator is not very useful on its own, because it doesn’t trigger any subscriptions, but can be useful to filter out messages that don’t contain the required headers and values.

volttron.platform.agent.matching.match_regex(pattern)[source]

Return a match decorator for the given regular expression.

volttron.platform.agent.matching.match_start(prefix)[source]

Return a match decorator to match the start of a topic.

volttron.platform.agent.matching.match_subtopic(prefix, subtopic, max_levels=None)[source]

Return a match decorator to match a subtopic.

volttron.platform.agent.matching.match_test(prefix, test=None)[source]

Decorate a callback method with subscription and test information.

Returns a decorator to attach (prefix, test) 2-tuples to methods which can be inspected to automatically subscribe to a topic prefix and provide a test for triggering a call back to the method.

prefix must match the start of a desired topic and test is either None or a function of the form test(topic, matched) where topic is the full topic to test against and matched should be the same as prefix. The test function must return a value that evaluates to True if the topic is a match or a value that evaluates to False otherwise. The test function is only called if topic.startswith(prefix) is True. If test is None, it is the same as if test = lambda topic, matched: True.

volttron.platform.agent.matching.test_contains(substring)[source]

Return a test function to match a topic containing substring.

volttron.platform.agent.matching.test_end(suffix)[source]

Return a test function to match the end of a topic.

volttron.platform.agent.matching.test_exact(topic, matched)[source]

Test if topic and match are exactly equal.

volttron.platform.agent.matching.test_glob(pattern)[source]

Return static prefix and regex test for glob pattern.

The pattern may include the following special wildcard patterns:

*      Matches zero or more characters.
**     Matches zero or more characters, including forward
       slashes (/).
?      Matches any single character
[...]  Matches any single characters between the brackets.  A
       range of adjacent characters may be matched using a
       hyphen (-) between the start and end character.  To
       include the hyphen as a search character, include it at
       the end of the pattern.  The range may be negated by
       immediately following the opening [ with a ^ or !.
volttron.platform.agent.matching.test_regex(pattern)[source]

Return the static prefix and a regex test function for pattern.

volttron.platform.agent.matching.test_subtopic(subtopic, max_levels=None)[source]

Return a test function to match a topic component after the prefix.

volttron.platform.agent.math_utils module

Dumping ground for VOLTTRON platform™ agent math helper functions.

Not meant to replace numpy in all cases. A basic set common math routines to remove the need for numpy in simple cases.

This module should NEVER import numpy as that would defeat the purpose.

volttron.platform.agent.math_utils.mean(data)[source]

Return the sample arithmetic mean of data.

volttron.platform.agent.math_utils.pstdev(data)[source]

Calculates the population standard deviation.

volttron.platform.agent.math_utils.stdev(data)[source]

Calculates the sample standard deviation.

volttron.platform.agent.multithreading module

VOLTTRON platform™ multi-threaded agent helper classes/functions.

These utilities are meant to be used with the BaseAgent and threading to provide synchronization between threads and the main agent loop.

exception volttron.platform.agent.multithreading.Timeout[source]

Bases: exceptions.Exception

Raised in the thread when waiting on a queue times out.

class volttron.platform.agent.multithreading.WaitQueue(lock=None)[source]

Bases: object

A holder for threads waiting on asynchronous data.

notify(data, n=1)[source]

Notify n waiting threads of the arrival of data.

notify_all(data)[source]

Notify all waiting threads of the arrival of data.

wait(timeout=None)[source]

Wait for data to become available and return it

If timeout is None, wait indefinitely. Otherwise, timeout if the thread hasn’t been notified within timeout seconds.

volttron.platform.agent.sched module

VOLTTRON platform™ agent event scheduling classes.

class volttron.platform.agent.sched.Event(function, args=None, kwargs=None)[source]

Bases: object

Base class for schedulable objects.

args
cancel()[source]

Mark the timer as canceled to avoid a callback.

canceled
finished
function
kwargs
class volttron.platform.agent.sched.EventWithTime(function, args=None, kwargs=None)[source]

Bases: volttron.platform.agent.sched.Event

Event that passes deadline to event handler.

class volttron.platform.agent.sched.Queue[source]

Bases: object

delay(time)[source]
execute(time)[source]
schedule(time, event)[source]
class volttron.platform.agent.sched.RecurringEvent(period, function, args=None, kwargs=None)[source]

Bases: volttron.platform.agent.sched.Event

period

volttron.platform.agent.utils module

VOLTTRON platform™ agent helper classes/functions.

volttron.platform.agent.utils.load_config(config_path)[source]

Load a JSON-encoded configuration file.

volttron.platform.agent.utils.run_agent(cls, subscribe_address=None, publish_address=None, config_path=None, **kwargs)[source]

Instantiate an agent and run it in the current thread.

Attempts to get keyword parameters from the environment if they are not set.

volttron.platform.agent.utils.start_agent_thread(cls, **kwargs)[source]

Instantiate an agent class and run it in a new daemon thread.

Returns the thread object.

volttron.platform.agent.utils.is_valid_identity(identity_to_check)[source]

Checks the passed identity to see if it contains invalid characters

A None value for identity_to_check will return False

@:param: string: The vip_identity to check for validity @:return: boolean: True if values are in the set of valid characters.

volttron.platform.agent.utils.load_platform_config(vhome=None)[source]

Loads the platform config file if the path exists.

volttron.platform.agent.utils.get_messagebus()[source]

Get type of message bus - zeromq or rabbbitmq.

volttron.platform.agent.utils.get_fq_identity(identity, platform_instance_name=None)[source]

Return the fully qualified identity for the passed core identity.

Fully qualified identities are instance_name.identity

Parameters:
  • identity
  • platform_instance_name – str The name of the platform.
Returns:

volttron.platform.agent.utils.execute_command(cmds, env=None, cwd=None, logger=None, err_prefix=None)[source]

volttron.platform.agent.web module

class volttron.platform.agent.web.Response(content=None, status=None, headers=None, mimetype=None, content_type=None)[source]

Bases: object

The WebResponse object is a serializable representation of a response to an http(s) client request that can be transmitted through the RPC subsystem to the appropriate platform’s MasterWebAgent

add_header(key, value)[source]
content
headers
process_data(data)[source]
status