Ejemplo n.º 1
0
def init_logger(config_file_name):
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    my_epid = h.helicsFederateGetEndpoint(fed, "logger")

    fed_name = h.helicsFederateGetName(fed)
    #	print(fed_name)
    pid = os.getpid()
    #	print("Logger Pid {}".format(pid))
    currenttime = -1

    output = ""
    log.basicConfig(filename='./log/logger.log',
                    filemode='w',
                    format='%(message)s',
                    level=log.INFO)

    h.helicsFederateEnterExecutingMode(fed)

    h.helicsFederateRequestTime(fed, maxtime)
    ideal_time_data = h.helicsEndpointGetMessage(my_epid)
    if h.helicsEndpointHasMessage(my_epid):
        output = output + "ideal simulation time " + ideal_time_data.data + "\n"

    while (currenttime < maxtime):
        currenttime = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            count = h.helicsEndpointPendingMessages(my_epid)
            for i in range(count):
                message = h.helicsEndpointGetMessage(my_epid)
                output = output + str(message.data) + "\n"
    log.info(output)
    h.helicsFederateFinalize(fed)
    print(fed_name, " : Federate finalized")
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 2
0
def init_worker(config_file_name, manager_name):
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)

    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    fed_name = h.helicsFederateGetName(fed)

    dest = manager_name + "/data"
    pid = os.getpid()
    h.helicsFederateEnterExecutingMode(fed)

    current_time = h.helicsFederateRequestTime(fed, maxtime)
    simulation_time_data = h.helicsEndpointGetMessage(my_epid)
    sleep_time = float(simulation_time_data.data)

    current_time = -1
    while current_time < maxtime:
        current_time = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            message = h.helicsEndpointGetMessage(my_epid)
            data = str(fed_name) + "(" + str(pid) + "): " + str(message.data)
            #			time.sleep(random.randrange(4))
            time.sleep(float(sleep_time))
            h.helicsEndpointSendMessageRaw(my_epid, str(dest), data)

    h.helicsFederateFinalize(fed)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 3
0
def init_worker(config_file_name, manager_name, individual_simulation_time):
    print("worker in")
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    print("worker passed config")
    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    fed_name = h.helicsFederateGetName(fed)

    dest = manager_name + "/data"
    pid = os.getpid()
    print(fed_name, " about to Started")
    h.helicsFederateEnterExecutingMode(fed)

    print(fed_name, " Started")
    current_time = -1
    while current_time < maxtime:
        current_time = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            message = h.helicsEndpointGetMessage(my_epid)
            data = str(fed_name) + "(" + str(pid) + "): " + str(message.data)
            #			time.sleep(random.randrange(4))
            time.sleep(individual_simulation_time)
            h.helicsEndpointSendMessageRaw(my_epid, str(dest), data)

    h.helicsFederateFinalize(fed)
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 4
0
def test_message_federate_endpoint_registration(mFed):
    epid1 = h.helicsFederateRegisterEndpoint(mFed, "ep1", None)
    epid2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "ep2", "random")

    h.helicsFederateSetTimeDelta(mFed, 1.0)
    h.helicsFederateEnterExecutionMode(mFed)

    data = "random-data"

    status = h.helicsEndpointSendEventRaw(epid1, "ep2", data, 1.0)

    status, granted_time = h.helicsFederateRequestTime(mFed, 1.0)

    assert granted_time == 1.0

    res = h.helicsFederateHasMessage(mFed)
    assert res == 1

    res = h.helicsEndpointHasMessage(epid1)
    # TODO: Figure out why this is returning zero
    assert res == 0

    res = h.helicsEndpointHasMessage (epid2)
    assert res == 1

    # This causes a segfault
    message = h.helicsEndpointGetMessage(epid2)

    assert message.data == 'random-data'
    assert message.length == 11
    assert message.original_dest == ''
    assert message.original_source == 'TestA Federate/ep1'
    assert message.source == 'TestA Federate/ep1'
    assert message.time == 1.0
Ejemplo n.º 5
0
def test_bad_input_message_federate_message():
    broker = createBroker(1)
    mFed1, fedinfo = createMessageFederate(1, "test")

    ept1 = h.helicsFederateRegisterGlobalEndpoint(mFed1, "ept1", "")
    with pt.raises(h.HelicsException):
        h.helicsFederateRegisterGlobalEndpoint(mFed1, "ept1", "")

    h.helicsFederateEnterExecutingMode(mFed1)
    h.helicsEndpointSetDefaultDestination(ept1, "ept1")

    mess0 = h.helicsEndpointGetMessage(ept1)
    mess0 = h.helicsFederateGetMessage(mFed1)

    with pt.raises(h.HelicsException):
        h.helicsEndpointSendMessage(ept1, mess0)

    h.helicsFederateRequestNextStep(mFed1)
    cnt = h.helicsEndpointPendingMessages(ept1)
    assert cnt == 0

    h.helicsFederateFinalize(mFed1)
    # @test_throws h.HELICSErrorInvalidFunctionCall
    with pt.raises(h.HelicsException):
        h.helicsEndpointSendMessage(ept1, mess0)

    destroyFederate(mFed1, fedinfo)
    destroyBroker(broker)
Ejemplo n.º 6
0
def test_message_federate_send(mFed):
    epid1 = h.helicsFederateRegisterEndpoint(mFed, "ep1", None)
    epid2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "ep2", "random")

    h.helicsFederateSetTimeProperty(mFed, h.helics_property_time_delta, 1.0)
    h.helicsFederateEnterExecutingMode(mFed)

    data = "random-data"

    h.helicsEndpointSendEventRaw(epid1, "ep2", data, 1.0)

    granted_time = h.helicsFederateRequestTime(mFed, 2.0)
    assert granted_time == 1.0

    res = h.helicsFederateHasMessage(mFed)
    assert res == 1

    res = h.helicsEndpointHasMessage(epid1)
    assert res == 0

    res = h.helicsEndpointHasMessage(epid2)
    assert res == 1

    message = h.helicsEndpointGetMessage(epid2)

    assert message.data == "random-data"
    assert message.length == 11
    assert message.original_dest == ""
    assert message.original_source == "TestA Federate/ep1"
    assert message.source == "TestA Federate/ep1"
    assert message.time == 1.0
Ejemplo n.º 7
0
def main(delay=None):

    broker = create_broker()
    fed = create_value_federate(broker)

    pubid = h.helicsFederateRegisterGlobalTypePublication(
        fed, "federate1-to-federate2", h.HELICS_DATA_TYPE_STRING, "")
    subid = h.helicsFederateRegisterSubscription(fed, "federate2-to-federate1",
                                                 "double", "")
    epid = h.helicsFederateRegisterGlobalEndpoint(fed, "endpoint1", "")

    if delay is not None:
        fid = h.helicsFederateRegisterSourceFilter(fed, h.helics_delay_filter,
                                                   "endpoint2", "filter-name")

    h.helicsSubscriptionSetDefaultDouble(subid, 0)

    print("Entering execution mode")
    h.helicsFederateEnterExecutionMode(fed)

    if delay is not None:
        h.helicsFilterSet(fid, "delay", 2.0)

    grantedtime = -1
    while True:
        try:
            stop_at_time, value_to_send = get_input(grantedtime)
        except KeyboardInterrupt:
            print("")
            break
        while grantedtime < stop_at_time:
            print(">>>>>>>> Requesting time = {}".format(stop_at_time))
            status, grantedtime = h.helicsFederateRequestTime(
                fed, stop_at_time)
            assert status == 0
            if grantedtime != stop_at_time:
                status, value = h.helicsSubscriptionGetString(subid)
                assert status == 0
                print("Interrupt value '{}' from Federate 2".format(value))
            print("<<<<<<<< Granted Time = {}".format(grantedtime))
        assert grantedtime == stop_at_time, "stop_at_time = {}, grantedtime = {}".format(
            stop_at_time, grantedtime)
        if value_to_send is not None and value_to_send != '':
            print("Sending '{}' to Federate 2".format(value_to_send))
            status = h.helicsPublicationPublishString(pubid,
                                                      str(value_to_send))
            assert status == 0
            status = h.helicsEndpointSendMessageRaw(epid, "endpoint2",
                                                    str(value_to_send))
            assert status == 0
        status, value = h.helicsSubscriptionGetString(subid)
        assert status == 0
        print("Received value '{}' from Federate 2".format(value))
        while h.helicsEndpointHasMessage(epid):
            value = h.helicsEndpointGetMessage(epid)
            print("Received message '{}' at time {} from Federate 2".format(
                value.data, value.time))
        print("----------------------------------")

    destroy_value_federate(fed, broker)
