示例#1
0
    def __init__(self, config_path, **kwargs):
        Agent.__init__(self, **kwargs)
        myTransactiveNode.__init__(self)

        self.config_path = config_path
        self.config = utils.load_config(config_path)
        self.name = self.config.get('name')
        self.market_cycle_in_min = int(
            self.config.get('market_cycle_in_min', 60))
        self.duality_gap_threshold = float(
            self.config.get('duality_gap_threshold', 0.01))
        self.supplier_loss_factor = float(
            self.config.get('supplier_loss_factor'))
        self.neighbors = []

        self.db_topic = self.config.get("db_topic", "tnc")
        self.campus_demand_topic = "{}/campus/city/demand".format(
            self.db_topic)
        self.city_supply_topic = "{}/city/campus/supply".format(self.db_topic)

        self.reschedule_interval = timedelta(minutes=10, seconds=1)

        self.simulation = self.config.get('simulation', False)
        self.simulation_start_time = parser.parse(
            self.config.get('simulation_start_time'))
        self.simulation_one_hour_in_seconds = int(
            self.config.get('simulation_one_hour_in_seconds'))

        Timer.created_time = datetime.now()
        Timer.simulation = self.simulation
        Timer.sim_start_time = self.simulation_start_time
        Timer.sim_one_hr_in_sec = self.simulation_one_hour_in_seconds
示例#2
0
    def __init__(self, config_path, **kwargs):
        Agent.__init__(self, **kwargs)
        myTransactiveNode.__init__(self)

        self.config_path = config_path
        self.config = utils.load_config(config_path)
        self.name = self.config.get('name')
        self.market_cycle_in_min = int(self.config.get('market_cycle_in_min', 60))
        self.duality_gap_threshold = float(self.config.get('duality_gap_threshold', 0.01))
        self.building_names = self.config.get('buildings', [])
        self.building_powers = self.config.get('building_powers')

        self.neighbors = []

        self.city_supply_topic = 'tnsmarket/city/campus/supply'
        self.building_demand_topic = 'tnsmarket/{}/campus/demand'
        self.campus_demand_topic = 'tnsmarket/campus/city/demand'
        self.campus_supply_topic = 'tnsmarket/campus/{}/supply'

        self.reschedule_interval = timedelta(minutes=10, seconds=1)

        self.simulation = self.config.get('simulation', False)
        self.simulation_start_time = parser.parse(self.config.get('simulation_start_time'))
        self.simulation_one_hour_in_seconds = int(self.config.get('simulation_one_hour_in_seconds'))

        Timer.created_time = datetime.now()
        Timer.simulation = self.simulation
        Timer.sim_start_time = self.simulation_start_time
        Timer.sim_one_hr_in_sec = self.simulation_one_hour_in_seconds
    def __init__(self, config_path, **kwargs):
        Agent.__init__(self, **kwargs)
        TransactiveNode.__init__(self)

        self.config_path = config_path
        self.config = utils.load_config(config_path)
        self.name = self.config.get('name')
        self.market_cycle_in_min = int(
            self.config.get('market_cycle_in_min', 60))
        self.duality_gap_threshold = float(
            self.config.get('duality_gap_threshold', 0.01))
        self.supplier_loss_factor = float(
            self.config.get('supplier_loss_factor'))

        self.demand_threshold_coef = float(
            self.config.get('demand_threshold_coef'))
        self.monthly_peak_power = float(self.config.get('monthly_peak_power'))

        self.neighbors = []

        self.db_topic = self.config.get("db_topic", "tnc")
        #self.db_topic = self.config.get("db_topic", "record")
        self.campus_demand_topic = "{}/campus/city/demand".format(
            self.db_topic)
        self.city_supply_topic = "{}/city/campus/supply".format(self.db_topic)
        self.system_loss_topic = "{}/{}/system_loss".format(
            self.db_topic, self.name)
        self.dc_threshold_topic = "{}/{}/dc_threshold_topic".format(
            self.db_topic, self.name)

        self.reschedule_interval = timedelta(minutes=10, seconds=1)

        self.simulation = self.config.get('simulation', False)
        self.simulation_start_time = parser.parse(
            self.config.get('simulation_start_time'))
        self.simulation_one_hour_in_seconds = int(
            self.config.get('simulation_one_hour_in_seconds'))

        Timer.created_time = Timer.get_cur_time()
        Timer.simulation = self.simulation
        Timer.sim_start_time = self.simulation_start_time
        Timer.sim_one_hr_in_sec = self.simulation_one_hour_in_seconds
        self._stop_agent = False
        self.campus = None
        # New TNT db topics
        self.transactive_operation_topic = "{}/{}/transactive_operation".format(
            self.db_topic, self.name)
        self.local_asset_topic = "{}/{}/local_assets".format(
            self.db_topic, self.name)
        self.neighbor_topic = "{}/{}/neighbors".format(self.db_topic,
                                                       self.name)
        self.transactive_record_topic = "{}/{}/transactive_record".format(
            self.db_topic, self.name)
        self.market_balanced_price_topic = "{}/{}/market_balanced_prices".format(
            self.db_topic, self.name)
        self.market_topic = "{}/{}/market".format(self.db_topic, self.name)
        self.real_time_duration = self.config.get('real_time_market_duration',
                                                  15)
        self.start_tent_market_topic = "{}/start_tent".format(self.db_topic)
