def historian_setup(self): if self.rmq_to_rmq_comm: _log.debug("Setting up to forward to {}".format( self.destination_instance_name)) self._target_platform = None else: _log.debug("Setting up to forward to {}".format( self.destination_vip)) try: agent = build_agent( address=self.destination_vip, serverkey=self.destination_serverkey, publickey=self.core.publickey, secretkey=self.core.secretkey, enable_store=False, identity=self.remote_identity, instance_name=self.destination_instance_name) except gevent.Timeout: self.vip.health.set_status(STATUS_BAD, "Timeout in setup of agent") try: status = Status.from_json(self.vip.health.get_status()) self.vip.health.send_alert(DATAMOVER_TIMEOUT_KEY, status) except KeyError: _log.error("Error getting the health status") else: self._target_platform = agent
def _build_agent_for_vc(self): """Can raise DiscoveryError and gevent.Timeout""" response = DiscoveryInfo.request_discovery_info( self._vc_discovery_address) agent = build_agent( address=response.vip_address, serverkey=response.serverkey, secretkey=self.core.secretkey, publickey=self.core.publickey) return agent
def _build_agent_for_vc(self): """Can raise DiscoveryError and gevent.Timeout""" response = DiscoveryInfo.request_discovery_info( self._vc_discovery_address) agent = build_agent(address=response.vip_address, serverkey=response.serverkey, secretkey=self.core.secretkey, publickey=self.core.publickey) return agent
def historian_setup(self): _log.debug("Setting up to forward to {}".format(self.destination_vip)) try: agent = build_agent(address=self.destination_vip, serverkey=self.destination_serverkey, publickey=self.core.publickey, secretkey=self.core.secretkey, enable_store=False) 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(DATAMOVER_TIMEOUT_KEY, status) else: self._target_platform = agent
def install_configs(input_directory, keep=False): try: os.chdir(input_directory) except FileNotFoundError: print(f"'input_directory' could not be found: {input_directory}") return ks = KeyStore() agent = build_agent(identity=PLATFORM, publickey=ks.public, secretkey=ks.secret, enable_store=True, timeout=30) if not keep: print("Deleting old Platform 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)
def historian_setup(self): _log.debug("Setting up to forward to {}".format(self.destination_vip)) try: agent = build_agent(address=self.destination_vip, serverkey=self.destination_serverkey, publickey=self.core.publickey, secretkey=self.core.secretkey, enable_store=False) 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(DATAMOVER_TIMEOUT_KEY, status) else: self._target_platform = agent
def main(): parser = argparse.ArgumentParser() parser.add_argument('vip_identity', help='VIP Identity of the agent that owns the config') parser.add_argument('filename', help='Name of the configstore file to edit') parser.add_argument('key', help='Key to add or edit in the config') parser.add_argument('value', help='int, float, or string') args = parser.parse_args() vip_id = args.vip_identity filename = args.filename key = args.key value = args.value try: value = int(value) except ValueError: try: value = float(value) except ValueError: pass agent = build_agent(**get_keys()) files = agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_list_configs', vip_id).get(timeout=10) if filename not in files: config = {key: value} else: config = agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_get', vip_id, filename).get(timeout=10) config = jsonapi.loads(config) config[key] = value agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_store', vip_id, filename, jsonapi.dumps(config), 'json').get(timeout=10)
def main(): parser = argparse.ArgumentParser() parser.add_argument('vip_identity', help='VIP Identity of the agent that owns the config') parser.add_argument('filename', help='Name of the configstore file to edit') parser.add_argument('key', help='Key to add or edit in the config') parser.add_argument('value', help='int, float, or string') args = parser.parse_args() vip_id = args.vip_identity filename = args.filename key = args.key value = args.value try: value = int(value) except ValueError: try: value = float(value) except ValueError: pass agent = build_agent(**get_keys()) files = agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_list_configs', vip_id).get(timeout=10) if filename not in files: config = {key: value} else: config = agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_get', vip_id, filename).get(timeout=10) config = json.loads(config) config[key] = value agent.vip.rpc.call(CONFIGURATION_STORE, 'manage_store', vip_id, filename, json.dumps(config), 'json').get(timeout=10)
def manage(self, address, vcserverkey, vcpublickey): """ Allows the `VolttronCentralPlatform` to be managed. From the web perspective this should be after the user has specified that a user has blessed an agent to be able to be managed. When the user enters a discovery address in `VolttronCentral` it is implied that the user wants to manage a platform. :returns publickey of the `VolttronCentralPlatform` """ _log.info('Manage request from address: {} serverkey: {}'.format( address, vcserverkey)) if self._managed: raise AlreadyManagedError() parsedaddress = urlparse.urlparse(address) if 'ipc://' == address[:6].lower(): self._agent_connected_to_vc = self else: # Attempt to connect to the passed address and serverkey. self._agent_connected_to_vc = build_agent( address=address, serverkey=vcserverkey, publickey=self.core.publickey, secretkey=self.core.secretkey) version, peer, identity = self._agent_connected_to_vc.vip.hello().get( timeout=30) if not self == self._agent_connected_to_vc: # Add the vcpublickey to the auth file. entry = AuthEntry( credentials="CURVE:{}".format(vcpublickey), capabilities=['manager']) # , address=parsedaddress.hostname) authfile = AuthFile() authfile.add(entry) self._managed = True self.core.spawn_later(2, self._publish_agent_list_to_vc) self.core.spawn_later(2, self._publish_stats) return self.core.publickey
def manage(self, address, vcserverkey, vcpublickey): """ Allows the `VolttronCentralPlatform` to be managed. From the web perspective this should be after the user has specified that a user has blessed an agent to be able to be managed. When the user enters a discovery address in `VolttronCentral` it is implied that the user wants to manage a platform. :returns publickey of the `VolttronCentralPlatform` """ _log.info('Manage request from address: {} serverkey: {}'.format( address, vcserverkey)) if self._managed: raise AlreadyManagedError() parsedaddress = urlparse.urlparse(address) if 'ipc://' == address[:6].lower(): self._agent_connected_to_vc = self else: # Attempt to connect to the passed address and serverkey. self._agent_connected_to_vc = build_agent( address=address, serverkey=vcserverkey, publickey=self.core.publickey, secretkey=self.core.secretkey) version, peer, identity = self._agent_connected_to_vc.vip.hello().get( timeout=30) if not self == self._agent_connected_to_vc: # Add the vcpublickey to the auth file. entry = AuthEntry( credentials="CURVE:{}".format(vcpublickey), capabilities=['manager']) # , address=parsedaddress.hostname) authfile = AuthFile() authfile.add(entry) self._managed = True self.core.spawn_later(2, self._publish_agent_list_to_vc) self.core.spawn_later(2, self._publish_stats) return self.core.publickey
def _establish_connection_to_vc(self): if not self.current_config.get("vc_connect_address"): raise ValueError("vc_connect_address was not resolved properly.") if not self.current_config.get("vc_connect_serverkey"): raise ValueError("vc_connect_serverkey was not resolved properly.") if self._establish_connection_event is not None: self._establish_connection_event.cancel() if self.vc_connection is None: _log.info("Attempting to reconnect with volttron central.") instance_id = self.current_config['instance_id'] # Note using the connect_address and connect_serverkey because they # are now resolved to the correct values based upon the different # ways of configuring the agent. vc_address = self.current_config['vc_connect_address'] vc_serverkey = self.current_config['vc_connect_serverkey'] try: self.volttron_central_connection = build_agent( identity=instance_id, address=vc_address, serverkey=vc_serverkey, publickey=self.core.publickey, secretkey=self.core.secretkey, agent_class=VCConnection) except gevent.Timeout: _log.debug("No connection to volttron central instance.") self.volttron_central_connection = None next_update_time = self._next_update_time() self._establish_connection_event = self.core.schedule( next_update_time, self._establish_connection_to_vc) else: self.volttron_central_connection.set_main_agent(self) self._still_connected()
def historian_setup(self): _log.debug("Setting up to forward to {}".format(self.destination_vip)) try: agent = build_agent(address=self.destination_vip, serverkey=self.destination_serverkey, publickey=self.core.publickey, secretkey=self.core.secretkey, enable_store=False) except gevent.Timeout: _log.error("Couldn't connect to destination-vip ({})".format( self.destination_vip)) self.vip.health.set_status(STATUS_BAD, "Timeout in setup of agent") except Exception as ex: _log.error(ex.args) else: self._target_platform = agent self.vip.health.set_status( STATUS_GOOD, "Connected to destination-vip ({})".format( self.destination_vip))
def remote_agent(self): if self._remote_agent is None: if not self._creating_agent: self._creating_agent = True try: self._remote_agent = build_agent( address=self.remote_address, identity=self.remote_identity, secretkey=self.core.secretkey, publickey=self.core.publickey, serverkey=self.remote_serverkey) self._remote_agent.vip.ping("").get(timeout=2) self.vip.health.set_status(STATUS_GOOD) except gevent.Timeout, ZMQError: status_context = "Couldn't connect to remote platform at: {}".format( self.remote_address) _log.error(status_context) self._remote_agent = None self.vip.health.set_status(STATUS_BAD, status_context) finally: self._creating_agent = False
def historian_setup(self): _log.debug("Setting up to forward to {}".format(self.destination_vip)) try: agent = build_agent(address=self.destination_vip, serverkey=self.destination_serverkey, publickey=self.core.publickey, secretkey=self.core.secretkey, enable_store=False) except gevent.Timeout: _log.error("Couldn't connect to destination-vip ({})".format( self.destination_vip )) self.vip.health.set_status( STATUS_BAD, "Timeout in setup of agent") except Exception as ex: _log.error(ex.args) else: self._target_platform = agent self.vip.health.set_status( STATUS_GOOD, "Connected to destination-vip ({})".format( self.destination_vip))
def remote_agent(self): if self._remote_agent is None: if not self._creating_agent: self._creating_agent = True try: self._remote_agent = build_agent( address=self.remote_address, identity=self.remote_identity, secretkey=self.core.secretkey, publickey=self.core.publickey, serverkey=self.remote_serverkey ) self._remote_agent.vip.ping("").get(timeout=2) self.vip.health.set_status(STATUS_GOOD) except gevent.Timeout, ZMQError: status_context = "Couldn't connect to remote platform at: {}".format( self.remote_address) _log.error(status_context) self._remote_agent = None self.vip.health.set_status(STATUS_BAD, status_context) finally: self._creating_agent = False
def start_bacnet_scan(self, iam_topic, proxy_identity, low_device_id=None, high_device_id=None, target_address=None, scan_length=5, instance_address=None, instance_serverkey=None): """This function is a wrapper around the bacnet proxy scan. """ agent_to_use = self if instance_address is not None: agent_to_use = build_agent(address=instance_address, identity="proxy_bacnetplatform", publickey=self.core.publickey, secretkey=self.core.secretkey, serverkey=instance_serverkey) if proxy_identity not in agent_to_use.vip.peerlist().get(timeout=5): raise Unreachable( "Can't reach agent identity {}".format(proxy_identity)) _log.info('Starting bacnet_scan with who_is request to {}'.format( proxy_identity)) def handle_iam(peer, sender, bus, topic, headers, message): proxy_identity = sender address = message['address'] device_id = message['device_id'] bn = BACnetReader(agent_to_use.vip.rpc, proxy_identity) message['device_name'] = bn.read_device_name(address, device_id) message['device_description'] = bn.read_device_description( address, device_id) self._pub_to_vc(iam_topic, message=message) def stop_iam(): _log.debug('Done publishing i am responses.') stop_timestamp = get_utc_seconds_from_epoch() self._pub_to_vc(iam_topic, message=dict(status="FINISHED IAM", timestamp=stop_timestamp)) agent_to_use.vip.pubsub.unsubscribe('pubsub', topics.BACNET_I_AM, handle_iam) agent_to_use.vip.pubsub.subscribe('pubsub', topics.BACNET_I_AM, handle_iam) timestamp = get_utc_seconds_from_epoch() self._pub_to_vc(iam_topic, message=dict(status="STARTED IAM", timestamp=timestamp)) agent_to_use.vip.rpc.call( proxy_identity, "who_is", low_device_id=low_device_id, high_device_id=high_device_id, target_address=target_address).get(timeout=5.0) gevent.spawn_later(float(scan_length), stop_iam)
def get_vc_connection(self): """ Attempt to connect to volttron central management console. The attempts will be done in the following order. 1. if peer is vc register with it. 2. volttron-central-tcp and serverkey 2. volttron-central-http (looks up tcp and serverkey) 3. volttron-central-ipc :param sender: :param kwargs: :return: """ if self.vc_connection: # if connected return the connection. if self.vc_connection.is_connected(5) and \ self.vc_connection.is_peer_connected(5): _log.debug('Returning current connection') return self.vc_connection _log.debug("Resetting connection as the peer wasn't responding.") # reset the connection so we can try it again below. self.vc_connection.kill() self.vc_connection = None def sync_status_to_vc(status, context): """ Sync the status of the current vcp object with that of the one that is connected to the vc instance. :param status: :param context: """ conn = self.vc_connection conn.vip.health.set_status(status, context) self.vip.health.add_status_callback(sync_status_to_vc) def enable_connection_heartbeat(): """ Start publishing the heartbeat with the status messages. """ conn = self.vc_connection status = self.vip.health.get_status() conn.vip.health.set_status(status['status'], status['context']) conn.vip.heartbeat.start() # We are going to use an identity of platform.address_hash for # connections to vc. This should allow us unique connection as well # as allowing the vc to filter on the heartbeat status of the pubsub # message to determine context. vcp_identity_on_vc = 'platform.' # First check to see if there is a peer with a volttron.central # identity, if there is use it as the manager of the platform. peers = self.vip.peerlist().get(timeout=5) if VOLTTRON_CENTRAL in peers: _log.debug('VC is a local peer.') # Address hash that uniquely defines this platform in the network. address_hash = hashlib.md5(self.core.address).hexdigest() self.current_config['address_hash'] = address_hash vcp_identity_on_vc += address_hash vc_serverkey = self.current_config['volttron_connect_serverkey'] self.vc_connection = build_agent( self.core.address, #peer=VOLTTRON_CENTRAL, publickey=self.core.publickey, secretkey=self.core.secretkey, serverkey=vc_serverkey, identity=vcp_identity_on_vc, agent_class=VCConnection) self.vc_connection.set_main_agent(self) if self.vc_connection.is_connected() and \ self.vc_connection.is_peer_connected(): _log.debug("Connection has been established to local peer.") else: _log.error('Unable to connect to local peer!') if self.vc_connection.is_connected(): enable_connection_heartbeat() return self.vc_connection if self.current_config.get('vc_connect_address') is None or \ self.current_config.get('vc_connect_serverkey') is None: _log.warn('volttron_central_address is None in config store ' 'and volttron.central is not a peer.') _log.warn('Recommend adding volttron.central address or adding a ' '"config" file to the config store.') return None c = self.current_config address_hash = c.get('address_hash') vcp_identity_on_vc += address_hash self.vc_connection = build_agent( identity=vcp_identity_on_vc, # peer=VOLTTRON_CENTRAL, address=c.get('vc_connect_address'), serverkey=c.get('vc_connect_serverkey'), publickey=self.core.publickey, secretkey=self.core.secretkey, agent_class=VCConnection) self.vc_connection.set_main_agent(self) if not self.vc_connection.is_peer_connected(): _log.error( 'Peer: {} is not connected to the external platform'.format( self.vc_connection.peer)) self.vc_connection.kill() self.vc_connection = None self.registration_state = RegistrationStates.NotRegistered return None if self.vc_connection.is_connected(): enable_connection_heartbeat() return self.vc_connection
import gevent from volttron.platform.keystore import KeyStore from volttron.platform.messaging.health import STATUS_BAD, Status from volttron.platform.vip.agent.utils import build_agent test_subject = "Test subject1" test_message = "this is a message that is sent via pubsub email" message = dict(subject=test_subject, message=test_message) ks = KeyStore() agent = build_agent(identity="test.email.pubsub", enable_store=False) agent.vip.pubsub.publish('pubsub', topic="platform/send_email", message=message) # agent.vip.health.set_status(STATUS_BAD, "It's bad man really bad!") agent.vip.health.send_alert("ALERT_KEY", Status.build(STATUS_BAD, "It's really bad again!")) gevent.sleep(5) agent.core.stop()
agent: Optional[Agent] = None while True: new_volttron_home = get_volttron_home() if new_volttron_home is not None and new_volttron_home != volttron_home: if agent: agent.core.stop() agent = None volttron_home = new_volttron_home os.environ['VOLTTRON_HOME'] = volttron_home public, secret = get_public_private_key(volttron_home) last_output = f"Attempting connection {volttron_home}" print(last_output) agent = build_agent(volttron_home=volttron_home, identity="peer.finder", publickey=public, secretkey=secret, serverkey=public) if agent: try: with gevent.Timeout(5): next_last_output = f"Peerlist: {agent.vip.peerlist().get()}" if next_last_output != last_output: last_output = next_last_output print(last_output) except gevent.Timeout: agent.core.stop() agent = None else: next_last_output = "waiting on file."
def run_tests(local_root="~/local_files", remote_root="~/remote_files"): agent = build_agent(identity='trigger') local_root = Path(local_root).expanduser() remote_root = Path(remote_root).expanduser() def build_remote_filename(filename): os.makedirs(remote_root, exist_ok=True) return str(Path(remote_root).joinpath(filename)) def build_local_filename(filename): os.makedirs(local_root, exist_ok=True) return str(Path(local_root).joinpath(filename)) def create_remote_file(filename, content): full_path = build_remote_filename(filename) with open(full_path, 'w') as fp: fp.write(content) return full_path def create_local_file(filename, content): full_path = build_local_filename(filename) with open(full_path, 'w') as fp: fp.write(content) return full_path def remove_files(): shutil.rmtree(remote_root, ignore_errors=True) shutil.rmtree(local_root, ignore_errors=True) remove_files() remote_path = create_remote_file("t1.txt", "this is f1") local_path = build_local_filename("t1.after.transfer.txt") go = input( f"Test 1: rpc: trigger_download\n\tdownload remote_path: {remote_path}\n\tto local_path: {local_path} " ) result = agent.vip.rpc.call("scp.agent", "trigger_download", remote_path=remote_path, local_path=local_path).get() print(f"The result was {result}\n") print(f"Creating test2 file") remote_path = build_remote_filename("t2.remote.transfer.txt") local_path = create_local_file("t2.txt", "This is test 2") go = input( f"Test 2: rpc: trigger_upload\n\tupload local_path: {local_path}\n\tto remote_path: {remote_path} " ) result = agent.vip.rpc.call("scp.agent", "trigger_upload", remote_path=remote_path, local_path=local_path).get() print(f"The result was {result}\n") print(f"Creating test3 file") remote_path = build_remote_filename("t3.sent.pubsub.txt") local_path = create_local_file("t3.txt", "This is test 3") go = input( f"Test 3: pubsub: SENDING\n\tlocal_path: {local_path}\n\tto remote_path: {remote_path} " ) agent.vip.pubsub.publish(peer='pubsub', topic="transfer", message=dict(remote_path=remote_path, local_path=local_path, direction="SENDING")).get() gevent.sleep(1) print(f"The result is {Path(remote_path).exists()}\n") print(f"Creating test4 file") remote_path = create_remote_file("t4.receive.pubsub.txt", "This is test 4") local_path = build_local_filename("t4.receive.txt") go = input( f"Test 4: pubsub: RECEIVING\n\tlocal_path: {local_path}\n\tfrom remote_path: {remote_path} " ) agent.vip.pubsub.publish(peer='pubsub', topic="transfer", message=dict(remote_path=remote_path, local_path=local_path, direction="RECEIVING")).get() gevent.sleep(1) print(f"The result is {Path(local_path).exists()}\n") agent.core.stop() print("Complete")
def connect(self): _log.info('Connecting {}'.format(self._address)) self._connected_agent = build_agent(address=self._address, serverkey=self._serverkey, secretkey=self._secretkey, publickey=self._publickey)
def main(): global agent global config_writer # parse the command line arguments arg_parser = argparse.ArgumentParser(description=__doc__) arg_parser.add_argument("device_id", type=int, help="Device ID of the target device") arg_parser.add_argument( "--address", help= "Address of target device, may be needed to help route initial request to device." ) arg_parser.add_argument("--registry-out-file", type=argparse.FileType('w'), help="Output registry to CSV file", default=sys.stdout) arg_parser.add_argument("--driver-out-file", type=argparse.FileType('w'), help="Output driver configuration to JSON file.", default=sys.stdout) arg_parser.add_argument( "--max-range-report", nargs='?', type=float, help= 'Affects how very large numbers are reported in the "Unit Details" column of the ' 'output. Does not affect driver behavior.', default=1.0e+20) arg_parser.add_argument("--proxy-id", help="VIP IDENTITY of the BACnet proxy agent.", default="platform.bacnet_proxy") args = arg_parser.parse_args() _log.debug("initialization") _log.debug(" - args: %r", args) key_store = KeyStore() config_writer = DictWriter( args.registry_out_file, ('Reference Point Name', 'Volttron Point Name', 'Units', 'Unit Details', 'BACnet Object Type', 'Property', 'Writable', 'Index', 'Write Priority', 'Notes')) config_writer.writeheader() agent = build_agent(address=get_address(), volttron_home=get_home(), publickey=key_store.public, secretkey=key_store.secret, enable_store=False) bn = BACnetReader(agent.vip, args.proxy_id, bacnet_response) async_result = AsyncResult() try: bn.get_iam(args.device_id, async_result.set, args.address) except errors.Unreachable as ure: _log.error(ure) _log.error( "No BACnet proxy Agent running on the platform with the VIP IDENTITY {}" .format(args.proxy_id)) sys.exit(1) try: results = async_result.get(timeout=5.0) except gevent.Timeout: _log.error("No response from device id {}".format(args.device_id)) sys.exit(1) if args.address and args.address != results["address"]: msg = "Inconsistent results from passed address ({}) and device address ({}) using results.".format( args.address, results["address"]) _log.warning(msg) args.address = results["address"] elif results["address"]: args.address = results["address"] bn.read_device_properties(target_address=args.address, device_id=args.device_id) agent.core.stop()
def connect_remote_platform( self, address, serverkey=None, agent_class=None ): """ Agent attempts to connect to a remote platform to exchange data. address must start with http, https, tcp, ampq, or ampqs or a ValueError will be raised If this function is successful it will return an instance of the `agent_class` parameter if not then this function will return None. If the address parameter begins with http or https TODO: use the known host functionality here the agent will attempt to use Discovery to find the values associated with it. Discovery should return either an rmq-address or a vip-address or both. In that situation the connection will be made using zmq. In the event that fails then rmq will be tried. If both fail then None is returned from this function. """ from volttron.platform.vip.agent.utils import build_agent from volttron.platform.vip.agent import Agent if agent_class is None: agent_class = Agent parsed_address = urlparse(address) _log.debug("Begining auth.connect_remote_platform: {}".format(address)) value = None if parsed_address.scheme == "tcp": # ZMQ connection hosts = KnownHostsStore() temp_serverkey = hosts.serverkey(address) if not temp_serverkey: _log.info( "Destination serverkey not found in known hosts file, " "using config" ) destination_serverkey = serverkey elif not serverkey: destination_serverkey = temp_serverkey else: if temp_serverkey != serverkey: raise ValueError( "server_key passed and known hosts serverkey do not " "" "match!" ) destination_serverkey = serverkey publickey, secretkey = ( self._core().publickey, self._core().secretkey, ) _log.debug( "Connecting using: %s", get_fq_identity(self._core().identity) ) value = build_agent( agent_class=agent_class, identity=get_fq_identity(self._core().identity), serverkey=destination_serverkey, publickey=publickey, secretkey=secretkey, message_bus="zmq", address=address, ) elif parsed_address.scheme in ("https", "http"): from volttron.platform.web import DiscoveryInfo from volttron.platform.web import DiscoveryError try: # TODO: Use known host instead of looking up for discovery # info if possible. # We need to discover which type of bus is at the other end. info = DiscoveryInfo.request_discovery_info(address) remote_identity = "{}.{}.{}".format( info.instance_name, get_platform_instance_name(), self._core().identity, ) # if the current message bus is zmq then we need # to connect a zmq on the remote, whether that be the # rmq router or proxy. Also note that we are using the # fully qualified # version of the identity because there will be conflicts if # volttron central has more than one platform.agent connecting if get_messagebus() == "zmq": if not info.vip_address or not info.serverkey: err = ( "Discovery from {} did not return serverkey " "and/or vip_address".format(address) ) raise ValueError(err) _log.debug( "Connecting using: %s", get_fq_identity(self._core().identity), ) # use fully qualified identity value = build_agent( identity=get_fq_identity(self._core().identity), address=info.vip_address, serverkey=info.serverkey, secretkey=self._core().secretkey, publickey=self._core().publickey, agent_class=agent_class, ) else: # we are on rmq messagebus # This is if both remote and local are rmq message buses. if info.messagebus_type == "rmq": _log.debug("Both remote and local are rmq messagebus.") fqid_local = get_fq_identity(self._core().identity) # Check if we already have the cert, if so use it # instead of requesting cert again remote_certs_dir = self.get_remote_certs_dir() remote_cert_name = "{}.{}".format( info.instance_name, fqid_local ) certfile = os.path.join( remote_certs_dir, remote_cert_name + ".crt" ) if os.path.exists(certfile): response = certfile else: response = self.request_cert( address, fqid_local, info ) if response is None: _log.error("there was no response from the server") value = None elif isinstance(response, tuple): if response[0] == "PENDING": _log.info( "Waiting for administrator to accept a " "CSR request." ) value = None # elif isinstance(response, dict): # response elif os.path.exists(response): # info = DiscoveryInfo.request_discovery_info( # address) # From the remote platforms perspective the # remote user name is # remoteinstance.localinstance.identity, # this is what we must # pass to the build_remote_connection_params # for a successful remote_rmq_user = get_fq_identity( fqid_local, info.instance_name ) _log.debug( "REMOTE RMQ USER IS: %s", remote_rmq_user ) remote_rmq_address = self._core().rmq_mgmt.build_remote_connection_param( remote_rmq_user, info.rmq_address, ssl_auth=True, cert_dir=self.get_remote_certs_dir(), ) value = build_agent( identity=fqid_local, address=remote_rmq_address, instance_name=info.instance_name, publickey=self._core().publickey, secretkey=self._core().secretkey, message_bus="rmq", enable_store=False, agent_class=agent_class, ) else: raise ValueError( "Unknown path through discovery process!" ) else: # TODO: cache the connection so we don't always have # to ping the server to connect. # This branch happens when the message bus is not # the same note # this writes to the agent-data directory of this # agent if the agent # is installed. if get_messagebus() == "rmq": if not os.path.exists("keystore.json"): with open("keystore.json", "w") as file_pointer: file_pointer.write( jsonapi.dumps( KeyStore.generate_keypair_dict() ) ) with open("keystore.json") as file_pointer: keypair = jsonapi.loads(file_pointer.read()) value = build_agent( agent_class=agent_class, identity=remote_identity, serverkey=info.serverkey, publickey=keypair.get("publickey"), secretkey=keypair.get("secretekey"), message_bus="zmq", address=info.vip_address, ) except DiscoveryError: _log.error( "Couldn't connect to %s or incorrect response returned " "response was %s", address, value, ) else: raise ValueError( "Invalid configuration found the address: {} has an invalid " "scheme".format(address) ) return value
def connect(self): _log.info('Connecting {}'.format(self._address)) self._connected_agent = build_agent( address=self._address, serverkey=self._serverkey, secretkey=self._secretkey, publickey=self._publickey )
def main(): global agent global config_writer # parse the command line arguments arg_parser = argparse.ArgumentParser(description=__doc__) arg_parser.add_argument("device_id", type=int, help="Device ID of the target device" ) arg_parser.add_argument("--address", help="Address of target device, may be needed to help route initial request to device." ) arg_parser.add_argument("--registry-out-file", type=argparse.FileType('wb'), help="Output registry to CSV file", default=sys.stdout ) arg_parser.add_argument("--driver-out-file", type=argparse.FileType('wb'), help="Output driver configuration to JSON file.", default=sys.stdout) arg_parser.add_argument("--max-range-report", nargs='?', type=float, help='Affects how very large numbers are reported in the "Unit Details" column of the output. ' 'Does not affect driver behavior.', default=1.0e+20 ) arg_parser.add_argument("--proxy-id", help="VIP IDENTITY of the BACnet proxy agent.", default="platform.bacnet_proxy") args = arg_parser.parse_args() _log.debug("initialization") _log.debug(" - args: %r", args) key_store = KeyStore() config_writer = DictWriter(args.registry_out_file, ('Reference Point Name', 'Volttron Point Name', 'Units', 'Unit Details', 'BACnet Object Type', 'Property', 'Writable', 'Index', 'Write Priority', 'Notes')) config_writer.writeheader() agent = build_agent(address=get_address(), volttron_home=get_home(), publickey=key_store.public, secretkey=key_store.secret, enable_store=False) bn = BACnetReader(agent.vip, args.proxy_id, bacnet_response) async_result = AsyncResult() try: bn.get_iam(args.device_id, async_result.set, args.address) except errors.Unreachable: msg = "No BACnet proxy Agent running on the platform with the " \ "VIP IDENTITY {}".format(args.proxy_id) sys.exit(1) try: results = async_result.get(timeout=5.0) except gevent.Timeout: _log.error("No response from device id {}".format(args.device_id)) sys.exit(1) if args.address and args.address != results["address"]: msg = "Inconsistent results from passed address " \ "({}) and device address ({}) using results.".format( args.address, results["address"]) _log.warning(msg) args.address = results["address"] elif results["address"]: args.address = results["address"] bn.read_device_properties(target_address=args.address, device_id=args.device_id) agent.core.stop()
import gevent from volttron.platform.keystore import KeyStore from volttron.platform.messaging.health import STATUS_BAD, Status from volttron.platform.vip.agent.utils import build_agent test_subject = "Test subject1" test_message = "this is a message that is sent via pubsub email" message = dict(subject=test_subject, message=test_message) ks = KeyStore() agent = build_agent(identity="test.email.pubsub", enable_store=False) agent.vip.pubsub.publish('pubsub', topic="platform/send_email", message=message) # agent.vip.health.set_status(STATUS_BAD, "It's bad man really bad!") agent.vip.health.send_alert("ALERT_KEY", Status.build( STATUS_BAD, "It's really bad again!" )) gevent.sleep(5) agent.core.stop()