Ejemplo n.º 8
0
def test_filter_type_tests_message_filter_function():

    broker = createBroker(2)
    fFed, fedinfo1 = createMessageFederate(1, "filter")
    mFed, fedinfo2 = createMessageFederate(1, "message")

    h.helicsFederateSetFlagOption(mFed,
                                  h.HELICS_FLAG_IGNORE_TIME_MISMATCH_WARNINGS,
                                  True)
    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    f1 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    h.helicsFilterSet(f1, "delay", 2.5)

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsFederateHasMessage(mFed) is False

    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False

    h.helicsFederateRequestTimeAsync(fFed, 3.0)
    h.helicsFederateRequestTime(mFed, 3.0)

    assert h.helicsEndpointHasMessage(p2) is True

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    h.helicsFederateRequestTime(mFed, 3.0)
    h.helicsFederateRequestTimeComplete(fFed)
    h.helicsFederateFinalizeAsync(mFed)
    h.helicsFederateFinalize(fFed)
    h.helicsFederateFinalizeComplete(mFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(fFed, fedinfo1)
    destroyFederate(mFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 9
0
def test_messagefederate_test_message_federate_send(mFed):

    epid1 = h.helicsFederateRegisterEndpoint(mFed, "ep1", "")
    epid2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "ep2", "random")

    h.helicsFederateSetTimeProperty(mFed, h.HELICS_PROPERTY_TIME_DELTA, 1.0)
    h.helicsFederateEnterExecutingMode(mFed)

    data = "random-data"

    h.helicsEndpointSendEventRaw(epid1, "ep2", data, 1.0)

    granted_time = h.helicsFederateRequestTime(mFed, 2.0)
    assert granted_time == 1.0

    res = h.helicsFederateHasMessage(mFed)
    assert res is True

    res = h.helicsEndpointHasMessage(epid1)
    assert res is False

    res = h.helicsEndpointHasMessage(epid2)
    assert res is True

    message = h.helicsEndpointGetMessage(epid2)

    assert h.helicsMessageGetMessageID(message) == 55
    assert h.helicsMessageIsValid(message) is True
    assert h.helicsMessageGetString(message) == "random-data"
    assert h.helicsMessageGetRawDataSize(message) == 11
    assert h.helicsMessageGetOriginalDestination(message) == ""
    assert h.helicsMessageGetOriginalSource(message) == "TestA Federate/ep1"
    assert h.helicsMessageGetSource(message) == "TestA Federate/ep1"
    assert h.helicsMessageGetTime(message) == 1.0
Ejemplo n.º 10
0
def main(delay=None):

    broker = create_broker()
    fed = create_value_federate(broker)

    pubid = h.helicsFederateRegisterGlobalTypePublication(
        fed, "federate1-to-federate2", "string", "")
    subid = h.helicsFederateRegisterSubscription(fed, "federate2-to-federate1",
                                                 "")
    epid = h.helicsFederateRegisterGlobalEndpoint(fed, "endpoint1", "")

    if delay is not None:
        fid = h.helicsFederateRegisterGlobalFilter(fed,
                                                   h.helics_filter_type_delay,
                                                   "filter-name")
        h.helicsFilterAddSourceTarget(fid, "endpoint1")

    h.helicsInputSetDefaultNamedPoint(subid, "", 0)

    print("Entering execution mode")
    h.helicsFederateEnterExecutingMode(fed)

    if delay is not None:
        h.helicsFilterSet(fid, "delay", delay)
    grantedtime = -1
    while True:
        try:
            stop_at_time, value_to_send = get_input(grantedtime)
            print(stop_at_time)
        except KeyboardInterrupt:
            print("")
            break
        while grantedtime < stop_at_time:
            print(">>>>>>>> Requesting time = {}".format(stop_at_time))
            grantedtime = h.helicsFederateRequestTime(fed, stop_at_time)
            grantedtime = int(grantedtime)
            if grantedtime != stop_at_time:
                value = h.helicsSubscriptionGetKey(subid)
                print("Interrupt value '{}' from Federate 2".format(value))
            print("<<<<<<<< Granted Time = {}".format(grantedtime))
        assert (grantedtime == stop_at_time
                ), "stop_at_time = {}, grantedtime = {}".format(
                    stop_at_time, grantedtime)
        if value_to_send is not None and value_to_send != "":
            print("Sending '{}' to Federate 2".format(value_to_send))
            h.helicsPublicationPublishString(pubid, str(value_to_send))
            h.helicsEndpointSendMessageRaw(epid, "endpoint2",
                                           str(value_to_send))
        value = h.helicsSubscriptionGetKey(subid)
        print("Received value '{}' from Federate 2".format(value))
        while h.helicsEndpointHasMessage(epid):
            value = h.helicsEndpointGetMessage(epid)
            print("Received message '{}' at time {} from Federate 2".format(
                value.data, value.time))
        print("----------------------------------")

    destroy_value_federate(fed, broker)
Ejemplo n.º 11
0
def init_manager(config_file_name, worker_name_list):
    print("manager in")
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    print("manager passed config")
    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    log_id = h.helicsFederateGetEndpoint(fed, "logger")
    log_dest = h.helicsEndpointGetDefaultDestination(log_id)

    currenttime = -1
    print("Manager about to Started")
    h.helicsFederateEnterExecutingMode(fed)
    print("Manager Started")
    for t in range(1, 11):
        h.helicsEndpointSendMessageRaw(log_id, log_dest,
                                       "Timestep {}".format(t))

        message = "Hello World " + str(t)
        while currenttime < t:
            currenttime = h.helicsFederateRequestTime(fed, t)

        log_msg = ""

        ################### START TIMING ###############
        start_time = time.time_ns() / (10**9)
        ##############################################

        for worker_name in worker_name_list:
            h.helicsEndpointSendMessageRaw(my_epid, worker_name + "/data",
                                           message)

        while not (h.helicsEndpointPendingMessages(my_epid)
                   == len(worker_name_list)):
            currenttime = h.helicsFederateRequestTime(fed, 0)

        for i in range(len(worker_name_list)):
            if h.helicsEndpointHasMessage(my_epid):
                new_message = h.helicsEndpointGetMessage(my_epid)
                log_msg = log_msg + "From: {}  Msg: {}  Time: {}\n".format(
                    new_message.source, new_message.data, new_message.time)

        ################### END TIMING ##################
        end_time = time.time_ns() / (10**9)
        ###############################################

        time_taken = "Time taken for iteration " + str(t) + ": " + str(
            end_time - start_time) + "\n"

        h.helicsEndpointSendMessageRaw(log_id, log_dest, log_msg)
        h.helicsEndpointSendMessageRaw(log_id, log_dest, time_taken)

    fed_name = h.helicsFederateGetName(fed)
    h.helicsFederateFinalize(fed)
    #	print("{}: Federate finalized".format(fed_name))
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 12
0
def test_messagefederate_message_object_tests(mFed):

    epid1 = h.helicsFederateRegisterEndpoint(mFed, "ep1", "")
    epid2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "ep2", "random")

    h.helicsFederateSetTimeProperty(mFed, h.HELICS_PROPERTY_TIME_DELTA, 1.0)

    h.helicsFederateEnterExecutingMode(mFed)

    assert h.helicsFederateGetState(mFed) == h.HELICS_STATE_EXECUTION

    msg = h.helicsFederateCreateMessage(mFed)
    h.helicsMessageSetDestination(msg, "ep2")
    h.helicsMessageGetDestination(msg) == "ep2"
    h.helicsMessageSetData(msg, "".join(["a" for _ in range(0, 500)]).encode())
    h.helicsMessageSetTime(msg, 0.0)

    h.helicsEndpointSendMessage(epid1, msg)
    t = h.helicsFederateRequestTime(mFed, 1.0)
    assert t == 1.0

    assert h.helicsFederateHasMessage(mFed) is True
    assert h.helicsEndpointHasMessage(epid1) is False
    assert h.helicsEndpointHasMessage(epid2) is True

    msg = h.helicsEndpointGetMessage(epid2)
    assert h.helicsMessageGetRawDataSize(msg) == 500
    # TODO: segfaults
    # print(h.helicsMessageGetRawData(msg))
    # @test_broken False
    # segfaults
    # rawdata = h.helicsMessageGetRawDataPointer(msg)
    # assert Char(unsafe_load(Ptr{Cchar}(rdata), 245)) == 'a'

    h.helicsFederateFinalize(mFed)

    assert h.helicsFederateGetState(mFed) == h.HELICS_STATE_FINALIZE

    h.helicsMessageSetFlagOption(msg, 7, True)
    assert h.helicsMessageCheckFlag(msg, 7) is True
    h.helicsMessageClearFlags(msg)
    assert h.helicsMessageCheckFlag(msg, 7) is False

    h.helicsEndpointSetDefaultDestination(epid1, "ep2")