示例#4
0
    def __init__(self, config_path, **kwargs):
        Agent.__init__(self, **kwargs)
        myTransactiveNode.__init__(self)

        self.config_path = config_path
        self.config = utils.load_config(config_path)
        self.name = self.config.get('name')
        self.market_cycle_in_min = int(
            self.config.get('market_cycle_in_min', 60))
        self.duality_gap_threshold = float(
            self.config.get('duality_gap_threshold', 0.01))
        self.building_names = self.config.get('buildings', [])
        self.building_powers = self.config.get('building_powers')
        self.db_topic = self.config.get("db_topic", "tnc")
        self.PV_max_kW = float(self.config.get("PV_max_kW"))
        self.city_loss_factor = float(self.config.get("city_loss_factor"))

        self.demand_threshold_coef = float(
            self.config.get('demand_threshold_coef'))
        self.monthly_peak_power = float(self.config.get('monthly_peak_power'))

        self.neighbors = []

        self.city_supply_topic = "{}/city/campus/supply".format(self.db_topic)
        self.building_demand_topic = "/".join(
            [self.db_topic, "{}/campus/demand"])
        self.campus_demand_topic = "{}/campus/city/demand".format(
            self.db_topic)
        self.campus_supply_topic = "/".join(
            [self.db_topic, "campus/{}/supply"])
        self.solar_topic = "/".join([self.db_topic, "campus/pv"])
        self.system_loss_topic = "{}/{}/system_loss".format(
            self.db_topic, self.name)
        self.dc_threshold_topic = "{}/{}/dc_threshold_topic".format(
            self.db_topic, self.name)
        self.price_topic = "{}/{}/marginal_prices".format(
            self.db_topic, self.name)

        self.reschedule_interval = timedelta(minutes=10, seconds=1)

        self.simulation = self.config.get('simulation', False)
        self.simulation_start_time = parser.parse(
            self.config.get('simulation_start_time'))
        self.simulation_one_hour_in_seconds = int(
            self.config.get('simulation_one_hour_in_seconds'))

        Timer.created_time = datetime.now()
        Timer.simulation = self.simulation
        Timer.sim_start_time = self.simulation_start_time
        Timer.sim_one_hr_in_sec = self.simulation_one_hour_in_seconds
