示例#1
0
    def _fncs_loop(self):
        _log.info("Starting fncs loop")
        self._simulation_started = True
        while self._current_step < self._simulation_length:
            # Block until the work is done here.
            subKeys = fncs.get_events()
            self._raise_if_error("After get_events")
            self._current_values.clear()

            for x in subKeys:
                fncs_topic = self._registered_fncs_topics[x].get('fncs_topic')
                self._current_values[fncs_topic] = fncs.get_value(x)
                if not fncs.is_initialized():
                    fncs.die()
                    raise RuntimeError("FNCS unexpected error after get_values")

            self._work_callback()

            subKeys = fncs.get_events()

            if len(subKeys) > 0:
                for x in subKeys:
                    subkeyvalue = fncs.get_value(x)
                    volttron_topic = self._registered_fncs_topics[x].get('volttron_topic')
                    if volttron_topic:
                        self.pubsub().publish('pubsub', topic=volttron_topic, message=subkeyvalue)

            # This allows other event loops to run
            gevent.sleep(0.000000001)

        self._simulation_complete = True
        fncs.finalize()
        if self._stop_agent_when_sim_complete:
            self.core().stop()
示例#2
0
 def on_error(self, headers, message):
     global stop_simulation
     message_str = 'Error in goss listener '+str(message)
     _send_simulation_status('ERROR', message_str, 'ERROR')
     stop_simulation = True
     if fncs.is_initialized():
         fncs.die()
示例#3
0
 def on_message(self, headers, msg):
     global stop_simulation
     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))
         print("\n{}\n".format(json_msg['command']))
         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')
             message['timestamp'] = datetime.utcnow().microsecond
             goss_connection.send(output_to_simulation_manager , json.dumps(message))
         elif json_msg['command'] == 'update':
             message['command'] = 'update'
             _publish_to_fncs_bus(simulation_id, json.dumps(json_msg['input'])) #does not return
         elif json_msg['command'] == 'nextTimeStep':
             message['command'] = 'nextTimeStep'
             current_time = json_msg['currentTime']
             message_str = 'incrementing to '+str(current_time + 1)
             _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['output'] = _get_fncs_bus_messages(simulation_id)
             message['timestamp'] = datetime.utcnow().microsecond
             response_msg = json.dumps(message)
             goss_connection.send(output_to_goss_topic + "{}".format(simulation_id) , response_msg)
         elif json_msg['command'] == 'stop':
             message_str = 'Stopping the simulation'
             _send_simulation_status('CLOSED', message_str, 'INFO')
             stop_simulation = True
             fncs.finalize()
             
     
     except Exception as e:
         message_str = 'Error in command '+str(e)
         _send_simulation_status('ERROR', message_str, 'ERROR')
         stop_simulation = True
         if fncs.is_initialized():
             fncs.die()
 def run_simulation(self):
     try:
         current_time = 0
         while current_time <= self.sim_length:
             sim_message_topics = fncs.get_events()
             if self.sim_id in sim_message_topics:
                 message = fncs.get_value(self.sim_id)
             time_request = current_time + 1
             if time_request > self.sim_length:
                 fncs.finalize()
                 break
             time_approved = fncs.time_request(time_request)
             if time_approved != time_request:
                 raise RuntimeError(
                     "The time approved from the fncs broker is not the time requested.\ntime_request = {}.\ntime_approved = {}"
                     .format(time_request, time_approved))
             current_time += 1
     except Exception as e:
         if fncs.is_initialized():
             fncs.die()
         raise
 def register_with_fncs(self):
     fncs_configuration = {
         "name": "PythonListener{}".format(self.sim_id),
         "time_delta": "1s",
         "broker": self.broker_location,
         "values": {
             "{}".format(self.sim_id): {
                 "topic": self.subscription_topic,
                 "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'])
     try:
         fncs.initialize(configuration_zpl)
         if not fncs.is_initialized():
             raise RuntimeError(
                 "fncs.initialize(configuration_zpl) failed!\nconfiguration_zpl = {}"
                 .format(configuration_zpl))
     except Exception as e:
         if fncs.is_initialized():
             fncs.die()
         raise
示例#6
0
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
    global stop_simulation
    configuration_zpl = ''
    try:
        message_str = 'Registering with FNCS broker '+str(simulation_id)+' and broker '+broker_location
        ('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')
        stop_simulation = True
        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')
        stop_simulation = True
        if fncs.is_initialized():
            fncs.die()
        raise RuntimeError(
            'fncs.initialize(configuration_zpl) failed!\n'
            + 'configuration_zpl = {0}'.format(configuration_zpl))
示例#7
0
 def on_disconnected(self):
     global stop_simulation
     stop_simulation = True
     if fncs.is_initialized():
         fncs.die()
示例#8
0
 def _raise_if_error(self, location):
     if not fncs.is_initialized():
         fncs.die()
         raise RuntimeError("FNCS unexpected error: {}".format(location))
示例#9
0
 def reset(self):
     self.__raise_if_not_installed()
     fncs.die()
示例#10
0
 def _raise_if_error(self, location):
     if not fncs.is_initialized():
         fncs.die()
         raise RuntimeError("FNCS unexpected error: {}".format(location))
示例#11
0
 def reset(self):
     self.__raise_if_not_installed()
     fncs.die()