Ejemplo n.º 13
0
    def _sim_loop(self):
        """
        Continuous loop to get registered input values from HELICS and feed it to user callback
        :return:
        """
        _log.info("Starting simulation loop")
        self._simulation_started = True
        while self.current_time < self._simulation_length:
            for in_put in self.inputs:
                sub_key = in_put['key']
                # NOTE: Values are persisted in HELICS. Old values are returned if they dont
                # get updated in current time step
                self.current_values[sub_key] = self._get_input_based_on_type(
                    in_put)
                try:
                    # Get VOLTTRON topic for the input key
                    volttron_topic = self.helics_to_volttron_publish[sub_key]
                    self.pubsub().publish('pubsub',
                                          topic=volttron_topic,
                                          message=self.current_values[sub_key])
                except KeyError:
                    # No VOLTTRON topic for input key
                    pass

            # Collect any messages from endpoints (messages are not persistent)
            for name, idx in self.endpoints.items():
                try:
                    if h.helicsEndpointHasMessage(idx):
                        msg = h.helicsEndpointGetMessage(idx)
                        self.current_values[name] = msg.data
                except h._helics.HelicsException as e:
                    _log.exception(
                        "Error getting endpoint message from  HELICS {}".
                        format(e))

            # Call user provided callback to perform work on HELICS inputs
            self._work_callback()
            # This allows other event loops to run
            gevent.sleep(0.000000001)
        _log.debug("Simulation completed. Closing connection to HELICS")
        # Check if anything to publish
        self._simulation_complete = True
        # Closing connection to HELICS
        self.stop_simulation()
Ejemplo n.º 14
0
def init_manager(config_file_name, worker_name_list):
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)

    my_epid = h.helicsFederateGetEndpoint(fed, "data")
    log_id = h.helicsFederateGetEndpoint(fed, "logger")
    log_dest = h.helicsEndpointGetDefaultDestination(log_id)

    currenttime = -1
    h.helicsFederateEnterExecutingMode(fed)

    for t in range(1, 11):
        h.helicsEndpointSendMessageRaw(log_id, log_dest,
                                       "Timestep {}".format(t))

        message = "Hello World " + str(t)
        while currenttime < t:
            currenttime = h.helicsFederateRequestTime(fed, t)

        for worker_name in worker_name_list:
            h.helicsEndpointSendMessageRaw(my_epid, worker_name + "/data",
                                           message)

        while not (h.helicsEndpointPendingMessages(my_epid)
                   == len(worker_name_list)):
            currenttime = h.helicsFederateRequestTime(fed, 0)
        log_msg = ""
        for i in range(len(worker_name_list)):
            if h.helicsEndpointHasMessage(my_epid):
                new_message = h.helicsEndpointGetMessage(my_epid)
                log_msg = log_msg + "From: {}  Msg: {}  Time: {}\n".format(
                    new_message.source, new_message.data, new_message.time)

        h.helicsEndpointSendMessageRaw(log_id, log_dest, log_msg)

    fed_name = h.helicsFederateGetName(fed)
    h.helicsFederateFinalize(fed)

    #	print("{}: Federate finalized".format(fed_name))

    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 15
0
def init_logger(config_file_name, log_out_file_name, total_simulation_time,
                individual_simulation_time):
    print("logger in")
    fed = h.helicsCreateMessageFederateFromConfig(config_file_name)
    print("logger passed config")
    my_epid = h.helicsFederateGetEndpoint(fed, "logger")

    fed_name = h.helicsFederateGetName(fed)
    #	print(fed_name)
    pid = os.getpid()
    #	print("Logger Pid {}".format(pid))
    currenttime = -1

    output = ""
    log.basicConfig(filename="./log/{}".format(log_out_file_name),
                    filemode='w',
                    format='%(message)s',
                    level=log.INFO)

    print(fed_name, " about to Started")
    h.helicsFederateEnterExecutingMode(fed)

    print(fed_name, "Started")
    while (currenttime < maxtime):
        currenttime = h.helicsFederateRequestTime(fed, maxtime)
        if h.helicsEndpointHasMessage(my_epid):
            count = h.helicsEndpointPendingMessages(my_epid)
            for i in range(count):
                message = h.helicsEndpointGetMessage(my_epid)
                #				log.log(str(message.messageID))
                output = output + str(message.data) + "message id: " + "\n"
    log.info(output)
    h.helicsFederateFinalize(fed)
    print(fed_name, " : Federate finalized")
    h.helicsFederateFree(fed)
    h.helicsCloseLibrary()
Ejemplo n.º 16
0
                charging_voltage[j] = charge_V[0]

                currentsoc[j] = 0  # Initial SOC estimate
                logger.debug(f'\t New EV, SOC estimate: {currentsoc[j]:.4f}')
                logger.debug(f'\t New EV, charging voltage:'
                             f' {charging_voltage[j]}')
            else:
                # SOC estimation
                currentsoc[j] = estimate_SOC(charging_voltage[j],
                                             charging_current)
                logger.debug(f'\t EV SOC estimate: {currentsoc[j]:.4f}')

            # Check for messages from EV Controller
            endpoint_name = h.helicsEndpointGetName(endid[j])
            if h.helicsEndpointHasMessage(endid[j]):
                msg = h.helicsEndpointGetMessage(endid[j])
                instructions = h.helicsMessageGetString(msg)
                logger.debug(f'\tReceived message at endpoint {endpoint_name}'
                             f' at time {grantedtime}'
                             f' with command {instructions}')

                # Update charging state based on message from controller
                # The protocol used by the EV and the EV Controller is simple:
                #       EV Controller sends "1" - keep charging
                #       EV Controller sends anything else: stop charging
                # The default state is charging (1) so we only need to
                #   do something if the controller says to stop
                if int(instructions) == 0:
                    # Stop charing this EV
                    charging_voltage[j] = 0
                    logger.info(f'\tEV full; removing charging voltage')
Ejemplo n.º 17
0
def test_filter_test_types_clone_test_broker_dest_connections():

    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(1, "source", 1.0)
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1.0)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 1.0)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    p3 = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterGlobalCloningFilter(dcFed, "filt1")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")
    h.helicsBrokerAddDestinationFilterToEndpoint(broker, "filt1", "dest")

    h.helicsBrokerAddDestinationFilterToEndpoint(broker, "", "dest")

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateRequestTimeAsync(sFed, 1.0)
    h.helicsFederateRequestTimeAsync(dcFed, 1.0)
    h.helicsFederateRequestTime(dFed, 1.0)
    h.helicsFederateRequestTimeComplete(sFed)
    h.helicsFederateRequestTimeComplete(dcFed)

    assert h.helicsFederateHasMessage(dFed) is True

    m2 = h.helicsEndpointGetMessage(p2)

    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    h.helicsFederateFinalizeAsync(sFed)
    h.helicsFederateFinalizeAsync(dFed)

    # TODO: figure out why this test fails on CI
    # @test_broken False
    # assert h.helicsFederateHasMessage(dcFed) is False

    # h.helicsFederateRequestTime(dcFed, 2.0)

    # assert h.helicsFederateHasMessage(dcFed) is True

    # m2 = h.helicsEndpointGetMessage(p3)
    # assert h.helicsMessageGetSource(m2) == "src"
    # assert h.helicsMessageGetOriginalSource(m2) == "src"
    # assert h.helicsMessageGetDestination(m2) == "cm"
    # assert h.helicsMessageGetOriginalDestination(m2) == "dest"
    # assert h.helicsMessageGetRawDataSize(m2) == len(data)

    # _ = h.helicsFederateHasMessage(dcFed)

    h.helicsFederateFinalize(dcFed)
    h.helicsFederateFinalizeComplete(sFed)
    h.helicsFederateFinalizeComplete(dFed)
    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)