def test_delete_credential(volttron_instance_web):
    instance = volttron_instance_web
    auth_pending = instance.dynamic_agent.vip.rpc.call(
        AUTH, "get_authorization_pending").get()
    print(f"Auth pending is: {auth_pending}")
    len_auth_pending = len(auth_pending)
    with with_os_environ(instance.env):
        pending_agent = Agent(identity="PendingAgent3")
        task = gevent.spawn(pending_agent.core.run)
        task.join(timeout=5)
        pending_agent.core.stop()

        auth_pending = instance.dynamic_agent.vip.rpc.call(
            AUTH, "get_authorization_pending").get()
        print(f"Auth pending is: {auth_pending}")
        assert len(auth_pending) == len_auth_pending + 1

        instance.dynamic_agent.vip.rpc.call(
            AUTH, "delete_authorization_failure",
            auth_pending[0]["user_id"]).wait(timeout=4)
        gevent.sleep(2)
        auth_pending = instance.dynamic_agent.vip.rpc.call(
            AUTH, "get_authorization_pending").get()

        assert len(auth_pending) == len_auth_pending
示例#6
0
def build_agent(address=None, identity=None, publickey=None, secretkey=None,
                timeout=10, serverkey=None, **kwargs):
    """ Builds a dynamic agent connected to the specifiedd address.

    :param address:
    :param identity:
    :param publickey:
    :param secretkey:
    :param timeout:
    :param kwargs:
    :return:
    """
    if not address:
        address = os.environ['VOLTTRON_HOME']

    _log.debug('BUILDING AGENT VIP: {}'.format(address))
    vip_address = build_vip_address_string(
        vip_root=address, publickey=publickey, secretkey=secretkey,
        serverkey=serverkey)
    agent = Agent(address=vip_address, identity=identity)
    event = gevent.event.Event()
    gevent.spawn(agent.core.run, event)
    event.wait(timeout=timeout)
    _log.debug('RETURNING AGENT')

    return agent
def get_configs(config_id, output_directory):


    keystore = KeyStore()
    agent = Agent(address=get_address(),
                  publickey=keystore.public, secretkey=keystore.secret,
                  enable_store=False)

    event = gevent.event.Event()
    gevent.spawn(agent.core.run, event)
    event.wait()

    config_list = agent.vip.rpc.call(CONFIGURATION_STORE,
                           'manage_list_configs',
                           config_id).get(timeout=10)

    if not config_list:
        print "Config store", config_id, "does not exist."
        return

    ensure_dir(output_directory)

    os.chdir(output_directory)

    for config in config_list:
        print "Retrieving configuration", config
        raw_config = agent.vip.rpc.call(CONFIGURATION_STORE,
                           'manage_get',
                           config_id,
                           config, raw=True).get(timeout=10)

        ensure_dir(os.path.dirname(config))

        with open(config, "w") as f:
            f.write(raw_config)
示例#8
0
    def __init__(self, agentid, lock, dev, msgque, raw_queue, message_bus):
        Process.__init__(self)
        self.lock = lock
        self.msgque = msgque
        self.raw_queue = raw_queue
        ident = 'Agent' + str(agentid)
        self.agent = Agent(address=get_address(), identity=ident, message_bus=message_bus)
        event = gevent.event.Event()
        self.agent._agentid = 'Agent' + str(agentid)

        self.task = gevent.spawn(self.agent.core.run, event)

        event.wait(timeout=2)

        self.agent.vip.pubsub.subscribe('pubsub', 'devices', self.on_message)

        _log.debug("Process id: {}".format(os.getpid()))
        eprint("eprint - Process id: {}".format(os.getpid()))
        self.count = 0
        self.publishes = 0
        self.data_list = [[], [], [], [], []]
        self.delta_list = []
        self.msg = []
        self.devices = dev
        self.max_publishes = 5*dev
        self.utcnow_string = ''
示例#9
0
def build_agent(address=None,
                identity=None,
                publickey=None,
                secretkey=None,
                timeout=10,
                serverkey=None,
                **kwargs):
    """ Builds a dynamic agent connected to the specifiedd address.

    All key parameters should have been encoded with
    :py:meth:`volttron.platform.vip.socket.encode_key`

    :param str address: VIP address to connect to
    :param str identity: Agent's identity
    :param str publickey: Agent's Base64-encoded CURVE public key
    :param str secretkey: Agent's Base64-encoded CURVE secret key
    :param str serverkey: Server's Base64-encoded CURVE public key
    :param int timeout: Seconds to wait for agent to start
    :param kwargs: Any Agent specific parameters
    :return: Agent that has been started
    :rtype: Agent
    """
    agent = Agent(address=address,
                  identity=identity,
                  publickey=publickey,
                  secretkey=secretkey,
                  serverkey=serverkey)
    event = gevent.event.Event()
    gevent.spawn(agent.core.run, event)
    event.wait(timeout=timeout)
    return agent
