def on_message(self, headers, msg): message = {} try: logger.debug('received message ' + str(msg)) jsonmsg = yaml.safe_load(str(msg)) if jsonmsg['command'] == 'isInitialized': logger.debug('isInitialized check: ' + str(isInitialized)) message['command'] = 'isInitialized' message['response'] = str(isInitialized) if (simulationId != None): message['output'] = _getFncsBusMessages(simulationId) logger.debug('Added isInitialized output, sending message ' + str(message) + ' connection ' + str(gossConnection)) gossConnection.send(output_to_goss_topic, json.dumps(message)) gossConnection.send(output_to_goss_queue, json.dumps(message)) elif jsonmsg['command'] == 'update': message['command'] = 'update' _publishToFncsBus(simulationId, json.dumps( jsonmsg['message'])) #does not return elif jsonmsg['command'] == 'nextTimeStep': logger.debug('is next timestep') message['command'] = 'nextTimeStep' currentTime = jsonmsg['currentTime'] logger.debug('incrementing to ' + str(currentTime)) _doneWithTimestep( currentTime ) #currentTime is incrementing integer 0 ,1, 2.... representing seconds logger.debug('done with timestep ' + str(currentTime)) logger.debug('simulation id ' + str(simulationId)) message['output'] = _getFncsBusMessages(simulationId) responsemsg = json.dumps(message) logger.debug('sending fncs output message ' + str(responsemsg)) gossConnection.send(output_to_goss_topic, responsemsg) gossConnection.send(output_to_goss_queue, responsemsg) elif jsonmsg['command'] == 'stop': fncs.die() sys.exit() except Exception as e: logger.error('Error in command ' + str(e))
def on_disconnected(self): if fncs.is_initialized(): fncs.die()
def on_error(self, headers, message): message_str = 'Error in {} {}'.format('GridAPPSDListener', message) self._gridappsd.send_simulation_status('STOPPED', message_str) if fncs.is_initialized(): fncs.die()
def on_message(self, headers, msg): message = {} try: message_str = 'received message ' + str(msg) if fncs.is_initialized(): self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) else: self._gridappsd.send_simulation_status('STARTED', message_str, DEBUG) json_msg = yaml.safe_load(str(msg)) if json_msg['command'] == 'isInitialized': message_str = 'isInitialized check: ' + str(is_initialized) if fncs.is_initialized(): self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) else: self._gridappsd.send_simulation_status('STARTED', message_str, DEBUG) message['command'] = 'isInitialized' message['response'] = str(is_initialized) if self.simulation_id is not None: message['output'] = self._bridge.get_messages_from_fncs() message_str = 'Added isInitialized output, sending message {}'.format(message) if fncs.is_initialized(): self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) else: self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) self._gridappsd.send(topic=self._bridge.simulation_output_topic, message=json.dumps(message)) elif json_msg['command'] == 'update': message['command'] = 'update' # does not return self._bridge.publish_to_fncs(json.dumps(json_msg['message'])) elif json_msg['command'] == 'nextTimeStep': message_str = 'is next timestep' self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) message['command'] = 'nextTimeStep' current_time = json_msg['currentTime'] message_str = 'incrementing to ' + str(current_time) self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) # current_time is incrementing integer 0 ,1, 2.... representing seconds self._bridge.timestep_complete(current_time) message_str = 'done with timestep ' + str(current_time) self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) message_str = 'simulation id ' + str(self._bridge.simulation_id) self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) message['output'] = self._bridge.get_messages_from_fncs() response_msg = json.dumps(message) message_str = 'sending fncs output message ' + str(response_msg) self._gridappsd.send_simulation_status('RUNNING', message_str, DEBUG) self._gridappsd.send(topic=self._bridge.simulation_output_topic, message=json.dumps(message)) elif json_msg['command'] == 'stop': message_str = 'Stopping the simulation' self._gridappsd.send_simulation_status('STOPPED', message_str) fncs.die() sys.exit() except Exception as e: message_str = 'Error in command ' + str(e) self._gridappsd.send_simulation_status('ERROR', message_str, ERROR) if fncs.is_initialized(): fncs.die()
def start_bridge(self): """Register with the fncs_broker and return. Function arguments: broker_location -- Type: string. Description: The ip location and port for the fncs_broker. It must not be an empty string. Default: 'tcp://localhost:5570'. Function returns: None. Function exceptions: RuntimeError() ValueError() """ global is_initialized # First connect with goos via the GridAPPSD interface self._gridappsd = GridAPPSD(self.simulation_id, id=2, base_simulation_status_topic=BASE_SIMULATION_STATUS_TOPIC) self._gridappsd_listener = GridAPPSDListener(self, self._gridappsd) self._gridappsd.subscribe(self.simulation_input_topic, callback=self._gridappsd_listener) self._gridappsd.send_simulation_status("STARTING", "Starting Bridge for simulation id: {}".format(self.simulation_id)) configuration_zpl = '' try: message_str = 'Registering with FNCS broker ' + str(self.simulation_id) + ' and broker ' + self.fncs_broker_location self._gridappsd.send_simulation_status("STARTED", message_str) message_str = 'connected to goss {}'.format(self._gridappsd.connected) self._gridappsd.send_simulation_status("STARTED", message_str) if not self.simulation_id or type(self.simulation_id) != str: raise ValueError( 'simulation_id must be a nonempty string.\n' + 'simulation_id = {0}'.format(self.simulation_id)) if not self.fncs_broker_location or type(self.fncs_broker_location) != str: raise ValueError( 'broker_location must be a nonempty string.\n' + 'broker_location = {0}'.format(self.fncs_broker_location)) fncs_configuration = { 'name': 'FNCS_GOSS_Bridge_' + self.simulation_id, 'time_delta': '1s', 'broker': self.fncs_broker_location, 'values': { self.simulation_id: { 'topic': self.simulation_id + '/fncs_output', 'default': '{}', 'type': 'JSON', 'list': 'false' } } } configuration_zpl = ('name = {0}\n'.format(fncs_configuration['name']) + 'time_delta = {0}\n'.format(fncs_configuration['time_delta']) + 'broker = {0}\nvalues'.format(fncs_configuration['broker'])) for x in fncs_configuration['values'].keys(): configuration_zpl += '\n {0}'.format(x) configuration_zpl += '\n topic = {0}'.format( fncs_configuration['values'][x]['topic']) configuration_zpl += '\n default = {0}'.format( fncs_configuration['values'][x]['default']) configuration_zpl += '\n type = {0}'.format( fncs_configuration['values'][x]['type']) configuration_zpl += '\n list = {0}'.format( fncs_configuration['values'][x]['list']) fncs.initialize(configuration_zpl) is_initialized = fncs.is_initialized() if is_initialized: message_str = 'Registered with fncs ' + str(is_initialized) self._gridappsd.send_simulation_status("RUNNING", message_str) except Exception as e: message_str = 'Error while registering with fncs broker ' + str(e) self._gridappsd.send_simulation_status('ERROR', message_str, 'ERROR') if fncs.is_initialized(): fncs.die() if not fncs.is_initialized(): message_str = 'fncs.initialize(configuration_zpl) failed!\n' + 'configuration_zpl = {0}'.format( configuration_zpl) self._gridappsd.send_simulation_status('ERROR', message_str, 'ERROR') if fncs.is_initialized(): fncs.die() raise RuntimeError( 'fncs.initialize(configuration_zpl) failed!\n' + 'configuration_zpl = {0}'.format(configuration_zpl))
def on_message(self, headers, msg): message = {} try: message_str = 'received message ' + str(msg) if fncs.is_initialized(): _send_simulation_status('RUNNING', message_str, 'DEBUG') else: _send_simulation_status('STARTED', message_str, 'DEBUG') json_msg = yaml.safe_load(str(msg)) if json_msg['command'] == 'isInitialized': message_str = 'isInitialized check: ' + str(is_initialized) if fncs.is_initialized(): _send_simulation_status('RUNNING', message_str, 'DEBUG') else: _send_simulation_status('STARTED', message_str, 'DEBUG') message['command'] = 'isInitialized' message['response'] = str(is_initialized) if (simulation_id != None): message['output'] = _get_fncs_bus_messages(simulation_id) message_str = 'Added isInitialized output, sending message ' + str( message) + ' connection ' + str(goss_connection) if fncs.is_initialized(): _send_simulation_status('RUNNING', message_str, 'DEBUG') else: _send_simulation_status('STARTED', message_str, 'DEBUG') goss_connection.send(output_to_goss_topic, json.dumps(message)) goss_connection.send(output_to_goss_queue, json.dumps(message)) elif json_msg['command'] == 'update': message['command'] = 'update' _publish_to_fncs_bus( simulation_id, json.dumps(json_msg['message'])) #does not return elif json_msg['command'] == 'nextTimeStep': message_str = 'is next timestep' _send_simulation_status('RUNNING', message_str, 'DEBUG') message['command'] = 'nextTimeStep' current_time = json_msg['currentTime'] message_str = 'incrementing to ' + str(current_time) _send_simulation_status('RUNNING', message_str, 'DEBUG') _done_with_time_step( current_time ) #current_time is incrementing integer 0 ,1, 2.... representing seconds message_str = 'done with timestep ' + str(current_time) _send_simulation_status('RUNNING', message_str, 'DEBUG') message_str = 'simulation id ' + str(simulation_id) _send_simulation_status('RUNNING', message_str, 'DEBUG') message['output'] = _get_fncs_bus_messages(simulation_id) response_msg = json.dumps(message) message_str = 'sending fncs output message ' + str( response_msg) _send_simulation_status('RUNNING', message_str, 'DEBUG') goss_connection.send(output_to_goss_topic, response_msg) goss_connection.send(output_to_goss_queue, response_msg) elif json_msg['command'] == 'stop': message_str = 'Stopping the simulation' _send_simulation_status('stopped', message_str, 'INFO') fncs.die() sys.exit() except Exception as e: message_str = 'Error in command ' + str(e) _send_simulation_status('ERROR', message_str, 'ERROR') if fncs.is_initialized(): fncs.die()
def _register_with_fncs_broker(broker_location='tcp://localhost:5570'): """Register with the fncs_broker and return. Function arguments: broker_location -- Type: string. Description: The ip location and port for the fncs_broker. It must not be an empty string. Default: 'tcp://localhost:5570'. Function returns: None. Function exceptions: RuntimeError() ValueError() """ global is_initialized configuration_zpl = '' try: message_str = 'Registering with FNCS broker ' + str( simulation_id) + ' and broker ' + broker_location _send_simulation_status('STARTED', message_str, 'INFO') message_str = 'still connected to goss 1 ' + str( goss_connection.is_connected()) _send_simulation_status('STARTED', message_str, 'INFO') if simulation_id == None or simulation_id == '' or type( simulation_id) != str: raise ValueError('simulation_id must be a nonempty string.\n' + 'simulation_id = {0}'.format(simulation_id)) if (broker_location == None or broker_location == '' or type(broker_location) != str): raise ValueError('broker_location must be a nonempty string.\n' + 'broker_location = {0}'.format(broker_location)) fncs_configuration = { 'name': 'FNCS_GOSS_Bridge_' + simulation_id, 'time_delta': '1s', 'broker': broker_location, 'values': { simulation_id: { 'topic': simulation_id + '/fncs_output', 'default': '{}', 'type': 'JSON', 'list': 'false' } } } configuration_zpl = ( 'name = {0}\n'.format(fncs_configuration['name']) + 'time_delta = {0}\n'.format(fncs_configuration['time_delta']) + 'broker = {0}\nvalues'.format(fncs_configuration['broker'])) for x in fncs_configuration['values'].keys(): configuration_zpl += '\n {0}'.format(x) configuration_zpl += '\n topic = {0}'.format( fncs_configuration['values'][x]['topic']) configuration_zpl += '\n default = {0}'.format( fncs_configuration['values'][x]['default']) configuration_zpl += '\n type = {0}'.format( fncs_configuration['values'][x]['type']) configuration_zpl += '\n list = {0}'.format( fncs_configuration['values'][x]['list']) fncs.initialize(configuration_zpl) is_initialized = fncs.is_initialized() if is_initialized: message_str = 'Registered with fncs ' + str(is_initialized) _send_simulation_status('RUNNING', message_str, 'INFO') except Exception as e: message_str = 'Error while registering with fncs broker ' + str(e) _send_simulation_status('ERROR', message_str, 'ERROR') if fncs.is_initialized(): fncs.die() if not fncs.is_initialized(): message_str = 'fncs.initialize(configuration_zpl) failed!\n' + 'configuration_zpl = {0}'.format( configuration_zpl) _send_simulation_status('ERROR', message_str, 'ERROR') if fncs.is_initialized(): fncs.die() raise RuntimeError('fncs.initialize(configuration_zpl) failed!\n' + 'configuration_zpl = {0}'.format(configuration_zpl))
def on_error(self, headers, message): message_str = 'Error in goss listener ' + str(message) _send_simulation_status('ERROR', message_str, 'ERROR') if fncs.is_initialized(): fncs.die()
#Publish heartbeat message to voltron bus self.vip.pubsub.publish( 'pubsub', '{0[name]}/heartbeat'.format(self.fncs_zpl), headers, now).get(timeout=5) def fncs_bridge(**kwargs): config = utils.load_config('FNCS_VOLTTRON_Bridge.config') heartbeat_period = config.get('heartbeat_period', 1) heartbeat_multiplier = config.get('heartbeat_multiplier', 1) fncs_zpl = config["fncs_zpl"] params = config["remote_platform_params"] simulation_run_time = config.get("simulation_run_time", "1h") return FNCS_VOLTTRON_Bridge(simulation_run_time, heartbeat_period, heartbeat_multiplier, fncs_zpl, address=remote_url(**params), identity='FNCS_Volttron_Bridge') def main(): '''Main method to start the agent''' utils.vip_main(fncs_bridge) if __name__ == '__main__': # Entry point for script try: sys.exit(main()) except KeyboardInterrupt: if fncs.is_initialized(): fncs.die() pass