Ejemplo n.º 18
0
currenttime = h.helicsFederateRequestTime(fed, 100)[-1]
print("PI RECEIVER: Current time is {} ".format(currenttime))

isupdated = h.helicsSubscriptionIsUpdated(sub)

if isupdated == 1:
    result, value = h.helicsSubscriptionGetDouble(sub)
    print("PI RECEIVER: Received value = {} at time {} from PI SENDER".format(
        value, currenttime))

while currenttime <= 100:

    currenttime = h.helicsFederateRequestTime(fed, 100)[-1]

    isupdated = h.helicsSubscriptionIsUpdated(sub)

    if isupdated == 1:
        result, value = h.helicsSubscriptionGetDouble(sub)
        print("PI RECEIVER: Received value = {} at time {} from PI SENDER".
              format(value, currenttime))
    while h.helicsEndpointHasMessage(epid):
        value = h.helicsEndpointGetMessage(epid)
        print("PI RECEIVER: Received message '{}' at time {} from PI SENDER".
              format(value.data, value.time))

status = h.helicsFederateFinalize(fed)

h.helicsFederateFree(fed)
h.helicsCloseLibrary()
print("PI RECEIVER: Federate finalized")
Ejemplo n.º 19
0
def test_filter_test_types_clone_test_connections():

    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(
        1,
        "source",
        1.0,
    )
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1.0)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 1.0)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    p3 = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterGlobalCloningFilter(dcFed, "filt1")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")
    cr = h.helicsFederateGetCoreObject(sFed)

    h.helicsCoreAddSourceFilterToEndpoint(cr, "filt1", "src")
    h.helicsCoreAddSourceFilterToEndpoint(cr, "", "src")

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    q = h.helicsCreateQuery("", "filtered_endpoints")
    filteredEndpoints = h.helicsQueryExecute(q, sFed)
    assert "srcFilters" in str(filteredEndpoints)
    assert "(cloning)" in str(filteredEndpoints)
    h.helicsQueryFree(q)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateRequestTimeAsync(sFed, 1.0)
    h.helicsFederateRequestTimeAsync(dcFed, 1.0)
    h.helicsFederateRequestTime(dFed, 1.0)
    h.helicsFederateRequestTimeComplete(sFed)
    h.helicsFederateRequestTimeComplete(dcFed)

    assert h.helicsFederateHasMessage(dFed) is True

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    assert h.helicsFederateHasMessage(dcFed) is True

    m2 = h.helicsEndpointGetMessage(p3)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "cm"
    assert h.helicsMessageGetOriginalDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    h.helicsFederateFinalizeAsync(sFed)
    h.helicsFederateFinalizeAsync(dFed)
    h.helicsFederateFinalize(dcFed)
    h.helicsFederateFinalizeComplete(sFed)
    h.helicsFederateFinalizeComplete(dFed)
    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)