示例#10
0
    def __init__(self,
                 address,
                 peer=None,
                 publickey=None,
                 secretkey=None,
                 serverkey=None,
                 volttron_home=None,
                 **kwargs):
        _log.debug("Connection: {}, {}, {}, {}, {}".format(
            address, peer, publickey, secretkey, serverkey))
        self._address = address
        self._peer = peer
        self._serverkey = None
        if peer is None:
            _log.warn('Peer is non so must be passed in call method.')
        self.volttron_home = volttron_home

        if self.volttron_home is None:
            self.volttron_home = os.path.abspath(platform.get_home())

        if address.startswith('ipc'):
            full_address = address
        else:
            parsed = urlparse.urlparse(address)
            if parsed.scheme == 'tcp':
                qs = urlparse.parse_qs(parsed.query)
                _log.debug('QS IS: {}'.format(qs))
                if 'serverkey' in qs:
                    self._serverkey = qs.get('serverkey')
                else:
                    self._serverkey = serverkey

                # Handle case when the address has all the information in it.
                if 'serverkey' in qs.keys() and 'publickey' in qs.keys() and \
                                'secretkey' in qs.keys():
                    full_address = address
                else:
                    full_address = build_vip_address_string(
                        vip_root=address,
                        serverkey=serverkey,
                        publickey=publickey,
                        secretkey=secretkey)
            elif parsed.scheme == 'ipc':
                full_address = address
            else:
                raise AttributeError(
                    'Invalid address type specified. ipc or tcp accepted.')
        self._server = Agent(address=full_address,
                             volttron_home=self.volttron_home,
                             enable_store=False,
                             reconnect_interval=1000,
                             **kwargs)
        self._greenlet = None
        self._connected_since = None
        self._last_publish = None
        self._last_publish_failed = False
        self._last_rpc_call = None
        # Make the actual attempt to connect to the server.
        self.is_connected()
示例#11
0
def mock_masterweb_service():
    MasterWebService.__bases__ = (AgentMock.imitate(Agent, Agent()), )
    masterweb = MasterWebService(serverkey=MagicMock(),
                                 identity=MagicMock(),
                                 address=MagicMock(),
                                 bind_web_address=MagicMock())
    rpc_caller = masterweb.vip.rpc
    masterweb._admin_endpoints = AdminEndpoints(rpc_caller=rpc_caller)
    yield masterweb
示例#12
0
 def __init__(self):
     self.address = get_address()
     self.peer = 'messagedebugger'
     self._server = Agent(identity='message.viewer',
                          address=self.address,
                          publickey=KeyStore().public,
                          secretkey=KeyStore().secret,
                          serverkey=KnownHostsStore().serverkey(self.address),
                          enable_store=False,
                          enable_channel=True)
     self._greenlet = None
