def start(log_file, feeder_mrid, model_api_topic): global logfile logfile = log_file global G, measid_lbs, loadbreaksw, undirected_graph print("\nTOPOLOGY_VALIDATOR starting!!!------------------------------------------------------------") print("\nTOPOLOGY_VALIDATOR starting!!!------------------------------------------------------------", file=logfile) gapps = GridAPPSD() # NOTE: Use of modelType as STATIC or OPERATIONAL will change the response message = {"modelId": feeder_mrid, "requestType": "LOOPS", "modelType": "OPERATIONAL", "resultFormat": "JSON"} out_topic = "/topic/goss.gridappsd.model-validator.topology.out" gapps.subscribe(out_topic, on_message) in_topic = "/topic/goss.gridappsd.model-validator.topology.in" gapps.send(in_topic, message) print("TOPOLOGY_VALIDATOR sent request to microservice; waiting for response\n", flush=True) print("TOPOLOGY_VALIDATOR sent request to microservice; waiting for response\n", file=logfile) global exit_flag exit_flag = False while not exit_flag: time.sleep(0.1)
def handle_request(headers, message): global openSW if lock_flag: print("MICROSERVICES waiting for lock to be opened", flush=True) print("MICROSERVICES waiting for lock to be opened", file=logfile, flush=True) while lock_flag: time.sleep(0.1) print("MICROSERVICES I got the request", flush=True) print("MICROSERVICES I got the request", file=logfile, flush=True) gapps = GridAPPSD() if message['requestType'] == 'LOOPS': out_topic = "/topic/goss.gridappsd.model-validator.topology.out" if message['modelType'] == 'STATIC': openSW = [] response = find_all_cycles() else: response = find_all_cycles() elif message['requestType'] == 'GRAPH': out_topic = "/topic/goss.gridappsd.model-validator.graph.out" response = graph() elif message['requestType'] == 'ISOLATED_SECTIONS': out_topic = "/topic/goss.gridappsd.model-validator.topology.out" response = {'Is the graph connected': connected()} else: response = 'Invalid request type' print("MICROSERVICES I am sending the response", flush=True) print("MICROSERVICES I am sending the response", file=logfile, flush=True) gapps.send(out_topic, response)
def _main(): parser = argparse.ArgumentParser() parser.add_argument( "simulation_id", help="Simulation id to use for responses on the message bus.") opts = parser.parse_args() gapps = GridAPPSD(opts.simulation_id, address=utils.get_gridappsd_address(), username=utils.get_gridappsd_user(), password=utils.get_gridappsd_pass()) x = input("Press Enter to continue...") message = {'command': 'StartSimulation'} print(fncs_input_topic(opts.simulation_id)) print(json.dumps(message)) gapps.send(fncs_input_topic(opts.simulation_id), json.dumps(message)) while True: sleep(0.1)
def start(log_file, feeder_mrid, model_api_topic): global logfp logfp = log_file global xfm_df, load_df, der_df print("\nTRANSFORMER_CAPACITY starting!!!------------------------------------------------") print("\nTRANSFORMER_CAPACITY starting!!!------------------------------------------------", file=logfp) SPARQLManager = getattr(importlib.import_module('shared.sparql'), 'SPARQLManager') gapps = GridAPPSD() sparql_mgr = SPARQLManager(gapps, feeder_mrid, model_api_topic) # Get transformer data xfm_df = sparql_mgr.query_transformers() print('TRANSFORMER_CAPACITY transformer data obtained', flush=True) print('TRANSFORMER_CAPACITY transformer data obtained', file=logfp) load_df = sparql_mgr.query_energyconsumer() der_df = sparql_mgr.query_der() print('TRANSFORMER_CAPACITY load and DER data obtained', flush=True) print('TRANSFORMER_CAPACITY load and DER data obtained', file=logfp) # Subscribe to microservice for getting the graph information message = {"modelId": feeder_mrid, "requestType": "GRAPH", "modelType": "STATIC", "resultFormat": "JSON"} out_topic = "/topic/goss.gridappsd.model-validator.graph.out" gapps.subscribe(out_topic, callback) in_topic = "/topic/goss.gridappsd.model-validator.graph.in" gapps.send(in_topic, message) print("TRANSFORMER_CAPACITY sent request to microservice; waiting for response\n", flush=True) print("TRANSFORMER_CAPACITY sent request to microservice; waiting for response\n", file=logfp) global exit_flag exit_flag = False while not exit_flag: time.sleep(0.1)
class GridAPPSDVolttron(Agent): """ Document agent constructor here. """ def __init__(self, setting1=1, setting2="some/random/topic", **kwargs): super(GridAPPSDVolttron, self).__init__(**kwargs) self._gapps = GridAPPSD(override_threading=gevent.spawn) self._publish_event = None def publish_next(self): if self._publish_event is not None: self._publish_event.cancel() if self._gapps.connected: self._gapps.send("/queue/test", "foo bar") else: print("Not connected") now = get_aware_utc_now() print(utils.get_utc_seconds_from_epoch(now)) next_update_time = now + datetime.timedelta(seconds=5) self._publish_event = self.core.schedule(next_update_time, self.publish_next) gevent.sleep(0.1) @Core.receiver("onstart") def onstart(self, sender, **kwargs): def message_published(headers, body): self.vip.pubsub.publish('pubsub', "data/foo", headers=headers, message=body) self._gapps.subscribe('/queue/test', message_published) gevent.sleep(0.1) self.publish_next() @Core.receiver("onstop") def onstop(self, sender, **kwargs): print("Stopping data!") # self._gapps.disconnect() print("After disconnect")
def _main(): global sim_id, gapps if len(sys.argv) < 3 or '-help' in sys.argv: usestr = '\nUsage: ' + sys.argv[ 0] + ' simulation_id tap|reg|cap|switch\n' usestr += ''' Optional command line arguments: -help: show this usage message ''' print(usestr, file=sys.stderr, flush=True) exit() gapps = GridAPPSD() sim_id = sys.argv[1] diff = DifferenceBuilder(sim_id) # hardwired for 13assets if sys.argv[2] == 'tap' or sys.argv[2] == 'reg': reg_id = '_A480E0A9-AD2B-4D8E-9478-71C29F738221' # node RG60.2 diff.add_difference(reg_id, 'TapChanger.step', 5, 8) elif sys.argv[2] == 'cap': cap_id = '_28456F60-7196-47E4-9BE6-54F7EAABC04A' # bus 611 diff.add_difference(cap_id, 'ShuntCompensator.sections', 0, 1) else: switch_id = '_4E1B3F09-CB88-4A5E-8198-24490EE7FC58' # between bus 671-692 diff.add_difference(switch_id, 'Switch.open', 1, 0) msg = diff.get_message() print(json.dumps(msg)) publish_to_topic = simulation_input_topic(sim_id) gapps.send(publish_to_topic, json.dumps(msg)) time.sleep(2) gapps.disconnect()
get_input = raw_input except NameError: get_input = input print("Creating GridAPPSD object") gapps = GridAPPSD(stomp_address="127.0.0.1", stomp_port=61613, username='******', password='******') print("Subscribing to /topic/foo") gapps.subscribe('/topic/foo', on_message) result = get_input( "Press enter to send json.dumps(dict(bim='bash')) to topic /topic/foo") print("Sending data") gapps.send('/topic/foo', json.dumps(dict(bim='bash'))) sleep(1) get_input("Press enter to receive platform status") resp = gapps.get_platform_status() pprint(resp) get_input("Press enter to query model info") resp = gapps.query_model_info() pprint(resp) get_input("Press enter to query model names") resp = gapps.query_model_names() pprint(resp) get_input("Press enter to query object types")
class GridAPPSDSimIntegration(BaseSimIntegration): """ The class is responsible for integration with GridAPPSD co-simulation platform. It provides integration support to register configuration, start, stop, publish, receive messages, pause and resume simulation """ def __init__(self, config, pubsub): super(GridAPPSDSimIntegration, self).__init__(config) self._work_callback = None self.config = config self.gridappsd = None self.sim = None self.event_callbacks = {} self.topic_callbacks = {} self.sim_id = None self.username = None self.password = None def register_inputs(self, config=None, callback=None, **kwargs): """ Register configuration parameters with GridAppsD. The config parameters may include but not limited to: - power_system_config - application_config - simulation_config - test_config - service_configs : Register agent callback method :return: """ self.config = config self.username = self.config.pop('username', 'system') self.password = self.config.pop('password', 'manager') self._work_callback = callback def register_event_callbacks(self, callbacks={}): """ Register for event callbacks for event notifications such as - on measurement change - on timestep change - on finish """ _log.debug("Registering for event callbacks") self.event_callbacks = callbacks def register_topic_callbacks(self, callbacks={}): """ Register for any simulation topic callbacks """ _log.debug("Registering for topic callbacks") self.topic_callbacks = callbacks def start_simulation(self, *args, **kwargs): """ Simulation start activities involve: - Creating GridAppsD connection gevent thread - Registering for event callbacks (if specified) - Registering for topic callbacks if specified - Starting simulation based on the input config :return: """ try: self.gridappsd = GridAPPSD(override_threading=self.receiver_thread, username=self.username, password=self.password) _log.debug('Gridappsd connected') _log.debug(f"connection config is: {self.config}") self.sim = Simulation(self.gridappsd, self.config) _log.debug('Gridappsd adding onstart callback') # Register for onstart callback to know if simulation has started self.sim.add_onstart_callback(self.sim_on_start) # Register event callbacks - on measurement, on timestep, on finish for name, cb in self.event_callbacks.items(): if name == 'MEASUREMENT': _log.debug('Gridappsd adding measurement callback') self.sim.add_onmesurement_callback(cb) elif name == 'TIMESTEP': _log.debug('Gridappsd adding timestep callback') self.sim.add_ontimestep_callback(cb) elif name == 'FINISH': _log.debug('Gridappsd adding finish callback') self.sim.add_oncomplete_callback(cb) # Register/Subscribe for simulation topics for topic, cb in self.topic_callbacks: _log.debug('Gridappsd subscribing to topics callback') self.gridappsd.subscribe(topic, cb) # Starting GridAppsD simulation self.sim.start_simulation() _log.debug(f"Gridappsd simulation id: {self.sim.simulation_id}") except stomp.exception.NotConnectedException as ex: _log.error("Unable to connect to GridAPPSD: {}".format(ex)) raise ex def sim_on_start(self, sim): """ Simulation on start callback to get notified when simulation starts """ _log.debug( f"GridAppsD simulation id inside sim_on_start(): {sim.simulation_id}" ) self.sim_id = sim.simulation_id def receiver_thread(self, arg): """ GridAPPSD connection thread """ self._receiver_thread = gevent.threading.Thread(group=None, target=arg) self._receiver_thread.daemon = True # Don't let thread prevent termination self._receiver_thread.start() _log.debug('Gridappsd receiver_thread started!') return self._receiver_thread def publish_to_simulation(self, topic, message, **kwargs): """ Publish message to GridAppsD :param topic: GridAppsD publication topic :param message: message :return: """ self.gridappsd.send(topic, message) def pause_simulation(self, timeout=None, **kwargs): """ Pause the GridAppsD simulation """ if timeout is None: self.sim.pause() else: self.sim.pause(timeout) def resume_simulation(self, *args, **kwargs): """ Resume the GridAppsD simulation """ self.sim.resume() def is_sim_installed(self, **kwargs): """ Flag to indicate if GridAppsD is installed """ return HAS_GAPPSD def stop_simulation(self, *args, **kwargs): """ Stop the simulation if running and disconnect from GridAppsD server :return: """ _log.debug('Stopping the simulation') try: if self.sim_id is not None: self.sim.stop() _log.debug('Disconnect GridAppsd') if self.gridappsd is not None: self.gridappsd.disconnect() except Exception: _log.error("Error stop GridAPPSD simulation")