Ejemplo n.º 20
0
def test_filter_callback_test():

    broker = createBroker(2)

    assert """helics.HelicsBroker(identifier = "mainbroker", address = "tcp://127.0.0.1:23404")""" in repr(
        broker)

    fFed, fedinfo1 = createMessageFederate(1, "filter", 1.0)
    mFed, fedinfo2 = createMessageFederate(1, "message", 1.0)

    h.helicsFederateSetFlagOption(mFed,
                                  h.HELICS_FLAG_IGNORE_TIME_MISMATCH_WARNINGS,
                                  True)

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    assert (
        """helics.HelicsEndpoint(name = "port1", type = "", info = "", is_valid = True, default_destination = "", n_pending_messages = 0)"""
        in repr(p1))
    assert (
        """helics.HelicsEndpoint(name = "port2", type = "", info = "", is_valid = True, default_destination = "", n_pending_messages = 0)"""
        in repr(p2))

    f1 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_CUSTOM,
                                        "filter1")
    f2 = h.helicsFederateRegisterFilter(mFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "dfilter")

    h.helicsFilterAddSourceTarget(f1, "port1")

    assert 'name = "Testfilter/filter1"' in repr(f1)

    userdata = UserData(5)

    handle = h.ffi.new_handle(userdata)
    h.helicsFilterSetCustomCallback(f1, filterFunc1, handle)

    with pt.raises(h.HelicsException):
        h.helicsFilterSetCustomCallback(f2, filterFunc1, handle)

    assert (
        """helics.HelicsMessageFederate(name = "Testfilter", state = HelicsFederateState.STARTUP, current_time = -9223372036.854776, n_publications = 0, n_subscriptions = 0, n_endpoints = 0, n_filters = 1, n_pending_messages = 0)"""
        in repr(fFed))
    assert (
        """helics.HelicsMessageFederate(name = "Testmessage", state = HelicsFederateState.STARTUP, current_time = -9223372036.854776, n_publications = 0, n_subscriptions = 0, n_endpoints = 2, n_filters = 1, n_pending_messages = 0)"""
        in repr(mFed))

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    assert (
        """helics.HelicsMessageFederate(name = "Testfilter", state = HelicsFederateState.EXECUTION, current_time = 0.0, n_publications = 0, n_subscriptions = 0, n_endpoints = 0, n_filters = 1, n_pending_messages = 0)"""
        in repr(fFed))
    assert (
        """helics.HelicsMessageFederate(name = "Testmessage", state = HelicsFederateState.EXECUTION, current_time = 0.0, n_publications = 0, n_subscriptions = 0, n_endpoints = 2, n_filters = 1, n_pending_messages = 0)"""
        in repr(mFed))

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION
    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsFederateHasMessage(mFed) is False

    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False

    h.helicsFederateRequestTimeAsync(fFed, 3.0)
    h.helicsFederateRequestTime(mFed, 3.0)

    assert h.helicsEndpointHasMessage(p2)

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    h.helicsFederateRequestTime(mFed, 3.0)
    h.helicsFederateRequestTimeComplete(fFed)
    h.helicsFederateFinalizeAsync(mFed)
    h.helicsFederateFinalize(fFed)
    h.helicsFederateFinalizeComplete(mFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(fFed, fedinfo1)
    destroyFederate(mFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 21
0
def test_filter_test_types_message_filter_function3():

    broker = createBroker(2)
    fFed, fedinfo1 = createMessageFederate(1, "filter", 1)
    mFed, fedinfo2 = createMessageFederate(1, "message", 1)

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "random")

    f1 = h.helicsFederateRegisterGlobalFilter(fFed,
                                              h.HELICS_FILTER_TYPE_CUSTOM,
                                              "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    f2 = h.helicsFederateRegisterGlobalFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                              "filter2")
    h.helicsFilterAddSourceTarget(f2, "port1")

    h.helicsFederateRegisterEndpoint(fFed, "fout", "")
    f3 = h.helicsFederateRegisterFilter(fFed,
                                        h.HELICS_FILTER_TYPE_RANDOM_DELAY,
                                        "filter3")
    h.helicsFilterAddSourceTarget(f3, "filter0/fout")

    h.helicsFilterSet(f2, "delay", 2.5)

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION

    data = "hello world".encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsFederateHasMessage(mFed) is False

    h.helicsEndpointSendMessageRaw(p2, "port1", data)
    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False
    # there may be something wrong here yet but this test isn't the one to find it and
    # this may prevent spurious errors for now.
    # std::this_thread::yield()
    h.helicsFederateRequestTimeAsync(mFed, 3.0)
    h.helicsFederateRequestTime(fFed, 3.0)
    h.helicsFederateRequestTimeComplete(mFed)

    assert h.helicsEndpointHasMessage(p2)

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    assert h.helicsEndpointHasMessage(p1) is True
    h.helicsFederateFinalize(mFed)
    h.helicsFederateFinalize(fFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(mFed, fedinfo1)
    destroyFederate(fFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 22
0
def test_filter_test_types_clone_test():

    broker = createBroker(3)
    sFed, fedinfo1 = createMessageFederate(1, "source", 1)
    dFed, fedinfo2 = createMessageFederate(1, "dest", 1)
    dcFed, fedinfo3 = createMessageFederate(1, "dest_clone", 1)

    p1 = h.helicsFederateRegisterGlobalEndpoint(sFed, "src", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(dFed, "dest", "")
    p3 = h.helicsFederateRegisterGlobalEndpoint(dcFed, "cm", "")

    f1 = h.helicsFederateRegisterCloningFilter(dcFed, "")
    h.helicsFilterAddDeliveryEndpoint(f1, "cm")
    h.helicsFilterAddSourceTarget(f1, "src")

    h.helicsFederateEnterExecutingModeAsync(sFed)
    h.helicsFederateEnterExecutingModeAsync(dcFed)
    h.helicsFederateEnterExecutingMode(dFed)
    h.helicsFederateEnterExecutingModeComplete(sFed)
    h.helicsFederateEnterExecutingModeComplete(dcFed)

    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_EXECUTION
    state = h.helicsFederateGetState(dcFed)
    assert state == h.HELICS_STATE_EXECUTION
    state = h.helicsFederateGetState(dFed)
    assert state == h.HELICS_STATE_EXECUTION

    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "dest", data)

    h.helicsFederateRequestTimeAsync(sFed, 1.0)
    h.helicsFederateRequestTimeAsync(dcFed, 1.0)
    h.helicsFederateRequestTime(dFed, 1.0)
    h.helicsFederateRequestTimeComplete(sFed)
    h.helicsFederateRequestTimeComplete(dcFed)

    assert h.helicsFederateHasMessage(dFed)

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    assert h.helicsFederateHasMessage(dcFed)

    m2 = h.helicsEndpointGetMessage(p3)
    assert h.helicsMessageGetSource(m2) == "src"
    assert h.helicsMessageGetOriginalSource(m2) == "src"
    assert h.helicsMessageGetDestination(m2) == "cm"
    assert h.helicsMessageGetOriginalDestination(m2) == "dest"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)

    h.helicsFederateFinalizeAsync(sFed)
    h.helicsFederateFinalizeAsync(dFed)
    h.helicsFederateFinalize(dcFed)
    h.helicsFederateFinalizeComplete(sFed)
    h.helicsFederateFinalizeComplete(dFed)
    state = h.helicsFederateGetState(sFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(sFed, fedinfo1)
    destroyFederate(dFed, fedinfo2)
    destroyFederate(dcFed, fedinfo3)
    destroyBroker(broker)
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
def test_filter_test_types_function2():

    broker = createBroker(2)
    fFed, fedinfo1 = createMessageFederate(1, "filter")
    mFed, fedinfo2 = createMessageFederate(1, "message")

    p1 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port1", "")
    p2 = h.helicsFederateRegisterGlobalEndpoint(mFed, "port2", "")

    f1 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "filter1")
    h.helicsFilterAddSourceTarget(f1, "port1")
    h.helicsFilterSet(f1, "delay", 2.5)

    f2 = h.helicsFederateRegisterFilter(fFed, h.HELICS_FILTER_TYPE_DELAY,
                                        "filter2")
    h.helicsFilterAddSourceTarget(f2, "port2")
    h.helicsFilterSet(f2, "delay", 2.5)
    # this is expected to fail since a regular filter doesn't have a delivery endpoint
    # @test_throws h.HELICSErrorInvalidObject h.helicsFilterAddDeliveryEndpoint(f2, "port1")

    h.helicsFederateEnterExecutingModeAsync(fFed)
    h.helicsFederateEnterExecutingMode(mFed)
    h.helicsFederateEnterExecutingModeComplete(fFed)

    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_EXECUTION

    data = "".join(["a" for _ in range(0, 500)]).encode()
    h.helicsEndpointSendMessageRaw(p1, "port2", data)

    h.helicsFederateRequestTimeAsync(mFed, 1.0)
    h.helicsFederateRequestTime(fFed, 1.0)
    h.helicsFederateRequestTimeComplete(mFed)

    res = h.helicsFederateHasMessage(mFed)
    assert res is False

    h.helicsEndpointSendMessageRaw(p2, "port1", data)
    h.helicsFederateRequestTimeAsync(mFed, 2.0)
    h.helicsFederateRequestTime(fFed, 2.0)
    h.helicsFederateRequestTimeComplete(mFed)
    assert h.helicsEndpointHasMessage(p2) is False
    # there may be something wrong here yet but this test isn't the one to find it and
    # this may prevent spurious errors for now.
    # std::this_thread::yield()
    h.helicsFederateRequestTime(mFed, 3.0)

    assert h.helicsEndpointHasMessage(p2) is True

    m2 = h.helicsEndpointGetMessage(p2)
    assert h.helicsMessageGetSource(m2) == "port1"
    assert h.helicsMessageGetOriginalSource(m2) == "port1"
    assert h.helicsMessageGetDestination(m2) == "port2"
    assert h.helicsMessageGetRawDataSize(m2) == len(data)
    assert h.helicsMessageGetTime(m2) == 2.5

    assert h.helicsEndpointHasMessage(p1) is False

    h.helicsFederateRequestTime(mFed, 4.0)
    assert h.helicsEndpointHasMessage(p1) is True
    h.helicsFederateFinalizeAsync(mFed)
    h.helicsFederateFinalize(fFed)
    h.helicsFederateFinalizeComplete(mFed)
    state = h.helicsFederateGetState(fFed)
    assert state == h.HELICS_STATE_FINALIZE

    destroyFederate(fFed, fedinfo1)
    destroyFederate(mFed, fedinfo2)
    destroyBroker(broker)
Ejemplo n.º 25
0
def run_cosim(fed, endid):

    # The event queue ("eq") is the master list of events that the filter
    #   federates works on. In this simple filter federate, each event
    #   will be a dictionary with a few parameters:
    #       'dest' - destination of message
    #       'time' - time when the message should be sent on to its
    #               intended destination
    #       'payload' - content of the message being sent
    #
    #   When eq is empty, there are no messages being
    #   filtered by the federate. When there are events in the queue it
    #   indicates the filter federate has messages it is holding onto
    #   that it needs to forward on (at the indicated time).
    #
    eq = []

    h.helicsFederateEnterExecutingMode(fed)
    logger.info('Entered HELICS execution mode')

    hours = 24 * 7  # one week
    total_interval = int(60 * 60 * hours)

    # Blocking call for a time request at max simulation time
    fake_max_time = int(h.HELICS_TIME_MAXTIME / 1000)
    starttime = fake_max_time
    logger.debug(f'Requesting initial time {starttime}')
    grantedtime = h.helicsFederateRequestTime(fed, starttime)
    logger.debug(f'Granted time {grantedtime}')

    while grantedtime < total_interval:
        # In HELICS, when multiple messages arrive at an endpoint they
        # queue up and are popped off one-by-one with the
        #   "helicsEndpointHasMessage" API call. When that API doesn't
        #   return a message, you've processed them all.
        while h.helicsEndpointHasMessage(endid):
            msg = h.helicsEndpointGetMessage(endid)
            msg_str = h.helicsMessageGetString(msg)
            source = h.helicsMessageGetOriginalSource(msg)
            dest = h.helicsMessageGetOriginalDestination(msg)
            time = h.helicsMessageGetTime(msg)
            logger.debug(f'Received message from endpoint {source}'
                         f' to endpoint {dest}'
                         f' at time {grantedtime}'
                         f' with message {msg_str}')
            event = {
                "payload": msg_str,
                "source": source,
                "dest": dest,
                "time": time
            }
            eq = filter_message(eq, event, 'delay')
            if source == 'EVController_federate/endpoint':
                eq = filter_message(eq, event, 'hack')

        # Sort event queue to get it back in order
        eq = sorted(eq, key=itemgetter('time'))

        # Acting on any events that need to be dequeued
        # Running interference filter. This filter has the ability to
        #   remove events from eq. We may not have any messages to send
        #   after interference runs
        event = eq[0]
        eq = filter_message(eq, event, 'interfere')

        # After filtering, send all messages whose time has come (or past;
        #   in which case something has gone wrong)
        while eq and eq[0]['time'] <= grantedtime:
            h.helicsEndpointSendMessageRaw(endid, eq[0]['dest'],
                                           eq[0]['payload'].encode())
            logger.debug(f'Sent message from endpoint {endid}'
                         f' to endpoint {eq[0]["dest"]}'
                         f' at time {grantedtime}'
                         f' with message {eq[0]["payload"]}')
            del eq[0]

        if eq:
            # Event queue not empty, need to schedule filter federate to
            #   run again when its time to deliver the next message in the
            #   queue
            requested_time = eq[0]['time']
        else:
            # If no events in queue, schedule run for end of simulation.
            #   Filter federate will be granted an earlier time if a
            #   message is rerouted to the filter federate.
            requested_time = fake_max_time
        logger.debug(f'Requesting time {requested_time}')
        grantedtime = h.helicsFederateRequestTime(fed, requested_time)
        logger.debug(f'Granted time {grantedtime}')
Ejemplo n.º 26
0
def run_cosim(fed, endid, end_name, args):
    # The event queue ("eq") is the master list of events that the filter
    #   federates works on. In this simple filter federate, each event
    #   will be a dictionary with a few parameters:
    #       'dest' - destination of message
    #       'time' - time when the message should be sent on to its
    #               intended destination
    #       'payload' - content of the message being sent
    #
    #   When eq is empty, there are no messages being
    #   filtered by the federate. When there are events in the queue it
    #   indicates the filter federate has messages it is holding onto
    #   that it needs to forward on (at the indicated time).
    #
    eq = []

    # sub = h.helicsFederateRegisterSubscription(fed, "Charger/EV1_voltage", "")

    logger.info('Attempting to enter execution mode')
    h.helicsFederateEnterExecutingMode(fed)
    logger.info('Entered HELICS execution mode')

    hours = 24 * 7  # one week
    total_interval = int(60 * 60 * hours)

    # Blocking call for a time request at max simulation time
    # fake_max_time = int(h.HELICS_TIME_MAXTIME / 1000)
    fake_max_time = 100000000
    starttime = fake_max_time
    #starttime = 0
    logger.debug(f'Requesting initial time {starttime}')
    grantedtime = h.helicsFederateRequestTime(fed, starttime)
    logger.debug(f'Granted time {grantedtime}')

    while grantedtime < total_interval:

        # value = h.helicsInputGetString(sub)
        # logger.debug(f'Got message {value} from random sub at time {grantedtime}.')

        # In HELICS, when multiple messages arrive at an endpoint they
        # queue up and are popped off one-by-one with the
        #   "helicsEndpointHasMessage" API call. When that API doesn't
        #   return a message, you've processed them all.
        while h.helicsEndpointHasMessage(endid):
            msg = h.helicsEndpointGetMessage(endid)
#             msg_str = h.helicsMessageGetString(msg)
#             source = h.helicsMessageGetOriginalSource(msg)
            dest = h.helicsMessageGetOriginalDestination(msg)
#             time = h.helicsMessageGetTime(msg)
#             logger.debug(f'Received message from endpoint {source}'
#                          f' to endpoint {dest}'
#                          f' for delivery at time {time}'
#                          f' with payload \"{msg_str}\"')
            h.helicsMessageSetDestination(msg, dest)
            h.helicsEndpointSendMessage(endid, msg)
#             logger.debug(f'Sent message from endpoint {end_name}'
#                              f' appearing to come from {source}'
#                              f' to endpoint {dest}'
#                              f' at time {grantedtime}'
#                              f' with payload \"{msg_str}\"')
        logger.debug(f'Requesting time {fake_max_time}\n')
        grantedtime = h.helicsFederateRequestTime(fed, fake_max_time)
        logger.debug(f'Granted time {grantedtime}')
Ejemplo n.º 27
0
def test_misc_api():
    fedInfo1 = h.helicsCreateFederateInfo()
    h.helicsFederateInfoSetCoreInitString(fedInfo1, "-f 1")
    h.helicsFederateInfoSetCoreName(fedInfo1, "core3")
    h.helicsFederateInfoSetCoreType(fedInfo1, 3)
    h.helicsFederateInfoSetCoreTypeFromString(fedInfo1, "zmq")
    h.helicsFederateInfoSetFlagOption(fedInfo1, 1, True)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_INPUT_DELAY,
                                        1.0)
    h.helicsFederateInfoSetIntegerProperty(fedInfo1,
                                           h.HELICS_PROPERTY_INT_LOG_LEVEL, 1)
    h.helicsFederateInfoSetIntegerProperty(
        fedInfo1, h.HELICS_PROPERTY_INT_MAX_ITERATIONS, 100)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_OUTPUT_DELAY,
                                        1.0)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_PERIOD, 1.0)
    h.helicsFederateInfoSetTimeProperty(fedInfo1, h.HELICS_PROPERTY_TIME_DELTA,
                                        1.0)
    h.helicsFederateInfoSetTimeProperty(fedInfo1,
                                        h.HELICS_PROPERTY_TIME_OFFSET, 0.1)
    h.helicsFederateInfoFree(fedInfo1)

    broker3 = h.helicsCreateBroker("zmq", "broker3",
                                   "--federates 1 --loglevel 1")
    fedInfo2 = h.helicsCreateFederateInfo()
    coreInitString = "--federates 1"
    h.helicsFederateInfoSetCoreInitString(fedInfo2, coreInitString)
    h.helicsFederateInfoSetCoreTypeFromString(fedInfo2, "zmq")
    h.helicsFederateInfoSetIntegerProperty(fedInfo2,
                                           h.HELICS_PROPERTY_INT_LOG_LEVEL, 1)
    h.helicsFederateInfoSetTimeProperty(fedInfo2, h.HELICS_PROPERTY_TIME_DELTA,
                                        1.0)
    fed1 = h.helicsCreateCombinationFederate("fed1", fedInfo2)
    fed2 = h.helicsFederateClone(fed1)
    _ = h.helicsGetFederateByName("fed1")
    h.helicsFederateSetFlagOption(fed2, 1, False)

    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_INPUT_DELAY,
                                    1.0)
    h.helicsFederateSetIntegerProperty(fed1, h.HELICS_PROPERTY_INT_LOG_LEVEL,
                                       1)
    h.helicsFederateSetIntegerProperty(fed2,
                                       h.HELICS_PROPERTY_INT_MAX_ITERATIONS,
                                       100)
    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_OUTPUT_DELAY,
                                    1.0)
    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_PERIOD, 0.0)
    h.helicsFederateSetTimeProperty(fed2, h.HELICS_PROPERTY_TIME_DELTA, 1.0)

    _ = h.helicsFederateRegisterCloningFilter(fed1, "fed1/Ep1")
    fed1DestinationFilter = h.helicsFederateRegisterFilter(
        fed1, h.HELICS_FILTER_TYPE_DELAY, "fed1DestinationFilter")
    h.helicsFilterAddDestinationTarget(fed1DestinationFilter, "Ep2")

    ep1 = h.helicsFederateRegisterEndpoint(fed1, "Ep1", "string")
    ep2 = h.helicsFederateRegisterGlobalEndpoint(fed1, "Ep2", "string")
    pub1 = h.helicsFederateRegisterGlobalPublication(fed1, "pub1",
                                                     h.HELICS_DATA_TYPE_DOUBLE,
                                                     "")
    pub2 = h.helicsFederateRegisterGlobalTypePublication(
        fed1, "pub2", "complex", "")

    sub1 = h.helicsFederateRegisterSubscription(fed1, "pub1")
    sub2 = h.helicsFederateRegisterSubscription(fed1, "pub2")
    h.helicsInputAddTarget(sub2, "Ep2")
    pub3 = h.helicsFederateRegisterPublication(fed1, "pub3",
                                               h.HELICS_DATA_TYPE_STRING, "")

    pub1KeyString = h.helicsPublicationGetKey(pub1)
    pub1TypeString = h.helicsPublicationGetType(pub1)
    pub1UnitsString = h.helicsPublicationGetUnits(pub1)
    sub1KeyString = h.helicsSubscriptionGetKey(sub1)
    sub1UnitsString = h.helicsInputGetUnits(sub1)
    assert "pub1" == pub1KeyString
    assert "double" == pub1TypeString
    assert "" == pub1UnitsString
    assert "pub1" == sub1KeyString
    assert "" == sub1UnitsString

    fed1SourceFilter = h.helicsFederateRegisterFilter(
        fed1, h.HELICS_FILTER_TYPE_DELAY, "fed1SourceFilter")
    h.helicsFilterAddSourceTarget(fed1SourceFilter, "Ep2")
    h.helicsFilterAddDestinationTarget(fed1SourceFilter, "fed1/Ep1")
    h.helicsFilterRemoveTarget(fed1SourceFilter, "fed1/Ep1")
    h.helicsFilterAddSourceTarget(fed1SourceFilter, "Ep2")
    h.helicsFilterRemoveTarget(fed1SourceFilter, "Ep2")

    fed1SourceFilterNameString = h.helicsFilterGetName(fed1SourceFilter)
    assert fed1SourceFilterNameString == "fed1/fed1SourceFilter"

    sub3 = h.helicsFederateRegisterSubscription(fed1, "fed1/pub3", "")
    pub4 = h.helicsFederateRegisterTypePublication(fed1, "pub4", "int", "")

    sub4 = h.helicsFederateRegisterSubscription(fed1, "fed1/pub4", "")
    pub5 = h.helicsFederateRegisterGlobalTypePublication(
        fed1, "pub5", "boolean", "")

    sub5 = h.helicsFederateRegisterSubscription(fed1, "pub5", "")
    pub6 = h.helicsFederateRegisterGlobalPublication(fed1, "pub6",
                                                     h.HELICS_DATA_TYPE_VECTOR,
                                                     "")
    sub6 = h.helicsFederateRegisterSubscription(fed1, "pub6", "")
    pub7 = h.helicsFederateRegisterGlobalPublication(
        fed1, "pub7", h.HELICS_DATA_TYPE_NAMED_POINT, "")
    sub7 = h.helicsFederateRegisterSubscription(fed1, "pub7", "")

    assert """helics.HelicsPublication(name = "pub1", type = "double", units = "", info = "")""" in repr(
        pub1)
    assert """helics.HelicsPublication(name = "pub2", type = "complex", units = "", info = "")""" in repr(
        pub2)
    assert """helics.HelicsPublication(name = "fed1/pub3", type = "string", units = "", info = "")""" in repr(
        pub3)
    assert """helics.HelicsPublication(name = "fed1/pub4", type = "int", units = "", info = "")""" in repr(
        pub4)
    assert """helics.HelicsPublication(name = "pub5", type = "boolean", units = "", info = "")""" in repr(
        pub5)
    assert """helics.HelicsPublication(name = "pub6", type = "double_vector", units = "", info = "")""" in repr(
        pub6)
    assert """helics.HelicsPublication(name = "pub7", type = "named_point", units = "", info = "")""" in repr(
        pub7)
    assert (
        """helics.HelicsInput(name = "_input_18", units = "", injection_units = "", publication_type = "", type = "", target = "pub7", info = "")"""
        in repr(sub7))

    h.helicsInputSetDefaultBoolean(sub5, False)
    h.helicsInputSetDefaultComplex(sub2, -9.9 + 2.5j)
    h.helicsInputSetDefaultDouble(sub1, 3.4)
    h.helicsInputSetDefaultInteger(sub4, 6)
    h.helicsInputSetDefaultNamedPoint(sub7, "hollow", 20.0)
    h.helicsInputSetDefaultString(sub3, "default")
    sub6Default = [3.4, 90.9, 4.5]
    h.helicsInputSetDefaultVector(sub6, sub6Default)
    h.helicsEndpointSubscribe(ep2, "fed1/pub3")
    h.helicsFederateEnterInitializingModeAsync(fed1)
    rs = h.helicsFederateIsAsyncOperationCompleted(fed1)
    if rs == 0:
        time.sleep(0.500)
        rs = h.helicsFederateIsAsyncOperationCompleted(fed1)
        if rs == 0:
            time.sleep(0.500)
            rs = h.helicsFederateIsAsyncOperationCompleted(fed1)
            if rs == 0:
                assert True is False
    h.helicsFederateEnterInitializingModeComplete(fed1)
    h.helicsFederateEnterExecutingModeAsync(fed1)
    h.helicsFederateEnterExecutingModeComplete(fed1)

    assert (
        """helics.HelicsInput(name = "_input_18", units = "", injection_units = "", publication_type = "named_point", type = "", target = "pub7", info = "")"""
        in repr(sub7))

    mesg1 = h.helicsFederateCreateMessage(fed1)
    h.helicsMessageSetString(mesg1, "Hello")
    h.helicsMessageSetSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetOriginalSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetDestination(mesg1, "Ep2")
    h.helicsMessageSetOriginalDestination(mesg1, "Ep2")

    h.helicsEndpointSendMessage(ep1, mesg1)
    mesg1 = h.helicsFederateCreateMessage(fed1)
    h.helicsMessageSetString(mesg1, "There")
    h.helicsMessageSetSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetOriginalSource(mesg1, "fed1/Ep1")
    h.helicsMessageSetDestination(mesg1, "Ep2")
    h.helicsMessageSetOriginalDestination(mesg1, "Ep2")
    h.helicsEndpointSendMessage(ep1, mesg1)
    h.helicsEndpointSetDefaultDestination(ep2, "fed1/Ep1")

    ep1NameString = h.helicsEndpointGetName(ep1)
    ep1TypeString = h.helicsEndpointGetType(ep1)

    assert ep1NameString == "fed1/Ep1"
    assert ep1TypeString == "string"

    _ = h.helicsFederateGetCoreObject(fed1)

    fed1Time = h.helicsFederateGetCurrentTime(fed1)
    assert fed1Time == 0.0
    fed1EndpointCount = h.helicsFederateGetEndpointCount(fed1)
    assert fed1EndpointCount == 2

    fed1NameString = h.helicsFederateGetName(fed1)
    assert fed1NameString == "fed1"

    fed1State = h.helicsFederateGetState(fed1)
    assert fed1State == 2
    fed1PubCount = h.helicsFederateGetPublicationCount(fed1)
    assert fed1PubCount == 7
    fed1SubCount = h.helicsFederateGetInputCount(fed1)
    assert fed1SubCount == 7

    h.helicsPublicationPublishBoolean(pub5, True)
    h.helicsPublicationPublishComplex(pub2, 5.6 + -0.67j)
    h.helicsPublicationPublishDouble(pub1, 457.234)
    h.helicsPublicationPublishInteger(pub4, 1)
    h.helicsPublicationPublishNamedPoint(pub7, "Blah Blah", 20.0)
    h.helicsPublicationPublishString(pub3, "Mayhem")
    pub6Vector = [4.5, 56.5]
    h.helicsPublicationPublishVector(pub6, pub6Vector)
    time.sleep(0.500)
    h.helicsFederateRequestTimeAsync(fed1, 1.0)

    returnTime = h.helicsFederateRequestTimeComplete(fed1)
    assert returnTime == 1.0
    ep2MsgCount = h.helicsEndpointPendingMessages(ep2)
    assert ep2MsgCount == 2
    ep2HasMsg = h.helicsEndpointHasMessage(ep2)
    assert ep2HasMsg == 1

    msg2 = h.helicsEndpointGetMessage(ep2)
    assert h.helicsMessageGetTime(msg2) == 1.0
    assert h.helicsMessageGetString(msg2) == "Hello"
    assert h.helicsMessageGetOriginalSource(msg2) == "fed1/Ep1"
    assert h.helicsMessageGetSource(msg2) == "fed1/Ep1"
    assert h.helicsMessageGetDestination(msg2) == "Ep2"
    assert h.helicsMessageGetOriginalDestination(msg2) == "Ep2"

    fed1MsgCount = h.helicsFederatePendingMessages(fed1)
    assert fed1MsgCount == 1

    assert h.helicsFederateHasMessage(fed1) == 1

    msg3 = h.helicsFederateGetMessage(fed1)
    assert h.helicsMessageGetTime(msg3) == 1.0
    assert h.helicsMessageGetString(msg3) == "There"
    assert h.helicsMessageGetOriginalSource(msg3) == "fed1/Ep1"
    assert h.helicsMessageGetSource(msg3) == "fed1/Ep1"
    assert h.helicsMessageGetDestination(msg3) == "Ep2"
    assert h.helicsMessageGetOriginalDestination(msg3) == "Ep2"

    sub1Updated = h.helicsInputIsUpdated(sub1)
    # TODO: figure out why this test is broken
    assert sub1Updated is False

    # TODO: figure out why this test is broken
    assert h.helicsInputLastUpdateTime(sub2) == 0.0

    # assert h.helicsInputGetComplex(sub2) == 5.6 - 0.67j

    # assert h.helicsInputGetDouble(sub1) == 457.234
    # assert h.helicsInputGetInteger(sub4) == 1
    sub7PointString, sub7DoubleValue = h.helicsInputGetNamedPoint(sub7)
    # assert sub7PointString == "Blah Blah"
    assert sub7DoubleValue == 20.0
    # assert h.helicsInputGetBoolean(sub5) == True
    # assert h.helicsInputGetString(sub3) == "Mayhem"

    sub3ValueSize = h.helicsInputGetRawValueSize(sub3)
    # assert sub3ValueSize == 6

    # assert h.helicsInputGetVector(sub6) == [4.5, 56.5]

    h.helicsFederateFinalize(fed1)
    h.helicsFederateFinalize(fed2)
    h.helicsFederateFree(fed1)
    h.helicsFederateFinalize(fed2)
    h.helicsFederateFree(fed2)
    h.helicsFederateInfoFree(fedInfo2)
    h.helicsBrokerDisconnect(broker3)

    h.helicsBrokerFree(broker3)

    h.helicsCleanupLibrary()
    h.helicsCloseLibrary()