示例#13
0
 def connect_to_remote_volttron_bus(self):
     ''' Uses destination's ip to connect to a remote volttron bus at that ip. Must be valid ip to not raise an exception.
     '''
     agent = Agent(identity=self.destination_platform,
                   address=self.destination_vip)
     event = gevent.event.Event()
     _log.info('vip and platform %r and %r', self.destination_platform,
               self.destination_vip)
     gevent.spawn(agent.core.run, event)
     event.wait()
     self._target_platform = agent
     print(self._agent_id)
    def __init__(self, config_path, **kwargs):
        Agent.__init__(self, **kwargs)

        self.config_path = config_path
        self.config = utils.load_config(config_path)
        self.name = self.config.get('name')
        self.T = int(self.config.get('T', 24))

        self.db_topic = self.config.get("db_topic", "tnc")
        self.campus_demand_topic = "{}/campus/city/demand".format(
            self.db_topic)
        self.city_supply_topic = "{}/city/campus/supply".format(self.db_topic)

        self.simulation = self.config.get('simulation', False)
        self.simulation_start_time = parser.parse(
            self.config.get('simulation_start_time'))
        self.simulation_one_hour_in_seconds = int(
            self.config.get('simulation_one_hour_in_seconds'))

        Timer.created_time = datetime.now()
        Timer.simulation = self.simulation
        Timer.sim_start_time = self.simulation_start_time
        Timer.sim_one_hr_in_sec = self.simulation_one_hour_in_seconds

        # Initialization
        self.error_energy_threshold = float(
            self.config.get('error_energy_threshold'))
        self.error_reserve_threshold = float(
            self.config.get('error_reserve_threshold'))
        self.alpha_energy = float(self.config.get('alpha_energy'))
        self.alpha_reserve = float(self.config.get('alpha_reserve'))
        self.iteration_threshold = int(self.config.get('iteration_threshold'))

        self.init()
        self.grid_supplier = Generator()

        self.power_demand = []
        self.committed_reserves = []
        self.power_supply = []
        self.desired_reserves = []
示例#15
0
def mock_platformweb_service() -> PlatformWebService:
    PlatformWebService.__bases__ = (AgentMock.imitate(Agent, Agent()), )
    platformweb = PlatformWebService(serverkey=MagicMock(),
                                     identity=MagicMock(),
                                     address=MagicMock(),
                                     bind_web_address=MagicMock())
    # rpc_caller = platformweb.vip.rpc
    # platformweb._admin_endpoints = AdminEndpoints(rpc_caller=rpc_caller)

    # Internally the register uses this value to determine the caller's identity
    # to allow the platform web service to map calls back to the proper agent
    platformweb.vip.rpc.context.vip_message.peer.return_value = "foo"

    yield platformweb
示例#16
0
def install_configs(input_directory, keep=False):
    os.chdir(input_directory)

    keystore = KeyStore()
    agent = Agent(address=get_address(),
                  identity="master_driver_update_agent",
                  publickey=keystore.public,
                  secretkey=keystore.secret,
                  enable_store=False)

    event = gevent.event.Event()
    gevent.spawn(agent.core.run, event)
    event.wait()

    if not keep:
        print("Deleting old Master Driver store")
        agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_delete_store',
                           PLATFORM_DRIVER).get(timeout=10)

    with open("config") as f:
        print("Storing main configuration")
        agent.vip.rpc.call(CONFIGURATION_STORE,
                           'manage_store',
                           PLATFORM_DRIVER,
                           'config',
                           f.read(),
                           config_type="json").get(timeout=10)

    for name in glob.iglob("registry_configs/*"):
        with open(name) as f:
            print("Storing configuration:", name)
            agent.vip.rpc.call(CONFIGURATION_STORE,
                               'manage_store',
                               PLATFORM_DRIVER,
                               name,
                               f.read(),
                               config_type="csv").get(timeout=10)

    for dir_path, _, files in os.walk("devices"):
        for file_name in files:
            name = os.path.join(dir_path, file_name)
            with open(name) as f:
                print("Storing configuration:", name)
                agent.vip.rpc.call(CONFIGURATION_STORE,
                                   'manage_store',
                                   PLATFORM_DRIVER,
                                   name,
                                   f.read(),
                                   config_type="json").get(timeout=10)
示例#17
0
文件: agent.py 项目: rlutes/volttron
 def historian_setup(self):
     try:
         _log.debug(
             "Setting up to forward to {}".format(destination_vip))
         event = gevent.event.Event()
         agent = Agent(address=destination_vip, enable_store=False)
         agent.core.onstart.connect(lambda *a, **kw: event.set(), event)
         gevent.spawn(agent.core.run)
         event.wait(timeout=10)
         self._target_platform = agent
     except gevent.Timeout:
         self.vip.health.set_status(STATUS_BAD,
                                    "Timeout in setup of agent")
         status = Status.from_json(self.vip.health.get_status())
         self.vip.health.send_alert(FORWARD_TIMEOUT_KEY, status)
