pub_count = h.helicsFederateGetPublicationCount(fed) logger.debug(f'\tNumber of publications: {pub_count}') # Diagnostics to confirm JSON config correctly added the required # publications and subscriptions subid = {} sub_name = {} for i in range(0, sub_count): subid[i] = h.helicsFederateGetInputByIndex(fed, i) sub_name[i] = h.helicsSubscriptionGetKey(subid[i]) logger.debug(f'\tRegistered subscription---> {sub_name[i]}') pubid = {} pub_name = {} for i in range(0, pub_count): pubid[i] = h.helicsFederateGetPublicationByIndex(fed, i) pub_name[i] = h.helicsPublicationGetKey(pubid[i]) logger.debug(f'\tRegistered publication---> {pub_name[i]}') ############## Entering Execution Mode ################################## h.helicsFederateEnterExecutingMode(fed) logger.info('Entered HELICS execution mode') hours = 24 * 7 # one week total_interval = int(60 * 60 * hours) update_interval = int( h.helicsFederateGetTimeProperty(fed, h.HELICS_PROPERTY_TIME_PERIOD)) grantedtime = 0 # Define battery physics as empirical values socs = np.array([0, 1])
#fed = create_federate() ################################# Registering federate from json ######################################## fed = h.helicsCreateValueFederateFromConfig('Transmission_json.json') h.helicsFederateRegisterInterfaces(fed, 'Transmission_json.json') federate_name = h.helicsFederateGetName(fed)[-1] print(" Federate {} has been registered".format(federate_name)) pubkeys_count = h.helicsFederateGetPublicationCount(fed) subkeys_count = h.helicsFederateGetInputCount(fed) print(subkeys_count) ###################### Reference to Publications and Subscription form index ############################# pubid = {} subid = {} for i in range(0, pubkeys_count): pubid["m{}".format(i)] = h.helicsFederateGetPublicationByIndex(fed, i) pubtype = h.helicsPublicationGetType(pubid["m{}".format(i)]) print(pubtype) for i in range(0, subkeys_count): subid["m{}".format(i)] = h.helicsFederateGetInputByIndex(fed, i) h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0) sub_key = h.helicsSubscriptionGetKey(subid["m{}".format(i)]) print('Registered Subscription ---> {}'.format(sub_key)) ###################### Entereing Execution Mode ########################################################## h.helicsFederateEnterInitializingMode(fed) status = h.helicsFederateEnterExecutingMode(fed) #Pypower Processing (inputs) hours = 24 total_inteval = int(60 * 60 * hours)
def federate_example(config_path): # Registering federate from json try: fed = h.helicsCreateCombinationFederateFromConfig(config_path) except h._helics.HelicsException as exc: print("Exception occured".format(exc)) exit(-1) federate_name = h.helicsFederateGetName(fed) print(federate_name) endpoint_count = h.helicsFederateGetEndpointCount(fed) subkeys_count = h.helicsFederateGetInputCount(fed) pubkeys_count = h.helicsFederateGetPublicationCount(fed) # Reference to Publications and Subscription form index endid = {} subid = {} pubid = {} for i in range(0,endpoint_count): endid["m{}".format(i)] = h.helicsFederateGetEndpointByIndex(fed, i) end_name = h.helicsEndpointGetName(endid["m{}".format(i)]) logger.info( 'Registered Endpoint ---> {}'.format(end_name)) for i in range(0, subkeys_count): idx = h.helicsFederateGetInputByIndex(fed, i) subid["m{}".format(i)] = idx status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0) sub_key = h.helicsSubscriptionGetKey(idx) logger.info( 'Registered Subscription ---> {}'.format(sub_key)) for i in range(0, pubkeys_count): idx = h.helicsFederateGetPublicationByIndex(fed, i) pubid["m{}".format(i)] = idx pub_key = h.helicsPublicationGetKey(idx) logger.info( 'Registered Publications ---> {}'.format(pub_key)) print('###############################################################################################') print('######################## Entering Execution Mode ##########################################') # Entering Execution Mode h.helicsFederateEnterExecutingMode(fed) print('###############################################################################################') hours = 0.1 total_inteval = int(60 * 60 * hours) grantedtime = -1 update_interval = 1 # 5*60 k = 0 data ={} time.sleep(5) time_sim = [] real = 0 for t in range(0, total_inteval, update_interval): while grantedtime < t: grantedtime = h.helicsFederateRequestTime (fed, t) time.sleep(0.1) print('######################## Time interval {} ##########################################'.format(t)) print('######################## Publishing to topics ######################################') real = real + 1 for i in range(0, pubkeys_count): idx = pubid["m{}".format(i)] h.helicsPublicationPublishComplex(idx, real*i, 78) print( '######################## Get input from subscribed topics #########################') for i in range(0, subkeys_count): idx = subid["m{}".format(i)] value = h.helicsInputGetDouble(idx) key = h.helicsSubscriptionGetKey(idx) print("Value for key: {} is {}".format(key, value)) print('######################## Get from Endpoint #########################################') idx = endid["m{}".format(0)] while h.helicsEndpointHasMessage(idx): msg = h.helicsEndpointGetMessage(idx) end_name = h.helicsEndpointGetName(idx) print("Value from endpoint name: {} is {}".format(end_name, msg.data)) print('######################## Send to VOLTTRON Endpoint #################################') for i in range(0, endpoint_count): idx = endid["m{}".format(i)] value = i + random.randint(1, 101) + 89.7 end_name = h.helicsEndpointGetName(idx) print("Sending Value:{0} for endpoint: {1}".format(value, end_name)) h.helicsEndpointSendEventRaw(idx, '', str(value), t) end_name = h.helicsEndpointGetName(idx) logger.info("Destroying federate") destroy_federate(fed)
def test_valuefederate_subscription_and_publication_registration(): broker = createBroker() vFed, fedinfo = createValueFederate(1, "fed0") pubid = h.helicsFederateRegisterPublication(vFed, "pub1", h.HELICS_DATA_TYPE_STRING, "") pubid2 = h.helicsFederateRegisterGlobalPublication(vFed, "pub2", h.HELICS_DATA_TYPE_INT, "volts") pubid3 = h.helicsFederateRegisterTypePublication(vFed, "pub3", "double", "V") subid1 = h.helicsFederateRegisterSubscription(vFed, "sub1", "") subid2 = h.helicsFederateRegisterSubscription(vFed, "sub2", "") subid3 = h.helicsFederateRegisterSubscription(vFed, "sub3", "V") h.helicsFederateEnterExecutingMode(vFed) publication_type = h.helicsPublicationGetType(pubid3) assert publication_type == "double" sub_key = h.helicsSubscriptionGetKey(subid1) assert sub_key == "sub1" sub_type = h.helicsInputGetType(subid1) assert sub_type == "" sub_key = h.helicsSubscriptionGetKey(subid2) assert sub_key == "sub2" sub_key = h.helicsSubscriptionGetKey(subid3) assert sub_key == "sub3" sub_type = h.helicsInputGetType(subid3) assert sub_type == "" sub_units = h.helicsInputGetUnits(subid3) assert sub_units == "V" sub_type = h.helicsInputGetType(subid2) assert sub_type == "" subid_b = h.helicsFederateGetSubscription(vFed, "sub1") tmp = h.helicsSubscriptionGetKey(subid_b) assert tmp == "sub1" # check the getSubscriptionByIndex function subid_c = h.helicsFederateGetInputByIndex(vFed, 2) tmp = h.helicsInputGetUnits(subid_c) assert tmp == "V" # check publications sv = h.helicsPublicationGetKey(pubid) sv2 = h.helicsPublicationGetKey(pubid2) assert sv == "Testfed0/pub1" assert sv2 == "pub2" pub3name = h.helicsPublicationGetKey(pubid3) assert pub3name == "Testfed0/pub3" type = h.helicsPublicationGetType(pubid3) assert type == "double" units = h.helicsPublicationGetUnits(pubid3) assert units == "V" # check the getSubscription function pubid_b = h.helicsFederateGetPublication(vFed, "Testfed0/pub1") tmp = h.helicsPublicationGetType(pubid_b) assert tmp == "string" # check the getSubscriptionByIndex function pubid_c = h.helicsFederateGetPublicationByIndex(vFed, 1) tmp = h.helicsPublicationGetUnits(pubid_c) assert tmp == "volts" # this one should be invalid # @test_throws h.HELICSErrorInvalidArgument pubid_d = h.helicsFederateGetPublicationByIndex(vFed, 5) h.helicsFederateFinalize(vFed) state = h.helicsFederateGetState(vFed) assert state == h.HELICS_STATE_FINALIZE destroyFederate(vFed, fedinfo) destroyBroker(broker)
def register_inputs(self, config=None, callback=None, **kwargs): """ Register configuration parameters with HELICS. The config parameters may include but not limited to: 1. Name of the federate 2. simulation length 2. Type of core to use (zmq/tcp/udp etc) 3. list (and type) of subscriptions 4. list (and type) of publications 5. broker address (if not default) :param config: config parameters :param callback: Register agent callback method :return: """ self._work_callback = callback # Build HELICS config from agent config helics_config = deepcopy(config) properties = helics_config.pop('properties', {}) if not properties: raise RuntimeError( "Invalid configuration. Missing properties dictionary") self._simulation_delta = properties.pop('timeDelta', 1.0) # seconds self._simulation_length = properties.pop('simulation_length', 3600) # seconds for key, value in properties.items(): helics_config[key] = value subscriptions = helics_config.pop('outputs', []) for sub in subscriptions: volttron_topic = sub.pop('volttron_topic', None) if volttron_topic is not None: self.helics_to_volttron_publish[sub.get( 'key')] = volttron_topic sub['key'] = sub.pop('sim_topic') # Replace 'outputs' key with 'subscriptions' key if subscriptions: helics_config['subscriptions'] = subscriptions publications = helics_config.pop('inputs', []) for pub in publications: volttron_topic = pub.pop('volttron_topic', None) pub['key'] = pub.pop('sim_topic') # Replace 'inputs' key with 'publications' key if publications: helics_config['publications'] = publications _log.debug("new config: {}".format(helics_config)) # Create a temporary json file tmp_file = os.path.join(os.getcwd(), 'fed_cfg.json') _log.debug("tmp file: {}".format(tmp_file)) with open(tmp_file, 'w') as fout: fout.write(jsonapi.dumps(helics_config)) _log.debug("Create Combination Federate") # Create federate from provided config parameters try: self.fed = h.helicsCreateCombinationFederateFromConfig(tmp_file) except h._helics.HelicsException as e: _log.exception("Error parsing HELICS config {}".format(e)) # Check if HELICS broker correctly registered inputs federate_name = h.helicsFederateGetName(self.fed) _log.debug("Federate name: {}".format(federate_name)) endpoint_count = h.helicsFederateGetEndpointCount(self.fed) _log.debug("Endpoint count: {}".format(endpoint_count)) subkeys_count = h.helicsFederateGetInputCount(self.fed) _log.debug("Subscription key count: {}".format(subkeys_count)) pubkeys_count = h.helicsFederateGetPublicationCount(self.fed) _log.debug("Publication key count: {}".format(endpoint_count)) for i in range(0, endpoint_count): try: endpt_idx = h.helicsFederateGetEndpointByIndex(self.fed, i) endpt_name = h.helicsEndpointGetName(endpt_idx) self.endpoints[endpt_name] = endpt_idx except h._helics.HelicsException as e: _log.exception( "Error getting helics endpoint index: {}".format(e)) for i in range(0, subkeys_count): inputs = dict() try: idx = h.helicsFederateGetInputByIndex(self.fed, i) inputs['sub_id'] = idx inputs['type'] = h.helicsInputGetType(idx) inputs['key'] = h.helicsSubscriptionGetKey(idx) self.inputs.append(inputs) data = dict(type=inputs['type'], value=None) except h._helics.HelicsException as e: _log.exception( "Error getting helics input index: {}".format(e)) for i in range(0, pubkeys_count): outputs = dict() try: idx = h.helicsFederateGetPublicationByIndex(self.fed, i) outputs['pub_id'] = idx outputs['type'] = h.helicsPublicationGetType(idx) pub_key = h.helicsPublicationGetKey(idx) _log.debug("Publication: {}".format(pub_key)) self.outputs[pub_key] = outputs data = dict(type=outputs['type'], value=None) except h._helics.HelicsException as e: _log.exception( "Error getting helics publication index: {}".format(e))