Ejemplo n.º 28
0

fed = h.helicsCreateCombinationFederateFromConfig("sender.json")

my_epid = h.helicsFederateGetEndpoint(fed, "data")


h.helicsFederateEnterExecutingMode(fed)

current_time = 0

for i in range(1,11):
	while(current_time < i+1):
		current_time = h.helicsFederateRequestTime(fed, i)
		print("current time : ", current_time)
		if(current_time == i + 0.2):
			h.helicsEndpointSendMessageRaw(my_epid, "receiver/data", str(0.5))
		time.sleep(0.5)
		
		if(h.helicsEndpointHasMessage(my_epid)):
			message = h.helicsEndpointGetMessage(my_epid)
			print("Received message back", message.data, "at time", message.time)

h.helicsFederateFinalize(fed)

while h.helicsBrokerIsConnected(broker):
    time.sleep(1)

h.helicsFederateFree(fed)
h.helicsCloseLibrary()
Ejemplo n.º 29
0
def run_cosim(fed, endid, end_name, args):
    # The event queue ("eq") is the master list of events that the filter
    #   federates works on. In this simple filter federate, each event
    #   will be a dictionary with a few parameters:
    #       'dest' - destination of message
    #       'time' - time when the message should be sent on to its
    #               intended destination
    #       'payload' - content of the message being sent
    #
    #   When eq is empty, there are no messages being
    #   filtered by the federate. When there are events in the queue it
    #   indicates the filter federate has messages it is holding onto
    #   that it needs to forward on (at the indicated time).
    #
    eq = []

    # sub = h.helicsFederateRegisterSubscription(fed, "Charger/EV1_voltage", "")

    logger.info('Attempting to enter execution mode')
    h.helicsFederateEnterExecutingMode(fed)
    logger.info('Entered HELICS execution mode')

    hours = 24 * 7  # one week
    total_interval = int(60 * 60 * hours)

    # Blocking call for a time request at max simulation time
    # fake_max_time = int(h.HELICS_TIME_MAXTIME / 1000)
    fake_max_time = 100000000
    starttime = fake_max_time
    #starttime = 0
    logger.debug(f'Requesting initial time {starttime}')
    grantedtime = h.helicsFederateRequestTime(fed, starttime)
    logger.debug(f'Granted time {grantedtime}')

    while grantedtime < total_interval:

        # value = h.helicsInputGetString(sub)
        # logger.debug(f'Got message {value} from random sub at time {grantedtime}.')

        # In HELICS, when multiple messages arrive at an endpoint they
        # queue up and are popped off one-by-one with the
        #   "helicsEndpointHasMessage" API call. When that API doesn't
        #   return a message, you've processed them all.
        while h.helicsEndpointHasMessage(endid):
            msg = h.helicsEndpointGetMessage(endid)
            msg_str = h.helicsMessageGetString(msg)
            source = h.helicsMessageGetOriginalSource(msg)
            dest = h.helicsMessageGetOriginalDestination(msg)
            time = h.helicsMessageGetTime(msg)
            logger.debug(f'Received message from endpoint {source}'
                         f' to endpoint {dest}'
                         f' for delivery at time {time}'
                         f' with payload \"{msg_str}\"')
            msg_dict = {
                'msg_obj': msg,
                'payload': msg_str,
                'source': source,
                'dest': dest,
                'time': time
            }
            # Adding messagge to end of eq as a reserved place for all
            # filters to act on.
            eq.append(msg_dict)
            eq = filter_message(eq, 'drop_delay', args)
            if source == 'Controller/ep':
                eq = filter_message(eq, 'hack', args)

        # Sort event queue to get it back in order
        eq = sorted(eq, key=itemgetter('time'))

        # Acting on any events that need to be dequeued
        # Running interference filter. This filter has the ability to
        #   remove events from eq. We may not have any messages to send
        #   after interference runs. eq must be freshly sorted for this
        #   filter to work.
        if len(eq) > 0:
            eq = filter_message(eq, 'interfere', args)

            # After filtering, send all messages whose time has come (or past;
            #   in which case something has gone wrong)
            while eq and eq[0]['time'] <= grantedtime:
                # Change destination to original destination before sending
                #   If you don't do this is sends the message back to the rerouted
                #   destination which, in this case, is the filter endpoint.
                h.helicsMessageSetDestination(eq[0]['msg_obj'], eq[0]["dest"])
                h.helicsEndpointSendMessage(endid, eq[0]['msg_obj'])
                #                 h.helicsEndpointSendMessageRaw(endid, eq[0]['dest'],
                #                                                eq[0]['payload'].encode())
                #                logger.debug(eq[0]['msg_obj'])
                logger.debug(f'Sent message from endpoint {end_name}'
                             f' appearing to come from {eq[0]["source"]}'
                             f' to endpoint {eq[0]["dest"]}'
                             f' at time {grantedtime}'
                             f' with payload \"{eq[0]["payload"]}\"')
                del eq[0]

            if eq:
                # Event queue not empty, need to schedule filter federate to
                #   run again when its time to deliver the next message in the
                #   queue
                requested_time = eq[0]['time']
            else:
                # Reachable if interference has removed all the messages
                #   from the event queue.
                # No events in queue, schedule run for end of simulation.
                #   Filter federate will be granted an earlier time if a
                #   message is rerouted to the filter federate.
                requested_time = fake_max_time
                #requested_time = grantedtime + 5

        else:
            requested_time = fake_max_time
            #requested_time = grantedtime + 5
        logger.debug(f'Requesting time {requested_time}\n')
        grantedtime = h.helicsFederateRequestTime(fed, requested_time)
        logger.debug(f'Granted time {grantedtime}')