def test_get_credentials(volttron_instance_web):
    instance = volttron_instance_web
    auth_pending = instance.dynamic_agent.vip.rpc.call(
        AUTH, "get_authorization_pending").get()
    len_auth_pending = len(auth_pending)
    with with_os_environ(instance.env):
        pending_agent = Agent(identity="PendingAgent")
        task = gevent.spawn(pending_agent.core.run)
        task.join(timeout=5)
        pending_agent.core.stop()

    auth_pending = instance.dynamic_agent.vip.rpc.call(
        AUTH, "get_authorization_pending").get()
    print(f"Auth pending is: {auth_pending}")

    assert len(auth_pending) == len_auth_pending + 1
示例#19
0
        def remote_setup(self, node):
                if(node == self.zonenum):
                        return

                else:
                        try:
                                Log.info("Connecting to Zone: " + str(node))
                                masterVIP = (self.Config["masternode_z"+str(node)] 
							+ "?serverkey=" + self.Config["serverkey_z"+str(node)] 
							+ "&publickey=" + ks.public + "&secretkey=" + ks.secret)

                                event = gevent.event.Event()
                                masternode = Agent(address=masterVIP, enable_store=False, 
							identity=self.Config["identity"])
                                masternode.core.onstart.connect(lambda *a, **kw: event.set(),event)
                                gevent.spawn(masternode.core.run)
                                event.wait(timeout=5)
                                self.platforms[node-1] = masternode

                        except gevent.Timeout:
                                Log.exception("Platform Connection Timeout")
示例#20
0
    def remote_setup(self, z):
        if (z == self.zonenum):
            return

        else:
            try:
                Log.info("Connecting to Zone: " + str(z))
                VIP = self.Config["modelnode_z"+str(z)] + "?serverkey=" + \
self.Config["serverkey_z"+str(z)] + "&publickey=" + \
ks.public + "&secretkey=" + ks.secret
                event = gevent.event.Event()
                node = Agent(address=VIP,
                             enable_store=False,
                             identity=self.Config["identity"])
                node.core.onstart.connect(lambda *a, **kw: event.set(), event)
                gevent.spawn(node.core.run)
                event.wait(timeout=5)
                self.platforms[z - 1] = node
                self.platform_status[z - 1] = 1

            except gevent.Timeout:
                Log.exception("Platform Connection Timeout")
                self.platform_status[z - 1] = 0  #note that platform is down
示例#21
0
        def starting(self, sender, **kwargs):
            '''
            Subscribes to the platform message bus on the actuator, record,
            datalogger, and device topics to capture data.
            '''
            _log.info('Starting forwarder to {}'.format(destination_vip))
            
            
            agent = Agent(identity=forward_identity, address=destination_vip)
            event = gevent.event.Event()
            
            # agent.core.run set the event flag to true when agent is running
            gevent.spawn(agent.core.run, event)
            
            # Wait until the agent is fully initialized and ready to 
            # send and receive messages.
            event.wait()

            self._target_platform = agent
            
            #subscribe to everything on the local bus.
            self.vip.pubsub.subscribe(peer='pubsub', prefix='', 
                                     callback=self.data_received)
示例#22
0
    def starting(self, sender, **kwargs):
        '''Subscribes to the platform message bus 
        on the heatbeat/listeneragent topic 
        '''
        agent = Agent(identity=self.destination_platform,
                      address=self.destination_vip)
        event = gevent.event.Event()
        _log.info('vip and platform %r and %r', self.destination_platform,
                  self.destination_vip)
        # agent.core.run set the event flag to true when agent is running
        gevent.spawn(agent.core.run, event)
        _log.info('gevent spawned')

        # Wait until the agent is fully initialized and ready to
        # send and receive messages.
        event.wait()
        _log.info('event passed? wtf')

        self._target_platform = agent
        print(self._agent_id)
        _log.info('still going')

        #agent2 = Agent(identity='2', address=self.local_vip)
        _log.info('still going')

        demandfilepath = "/opt/intwine/icg-data/volttron/homeownerAgent1/curve.txt"
        global price_hwA1
        global quantity_hwA
        price_hwA1, quantity_hwA = self.extractData(demandfilepath)
        _log.info("price is %r, quantity is %r", price_hwA1, quantity_hwA)
        #self._local_platform = agent2
        self._target_platform.vip.pubsub.subscribe('pubsub',
                                                   '',
                                                   callback=self.on_heartbeat)
        self.vip.pubsub.subscribe('pubsub', '', callback=self.on_heartbeat2)
        _log.info('whole method passed')
import os
import sys

import gevent

from volttron.platform import get_address
from volttron.platform.agent.known_identities import VOLTTRON_CENTRAL_PLATFORM
from volttron.platform.keystore import KeyStore
from volttron.platform.messaging import topics
from volttron.platform.vip.agent import Agent


keystore = KeyStore()
agent = Agent(address=get_address(), identity="blahagent",
              publickey=keystore.public(), secretkey=keystore.secret(),
              enable_store=False)

event = gevent.event.Event()
config_store_task = gevent.spawn(agent.core.run, event)
event.wait()
del event

if VOLTTRON_CENTRAL_PLATFORM not in agent.vip.peerlist().get():
    agent.core.stop()
    print('no vcp availablel')
    sys.exit()


def receive_platform_data(peer, sender, bus, topic, headers, message):
    #assert 'message' in kwargs
示例#24
0
from volttron.platform.vip.agent.subsystems.web import ResourceType
from volttron.platform.vip.socket import decode_key
from volttron.platform.web import MasterWebService
from volttron.platform.web.admin_endpoints import AdminEndpoints
from volttron.utils import get_random_key
from volttrontesting.utils.platformwrapper import create_volttron_home
from volttrontesting.fixtures.volttron_platform_fixtures import get_test_volttron_home

from volttrontesting.utils.web_utils import get_test_web_env
from volttrontesting.utils.utils import AgentMock, get_hostname_and_random_port
#from volttrontesting.utils.platformwrapper import create_volttron_home
from volttrontesting.fixtures.cert_fixtures import certs_profile_1

# Patch the MasterWebService so the underlying Agent interfaces are mocked
# so we can just test the things that the MasterWebService is responsible for.
MasterWebService.__bases__ = (AgentMock.imitate(Agent, Agent()), )

#TODO add tests for new RPC calls


@pytest.fixture()
def master_web_service():
    serverkey = "serverkey"
    mock_aip = mock.Mock()
    yield MasterWebService(serverkey=serverkey,
                           identity=MASTER_WEB,
                           address="tcp://stuff",
                           bind_web_address="http://v2:8888")


@contextlib.contextmanager
示例#25
0
utils.setup_logging(level=logging.WARNING)
_log = logging.getLogger(__name__)

# These are the options that can be set from the settings module.
from settings import agent_kwargs
''' takes two arguments.  Firist is topic to publish under.  Second is message. '''
if __name__ == '__main__':
    try:
        # If stdout is a pipe, re-open it line buffered
        if utils.isapipe(sys.stdout):
            # Hold a reference to the previous file object so it doesn't
            # get garbage collected and close the underlying descriptor.
            stdout = sys.stdout
            sys.stdout = os.fdopen(stdout.fileno(), 'w', 1)

        agent = Agent(identity='NodeRedPublisher', **agent_kwargs)
        now = utils.format_timestamp(datetime.utcnow())
        headers = {
            headers_mod.CONTENT_TYPE: headers_mod.CONTENT_TYPE.PLAIN_TEXT,
            headers_mod.DATE: now,
            headers_mod.TIMESTAMP: now
        }
        event = gevent.event.Event()
        task = gevent.spawn(agent.core.run, event)
        with gevent.Timeout(10):
            event.wait()

        try:
            result = agent.vip.pubsub.publish('pubsub', sys.argv[1], headers,
                                              sys.argv[2])
            result.get(timeout=10)
示例#26
0
from mock import create_autospec

import pytest
import pytz

from platform_driver import agent
from platform_driver.agent import DriverAgent
from platform_driver.interfaces import BaseInterface
from platform_driver.interfaces.fakedriver import Interface as FakeInterface
from volttrontesting.utils.utils import AgentMock
from volttron.platform.vip.agent import Agent
from volttron.platform.messaging.utils import Topic
from volttron.platform.vip.agent.core import ScheduledEvent

agent._log = logging.getLogger("test_logger")
DriverAgent.__bases__ = (AgentMock.imitate(Agent, Agent()), )


@pytest.mark.driver_unit
def test_update_publish_types_should_only_set_depth_first_to_true():
    publish_depth_first_all = True
    publish_breadth_first_all = True
    publish_depth_first = True
    publish_breadth_first = True

    with get_driver_agent() as driver_agent:
        driver_agent.update_publish_types(publish_depth_first_all,
                                          publish_breadth_first_all,
                                          publish_depth_first,
                                          publish_breadth_first)
pytestmark = [pytest.mark.actuator_unit, pytest.mark.unit]

PEER = "peer-1"
SENDER = "sender-1"
HEADERS = {"requesterID": "id-12345"}
MESSAGE = "message-1"
BUS = "bus-1"
GET_TOPIC = "devices/actuators/get/somepath/actuationpoint"
SET_TOPIC = "devices/actuators/set/somepath/actuationpoint"
REQUEST_TOPIC = "devices/actuators/schedule/request"
REVERT_DEVICE_TOPIC = "devices/actuators/revert/device/somedevicepath"
REVERT_POINT_TOPIC = "actuators/revert/point/somedevicepath/someactuationpoint"

agent._log = logging.getLogger("test_logger")
ActuatorAgent.__bases__ = (AgentMock.imitate(Agent, Agent()),)


def test_handle_get_should_succeed():
    with get_actuator_agent() as actuator_agent:
        actuator_agent.handle_get(PEER, SENDER, BUS, GET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_called_once()
        actuator_agent.vip.pubsub.publish.assert_called_once()


def test_handle_get_should_handle_standard_error(caplog):
    with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_get(PEER, SENDER, BUS, GET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_not_called()
示例#28
0
from volttron.platform.vip.agent import Agent
from volttrontesting.utils.utils import AgentMock
from vcplatform.agent import VolttronCentralPlatform

# Patch the VolttronCentralPlatform so the underlying Agent interfaces are mocked
# so we can just test the things that the PlatformWebService is responsible for.
VolttronCentralPlatform.__bases__ = (AgentMock.imitate(Agent, Agent()), )
示例#29
0
 def setup_remote_actuation(self, vip_destination):
     event = gevent.event.Event()
     agent = Agent(address=vip_destination)
     gevent.spawn(agent.core.run, event)
     event.wait(timeout=15)
     return agent
示例#30
0
文件: send.py 项目: yizenrg/volttron
import gevent

from volttron.platform.vip.agent import Agent
from volttron.platform import get_home
import argparse

VIP_ADDR = 'ipc://@' + os.path.join(get_home(), 'run/vip.socket')
parser = argparse.ArgumentParser()
parser.add_argument("operation",
                    choices=['setstatusgood', 'setstatusbad', 'alert'],
                    help="Set the status of the alert agent")
parser.add_argument("message", help="Set the status of the alert agent")

args = parser.parse_args()

agent = Agent(address=VIP_ADDR)
event = gevent.event.Event()
gevent.spawn(agent.core.run, event)  #.join(0)
event.wait(timeout=2)

if args.operation == 'setstatusgood':
    agent.vip.rpc.call('alerter', 'status_good').get(timeout=2)
if args.operation == 'setstatusbad':
    agent.vip.rpc.call('alerter', 'status_bad', args.message).get(timeout=2)

if args.operation == 'alert':
    # alert
    alertkey = 'key{}'.format(random.randint(1, 1000))
    agent.vip.rpc.call('alerter', 'send_alert1', alertkey,
                       args.message).get(timeout=2)