public override void on_liveliness_changed(
     DDS.DataReader reader,
     ref DDS.LivelinessChangedStatus status)
 {
     Console.WriteLine("ReaderListener: on_liveliness_changed()");
     Console.WriteLine("  Alive writers: {0}", status.alive_count);
 }
예제 #2
0
 public override void on_liveliness_changed(
     DDS.DataReader reader,
     ref DDS.LivelinessChangedStatus status)
 {
 }
 public override void on_liveliness_changed(
     DDS.DataReader reader,
     ref DDS.LivelinessChangedStatus status)
 {
     Console.WriteLine("ParticipantListener: on_liveliness_changed()\n");
 }
    static void subscribe(int domain_id, int sample_count)
    {
        // --- Create participant --- //

        /* To customize the participant QoS, use
         * the configuration file USER_QOS_PROFILES.xml */
        DDS.DomainParticipant participant =
            DDS.DomainParticipantFactory.get_instance().create_participant(
                domain_id,
                DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT,
                null /* listener */,
                DDS.StatusMask.STATUS_MASK_NONE);
        if (participant == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_participant error");
        }

        // --- Create subscriber --- //

        /* To customize the subscriber QoS, use
         * the configuration file USER_QOS_PROFILES.xml */
        DDS.Subscriber subscriber = participant.create_subscriber(
            DDS.DomainParticipant.SUBSCRIBER_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (subscriber == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_subscriber error");
        }

        // --- Create topic --- //

        /* Register the type before creating the topic */
        System.String type_name = waitsetsTypeSupport.get_type_name();
        try {
            waitsetsTypeSupport.register_type(
                participant, type_name);
        } catch (DDS.Exception e) {
            Console.WriteLine("register_type error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* To customize the topic QoS, use
         * the configuration file USER_QOS_PROFILES.xml */
        DDS.Topic topic = participant.create_topic(
            "Example waitsets",
            type_name,
            DDS.DomainParticipant.TOPIC_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (topic == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_topic error");
        }

        // --- Create reader --- //

        /* To customize the data reader QoS, use
         * the configuration file USER_QOS_PROFILES.xml */
        DDS.DataReader reader = subscriber.create_datareader(
            topic,
            DDS.Subscriber.DATAREADER_QOS_DEFAULT,
            null,
            DDS.StatusMask.STATUS_MASK_ALL);
        if (reader == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_datareader error");
        }

        /* If you want to change the DataReader's QoS programmatically rather
         * than using the XML file, you will need to add the following lines to
         * your code and comment out the create_datareader call above.
         *
         * In this case, we reduce the liveliness timeout period to trigger the
         * StatusCondition DDS.StatusKind.LIVELINESS_CHANGED_STATUS
         */
        /*
         * DDS.DataReaderQos datawriter_qos = new DDS.DataReaderQos();
         * try {
         *  subscriber.get_default_datareader_qos(datawriter_qos);
         * } catch (DDS.Exception e) {
         *  Console.WriteLine("get_default_datareader_qos error {0}", e);
         *  shutdown(participant);
         *  throw e;
         * }
         * datawriter_qos.liveliness.lease_duration.sec = 2;
         * datawriter_qos.liveliness.lease_duration.nanosec = 0;
         *
         * reader = subscriber.create_datareader(topic, datawriter_qos,
         *  null, DDS.StatusMask.STATUS_MASK_NONE);
         * if (reader == null) {
         *  shutdown(participant);
         *  throw new ApplicationException("create_datawriter_qos error");
         * }
         */

        /* Create read condition
         * ---------------------
         * Note that the Read Conditions are dependent on both incoming
         * data as well as sample state. Thus, this method has more
         * overhead than adding a DDS.StatusKind.DATA_AVAILABLE_STATUS
         * StatusCondition. We show it here purely for reference
         */
        DDS.ReadCondition read_condition = reader.create_readcondition(
            DDS.SampleStateKind.NOT_READ_SAMPLE_STATE,
            DDS.ViewStateKind.ANY_VIEW_STATE,
            DDS.InstanceStateKind.ANY_INSTANCE_STATE);
        if (read_condition == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_readcondition error");
        }

        /* Get status conditions
         * ---------------------
         * Each entity may have an attached Status Condition. To modify the
         * statuses we need to get the reader's Status Conditions first.
         */

        DDS.StatusCondition status_condition = reader.get_statuscondition();
        if (status_condition.get_entity() == null)
        {
            shutdown(participant);
            throw new ApplicationException("get_statuscondition error");
        }

        /* Set enabled statuses
         * --------------------
         * Now that we have the Status Condition, we are going to enable the
         * statuses we are interested in:
         * DDS.StatusKind.SUBSCRIPTION_MATCHED_STATUS
         * and DDS.StatusKind.LIVELINESS_CHANGED_STATUS.
         */
        try {
            status_condition.set_enabled_statuses(
                DDS.StatusMask.STATUS_MASK_NONE |
                (DDS.StatusMask)DDS.StatusKind.SUBSCRIPTION_MATCHED_STATUS |
                (DDS.StatusMask)DDS.StatusKind.LIVELINESS_CHANGED_STATUS);
        } catch (DDS.Exception e) {
            Console.WriteLine("set_enabled_statuses error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* Create and attach conditions to the WaitSet
         * -------------------------------------------
         * Finally, we create the WaitSet and attach both the Read Conditions
         * and the Status Condition to it.
         */
        DDS.WaitSet waitset = new DDS.WaitSet();

        /* Attach Read Conditions */
        try {
            waitset.attach_condition(read_condition);
        } catch (DDS.Exception e) {
            Console.WriteLine("attach_read_condition error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* Attach Status Conditions */
        try {
            waitset.attach_condition(status_condition);
        } catch (DDS.Exception e) {
            Console.WriteLine("attach_status_condition error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* Narrow the reader into your specific data type */
        waitsetsDataReader waitsets_reader =
            (waitsetsDataReader)reader;


        /* Main loop */
        for (int count = 0; (sample_count == 0) || (count < sample_count);
             ++count)
        {
            DDS.ConditionSeq active_conditions_seq = new DDS.ConditionSeq();
            DDS.Duration_t   timeout;
            timeout.nanosec = (uint)500000000;
            timeout.sec     = 1;

            /* wait() blocks execution of the thread until one or more attached
             * Conditions become true, or until a user-specified timeout expires
             */
            try {
                waitset.wait(active_conditions_seq, timeout);
            } catch (DDS.Retcode_Timeout) {
                Console.WriteLine("Wait timed out!! No conditions were " +
                                  "triggered.");
                continue;
            } catch (DDS.Exception e) {
                Console.WriteLine("wait error {0}", e);
                break;
            }

            /* Get the number of active conditions */
            int active_conditions = active_conditions_seq.length;
            Console.WriteLine("Got {0} active conditions", active_conditions);

            for (int i = 0; i < active_conditions; i++)
            {
                /* Now we compare the current condition with the Status
                 * Conditions and the Read Conditions previously defined. If
                 * they match, we print the condition that was triggered.*/

                /* Compare with Status Conditions */
                if (active_conditions_seq.get_at(i) == status_condition)
                {
                    /* Get the status changes so we can check which status
                     * condition triggered. */
                    DDS.StatusMask triggeredmask =
                        waitsets_reader.get_status_changes();

                    /* Liveliness changed */
                    DDS.StatusMask test = triggeredmask &
                                          (DDS.StatusMask)DDS.StatusKind.
                                          LIVELINESS_CHANGED_STATUS;
                    if (test != DDS.StatusMask.STATUS_MASK_NONE)
                    {
                        DDS.LivelinessChangedStatus st =
                            new DDS.LivelinessChangedStatus();
                        waitsets_reader.get_liveliness_changed_status(ref st);
                        Console.WriteLine("Liveliness changed => " +
                                          "Active writers = {0}", st.alive_count);
                    }

                    /* Subscription matched */
                    test = triggeredmask &
                           (DDS.StatusMask)DDS.StatusKind.
                           SUBSCRIPTION_MATCHED_STATUS;
                    if (test != DDS.StatusMask.STATUS_MASK_NONE)
                    {
                        DDS.SubscriptionMatchedStatus st =
                            new DDS.SubscriptionMatchedStatus();
                        waitsets_reader.get_subscription_matched_status(ref st);
                        Console.WriteLine("Subscription matched => " +
                                          "Cumulative matches = {0}", st.total_count);
                    }
                }

                /* Compare with Read Conditions */
                else if (active_conditions_seq.get_at(i) == read_condition)
                {
                    /* Current conditions match our conditions to read data, so
                     * we can read data just like we would do in any other
                     * example. */
                    waitsetsSeq       data_seq = new waitsetsSeq();
                    DDS.SampleInfoSeq info_seq = new DDS.SampleInfoSeq();

                    /* You may want to call take_w_condition() or
                     * read_w_condition() on the Data Reader. This way you will
                     * use the same status masks that were set on the Read
                     * Condition.
                     * This is just a suggestion, you can always use
                     * read() or take() like in any other example.
                     */
                    bool follow = true;
                    while (follow)
                    {
                        try {
                            waitsets_reader.take_w_condition(
                                data_seq, info_seq,
                                DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                                read_condition);

                            for (int j = 0; j < data_seq.length; ++j)
                            {
                                if (!info_seq.get_at(j).valid_data)
                                {
                                    Console.WriteLine("Got metadata");
                                    continue;
                                }
                                waitsetsTypeSupport.print_data(
                                    data_seq.get_at(j));
                            }
                        } catch (DDS.Retcode_NoData) {
                            /* When there isn't data, the subscriber stop to
                             * take samples
                             */
                            follow = false;
                        } finally {
                            waitsets_reader.return_loan(data_seq, info_seq);
                        }
                    }
                }
            }
        }

        // --- Shutdown --- //

        /* Delete all entities */
        shutdown(participant);
    }
예제 #5
0
 public virtual void OnLivelinessChanged(IDataReader entityInterface, LivelinessChangedStatus status)
 {
 }
    static void subscribe( int domain_id, int sample_count )
    {
        // --- Create participant --- //

        /* To customize the participant QoS, use
           the configuration file USER_QOS_PROFILES.xml */
        DDS.DomainParticipant participant =
            DDS.DomainParticipantFactory.get_instance().create_participant(
                domain_id,
                DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT,
                null /* listener */,
                DDS.StatusMask.STATUS_MASK_NONE);
        if (participant == null) {
            shutdown(participant);
            throw new ApplicationException("create_participant error");
        }

        // --- Create subscriber --- //

        /* To customize the subscriber QoS, use
           the configuration file USER_QOS_PROFILES.xml */
        DDS.Subscriber subscriber = participant.create_subscriber(
            DDS.DomainParticipant.SUBSCRIBER_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (subscriber == null) {
            shutdown(participant);
            throw new ApplicationException("create_subscriber error");
        }

        // --- Create topic --- //

        /* Register the type before creating the topic */
        System.String type_name = waitsetsTypeSupport.get_type_name();
        try {
            waitsetsTypeSupport.register_type(
                participant, type_name);
        } catch (DDS.Exception e) {
            Console.WriteLine("register_type error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* To customize the topic QoS, use
           the configuration file USER_QOS_PROFILES.xml */
        DDS.Topic topic = participant.create_topic(
            "Example waitsets",
            type_name,
            DDS.DomainParticipant.TOPIC_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (topic == null) {
            shutdown(participant);
            throw new ApplicationException("create_topic error");
        }

        // --- Create reader --- //

        /* To customize the data reader QoS, use
           the configuration file USER_QOS_PROFILES.xml */
        DDS.DataReader reader = subscriber.create_datareader(
            topic,
            DDS.Subscriber.DATAREADER_QOS_DEFAULT,
            null,
            DDS.StatusMask.STATUS_MASK_ALL);
        if (reader == null) {
            shutdown(participant);
            throw new ApplicationException("create_datareader error");
        }

        /* If you want to change the DataReader's QoS programmatically rather
         * than using the XML file, you will need to add the following lines to
         * your code and comment out the create_datareader call above.
         *
         * In this case, we reduce the liveliness timeout period to trigger the
         * StatusCondition DDS.StatusKind.LIVELINESS_CHANGED_STATUS
         */
        /*
        DDS.DataReaderQos datawriter_qos = new DDS.DataReaderQos();
        try {
            subscriber.get_default_datareader_qos(datawriter_qos);
        } catch (DDS.Exception e) {
            Console.WriteLine("get_default_datareader_qos error {0}", e);
            shutdown(participant);
            throw e;
        }
        datawriter_qos.liveliness.lease_duration.sec = 2;
        datawriter_qos.liveliness.lease_duration.nanosec = 0;

        reader = subscriber.create_datareader(topic, datawriter_qos,
            null, DDS.StatusMask.STATUS_MASK_NONE);
        if (reader == null) {
            shutdown(participant);
            throw new ApplicationException("create_datawriter_qos error");
        }
        */

        /* Create read condition
         * ---------------------
         * Note that the Read Conditions are dependent on both incoming
         * data as well as sample state. Thus, this method has more
         * overhead than adding a DDS.StatusKind.DATA_AVAILABLE_STATUS
         * StatusCondition. We show it here purely for reference
         */
        DDS.ReadCondition read_condition = reader.create_readcondition(
            DDS.SampleStateKind.NOT_READ_SAMPLE_STATE,
            DDS.ViewStateKind.ANY_VIEW_STATE,
            DDS.InstanceStateKind.ANY_INSTANCE_STATE);
        if (read_condition == null) {
            shutdown(participant);
            throw new ApplicationException("create_readcondition error");
        }

        /* Get status conditions
         * ---------------------
         * Each entity may have an attached Status Condition. To modify the
         * statuses we need to get the reader's Status Conditions first.
         */

        DDS.StatusCondition status_condition = reader.get_statuscondition();
        if (status_condition.get_entity() == null) {
            shutdown(participant);
            throw new ApplicationException("get_statuscondition error");
        }

        /* Set enabled statuses
         * --------------------
         * Now that we have the Status Condition, we are going to enable the
         * statuses we are interested in:
         * DDS.StatusKind.SUBSCRIPTION_MATCHED_STATUS
         * and DDS.StatusKind.LIVELINESS_CHANGED_STATUS.
         */
        try {
            status_condition.set_enabled_statuses(
                DDS.StatusMask.STATUS_MASK_NONE |
                (DDS.StatusMask)DDS.StatusKind.SUBSCRIPTION_MATCHED_STATUS |
                (DDS.StatusMask)DDS.StatusKind.LIVELINESS_CHANGED_STATUS);
        } catch (DDS.Exception e) {
            Console.WriteLine("set_enabled_statuses error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* Create and attach conditions to the WaitSet
         * -------------------------------------------
         * Finally, we create the WaitSet and attach both the Read Conditions
         * and the Status Condition to it.
         */
        DDS.WaitSet waitset = new DDS.WaitSet();

        /* Attach Read Conditions */
        try {
            waitset.attach_condition(read_condition);
        } catch (DDS.Exception e) {
            Console.WriteLine("attach_read_condition error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* Attach Status Conditions */
        try {
            waitset.attach_condition(status_condition);
        } catch (DDS.Exception e) {
            Console.WriteLine("attach_status_condition error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* Narrow the reader into your specific data type */
        waitsetsDataReader waitsets_reader =
            (waitsetsDataReader)reader;

        /* Main loop */
        for (int count = 0; (sample_count == 0) || (count < sample_count);
                ++count) {
            DDS.ConditionSeq active_conditions_seq = new DDS.ConditionSeq();
            DDS.Duration_t timeout;
            timeout.nanosec = (uint)500000000;
            timeout.sec = 1;

            /* wait() blocks execution of the thread until one or more attached
             * Conditions become true, or until a user-specified timeout expires
             */
            try {
                waitset.wait(active_conditions_seq, timeout);
            } catch (DDS.Retcode_Timeout) {
                Console.WriteLine("Wait timed out!! No conditions were " +
                    "triggered.");
                continue;
            } catch (DDS.Exception e) {
                Console.WriteLine("wait error {0}", e);
                break;
            }

            /* Get the number of active conditions */
            int active_conditions = active_conditions_seq.length;
            Console.WriteLine("Got {0} active conditions", active_conditions);

            for (int i = 0; i < active_conditions; i++) {
                /* Now we compare the current condition with the Status
                 * Conditions and the Read Conditions previously defined. If
                 * they match, we print the condition that was triggered.*/

                /* Compare with Status Conditions */
                if (active_conditions_seq.get_at(i) == status_condition) {
                    /* Get the status changes so we can check which status
                     * condition triggered. */
                    DDS.StatusMask triggeredmask =
                        waitsets_reader.get_status_changes();

                    /* Liveliness changed */
                    DDS.StatusMask test = triggeredmask &
                        (DDS.StatusMask)DDS.StatusKind.
                            LIVELINESS_CHANGED_STATUS;
                    if (test != DDS.StatusMask.STATUS_MASK_NONE) {
                        DDS.LivelinessChangedStatus st =
                            new DDS.LivelinessChangedStatus();
                        waitsets_reader.get_liveliness_changed_status(ref st);
                        Console.WriteLine("Liveliness changed => " +
                            "Active writers = {0}", st.alive_count);
                    }

                    /* Subscription matched */
                    test = triggeredmask &
                        (DDS.StatusMask)DDS.StatusKind.
                            SUBSCRIPTION_MATCHED_STATUS;
                    if (test != DDS.StatusMask.STATUS_MASK_NONE) {
                        DDS.SubscriptionMatchedStatus st =
                            new DDS.SubscriptionMatchedStatus();
                        waitsets_reader.get_subscription_matched_status(ref st);
                        Console.WriteLine("Subscription matched => " +
                            "Cumulative matches = {0}", st.total_count);
                    }
                }

                /* Compare with Read Conditions */
                else if (active_conditions_seq.get_at(i) == read_condition) {
                    /* Current conditions match our conditions to read data, so
                     * we can read data just like we would do in any other
                     * example. */
                    waitsetsSeq data_seq = new waitsetsSeq();
                    DDS.SampleInfoSeq info_seq = new DDS.SampleInfoSeq();

                    /* You may want to call take_w_condition() or
                     * read_w_condition() on the Data Reader. This way you will
                     * use the same status masks that were set on the Read
                     * Condition.
                     * This is just a suggestion, you can always use
                     * read() or take() like in any other example.
                     */
                    try {
                        waitsets_reader.take_w_condition(
                            data_seq, info_seq,
                            DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                            read_condition);
                    } catch (DDS.Exception e) {
                        Console.WriteLine("take error {0}", e);
                        break;
                    }

                    for (int j = 0; j < data_seq.length; ++j) {
                        if (!info_seq.get_at(j).valid_data) {
                            Console.WriteLine("Got metadata");
                            continue;
                        }
                        waitsetsTypeSupport.print_data(data_seq.get_at(i));
                    }
                    waitsets_reader.return_loan(data_seq, info_seq);
                }

            }

        }

        // --- Shutdown --- //

        /* Delete all entities */
        shutdown(participant);
    }
예제 #7
0
 public virtual void OnLivelinessChanged(IDataReader entityInterface, LivelinessChangedStatus status)
 {
 }
예제 #8
0
        static void Main(string[] args)
        {
            DDSEntityManager mgr = new DDSEntityManager("WaitSet");
            String partitionName = "WaitSet example";

            // create Domain Participant
            mgr.createParticipant(partitionName);

            // create Type
            MsgTypeSupport msgTS = new MsgTypeSupport();
            mgr.registerType(msgTS);

            // create Topic
            mgr.createTopic("WaitSetData_Msg");

            // create Subscriber
            mgr.createSubscriber();

            // create DataReader
            mgr.createReader(false);

            // Read Events

            IDataReader dreader = mgr.getReader();
            MsgDataReader WaitSetReader = dreader as MsgDataReader;

            // Create a WaitSet
            WaitSet w = new WaitSet();

            // Create a ReadCondition
            IReadCondition readCond = WaitSetReader.CreateReadCondition(SampleStateKind.NotRead, ViewStateKind.New, InstanceStateKind.Alive);
            ErrorHandler.checkHandle(readCond, "DataReader.CreateReadCondition");

            // Create a QueryCondition
            String[] queryStr = { "Hello again" };
            Console.WriteLine("=== [WaitSetDataSubscriber] Query : message = \"Hello again");
            IQueryCondition queryCond = WaitSetReader.CreateQueryCondition("message=%0", queryStr);
            ErrorHandler.checkHandle(queryCond, "DataReader.CreateQueryCondition");

            // Obtain a StatusCondition
            IStatusCondition statusCond;
            statusCond = dreader.StatusCondition;
            statusCond.SetEnabledStatuses(StatusKind.LivelinessChanged);
            ErrorHandler.checkHandle(statusCond, "DataReader.StatusCondition");

            GuardCondition escape;
            escape = new GuardCondition();

            ReturnCode result;
            result = w.AttachCondition(statusCond);
            ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (status)");
            result = w.AttachCondition(readCond);
            ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (read)");
            result = w.AttachCondition(queryCond);
            ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (query)");
            result = w.AttachCondition(escape);
            ErrorHandler.checkStatus(result, "WaitSet.AttachCondition (guard)");

            /* Initialize and pre-allocate the GuardList used to obtain
               the triggered Conditions. */
            ICondition[] guardList = new ICondition[4];

            DDS.SampleInfo[] infoSeq = null;
            Msg[] msgSeq = null;

            bool escaped = false;
            bool writerLeft = false;
            int prevCount = 0;
            int count = 0;
            Console.WriteLine("=== [WaitSetDataSubscriber] Ready ...");
            while (!escaped && count < 20 )
            {
                /**
                 * Wait until data will be available
                 */
                Duration wait_timeout = new Duration(Duration.InfiniteSec, Duration.InfiniteNanoSec);
                result = w.Wait(ref guardList, wait_timeout);
                ErrorHandler.checkStatus(result, "WaitSet.Wait");

                /* Walk over all guards to display information */
                foreach (ICondition guard in guardList)
                {
                    if (guard == readCond)
                    {
                        result = WaitSetReader.ReadWithCondition(ref msgSeq, ref infoSeq,
                                                                 Length.Unlimited, readCond);
                        ErrorHandler.checkStatus(result, "WaitSetReader.ReadWithCondition");
                        foreach (Msg msg in msgSeq)
                        {
                            Console.WriteLine("   --- New message received ---   ");
                            Console.WriteLine("   userID: {0}", msg.userID);
                            Console.WriteLine("   Message :  \"{0}", msg.message);
                        }
                        result = WaitSetReader.ReturnLoan(ref msgSeq, ref infoSeq);
                        ErrorHandler.checkStatus(result, "WaitSet.ReturnLoan");
                    }
                    else if (guard == queryCond)
                    {
                        result = WaitSetReader.TakeWithCondition(ref msgSeq, ref infoSeq,
                                                                 Length.Unlimited, queryCond);
                        ErrorHandler.checkStatus(result, "WaitSetReader.TakeWithCondition");
                        foreach (Msg msg in msgSeq)
                        {
                            Console.WriteLine("   --- New message received with QueryCondition ---   ");
                            Console.WriteLine("   userID: {0}", msg.userID);
                            Console.WriteLine("   Message : \" {0}", msg.message);
                        }
                        result = WaitSetReader.ReturnLoan(ref msgSeq, ref infoSeq);
                        ErrorHandler.checkStatus(result, "WaitSet.ReturnLoan");
                    }
                    else if (guard == statusCond)
                    {
                        LivelinessChangedStatus livelinessStatus = new LivelinessChangedStatus();
                        result = WaitSetReader.GetLivelinessChangedStatus(ref livelinessStatus);
                        ErrorHandler.checkStatus(result, "DataReader.getLivelinessChangedStatus");
                        if (livelinessStatus.AliveCount < prevCount)
                        {
                            Console.WriteLine("!!! A WaitSetDataWriter lost its liveliness");
                            writerLeft = true;
                            Console.WriteLine("Triggering escape condition.");
                            ReturnCode status = escape.SetTriggerValue(true);
                        }
                        else
                        {
                            Console.WriteLine("!!! A WaitSetDataWriter joined");
                        }
                        prevCount = livelinessStatus.AliveCount;
                    }
                    else if (guard == escape)
                    {
                        Console.WriteLine("WaitSetSubscriber has terminated.");
                        escaped = true;
                        ReturnCode status = escape.SetTriggerValue(false);
                    }
                    else
                    {
                        // Unknown Condition
                    }
                }
                ++count;
            }

            // Detach all Conditions from the WaitSet
            result = w.DetachCondition(escape);
            ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (escape)");
            result = w.DetachCondition(readCond);
            ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (readCond)");
            result = w.DetachCondition(queryCond);
            ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (queryCond)");
            result = w.DetachCondition(statusCond);
            ErrorHandler.checkStatus(result, "WaitSet.DetachCondition (statusCond)");

            Console.WriteLine("=== [Subscriber] Closed");
            // clean up
            WaitSetReader.DeleteReadCondition(readCond);
            WaitSetReader.DeleteReadCondition(queryCond);
            mgr.getSubscriber().DeleteDataReader(WaitSetReader);
            mgr.deleteSubscriber();
            mgr.deleteTopic();
            mgr.deleteParticipant();
        }
예제 #9
0
파일: UserLoad.cs 프로젝트: xrl/opensplice
        static void Main(string[] args)
        {
            string domain = null;

            /* Create a DomainParticipant */
            DomainParticipantFactory dpf = DomainParticipantFactory.Instance;

            IDomainParticipant participant = dpf.CreateParticipant(
                domain,
                null,
                StatusKind.Any);
            ErrorHandler.checkHandle(
                participant, "DDS.DomainParticipantFactory.CreateParticipant");

            /* Register the required datatype for ChatMessage. */
            ChatMessageTypeSupport chatMessageTS = new ChatMessageTypeSupport();
            string chatMessageTypeName = chatMessageTS.TypeName;
            ReturnCode status = chatMessageTS.RegisterType(
                participant, chatMessageTypeName);
            ErrorHandler.checkStatus(
                status, "Chat.ChatMessageTypeSupport.RegisterType");

            /* Register the required datatype for NameService. */
            NameServiceTypeSupport nameServiceTS = new NameServiceTypeSupport();
            ErrorHandler.checkHandle(
                nameServiceTS, "new NameServiceTypeSupport");
            string nameServiceTypeName = nameServiceTS.TypeName;
            status = nameServiceTS.RegisterType(
                participant, nameServiceTypeName);
            ErrorHandler.checkStatus(
                status, "Chat.NameServiceTypeSupport.RegisterType");

            /* Set the ReliabilityQosPolicy to RELIABLE. */
            TopicQos reliableTopicQos = new TopicQos();
            status = participant.GetDefaultTopicQos(ref reliableTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.get_DefaultTopicQos");
            reliableTopicQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;

            /* Make the tailored QoS the new default. */
            status = participant.SetDefaultTopicQos(reliableTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.SetDefaultTopicQos");

            /* Use the changed policy when defining the ChatMessage topic */
            ITopic chatMessageTopic = participant.CreateTopic(
                "Chat_ChatMessage",
                chatMessageTypeName,
                reliableTopicQos);
            ErrorHandler.checkHandle(
                chatMessageTopic,
                "DDS.DomainParticipant.CreateTopic (ChatMessage)");

            /* Set the DurabilityQosPolicy to TRANSIENT. */
            TopicQos settingTopicQos = new TopicQos();
            status = participant.GetDefaultTopicQos(ref settingTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.GetDefaultTopicQos");
            settingTopicQos.Durability.Kind = DurabilityQosPolicyKind.TransientDurabilityQos;

            /* Create the NameService Topic. */
            ITopic nameServiceTopic = participant.CreateTopic(
                "Chat_NameService",
                nameServiceTypeName,
                settingTopicQos);
            ErrorHandler.checkHandle(
                nameServiceTopic, "DDS.DomainParticipant.CreateTopic");

            /* Adapt the default SubscriberQos to read from the
               "ChatRoom" Partition. */
            SubscriberQos subQos = new SubscriberQos();
            status = participant.GetDefaultSubscriberQos(ref subQos);
            ErrorHandler.checkStatus(
                status, "DDS.DomainParticipant.GetDefaultSubscriberQos");
            subQos.Partition.Name = new string[1];
            subQos.Partition.Name[0] = "ChatRoom";

            /* Create a Subscriber for the UserLoad application. */
            ISubscriber chatSubscriber = participant.CreateSubscriber(subQos);
            ErrorHandler.checkHandle(
                chatSubscriber, "DDS.DomainParticipant.CreateSubscriber");

            /* Create a DataReader for the NameService Topic
               (using the appropriate QoS). */
            DataReaderQos nsQos = null;
            status = chatSubscriber.GetDefaultDataReaderQos(ref nsQos);
            ErrorHandler.checkStatus(
                status, "DDS.Subscriber.GetDefaultDataReaderQos");
            status = chatSubscriber.CopyFromTopicQos(ref nsQos, settingTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.Subscriber.CopyFromTopicQos");
            IDataReader parentReader = chatSubscriber.CreateDataReader(
                nameServiceTopic,
                nsQos,
                null,
                StatusKind.Any);
            ErrorHandler.checkHandle(
                parentReader, "DDS.Subscriber.CreateDatareader (NameService)");

            NameServiceDataReader nameServer = parentReader as NameServiceDataReader;

            /* Adapt the DataReaderQos for the ChatMessageDataReader to
               keep track of all messages. */
            DataReaderQos messageQos = new DataReaderQos();
            status = chatSubscriber.GetDefaultDataReaderQos(ref messageQos);
            ErrorHandler.checkStatus(
                status, "DDS.Subscriber.GetDefaultDataReaderQos");
            status = chatSubscriber.CopyFromTopicQos(
                ref messageQos, reliableTopicQos);
            ErrorHandler.checkStatus(
                status, "DDS.Subscriber.CopyFromTopicQos");
            messageQos.History.Kind = HistoryQosPolicyKind.KeepAllHistoryQos;

            /* Create a DataReader for the ChatMessage Topic
               (using the appropriate QoS). */
            parentReader = chatSubscriber.CreateDataReader(
                chatMessageTopic,
                messageQos);
            ErrorHandler.checkHandle(
                parentReader, "DDS.Subscriber.CreateDataReader (ChatMessage)");

            /* Narrow the abstract parent into its typed representative. */
            ChatMessageDataReader loadAdmin = parentReader as ChatMessageDataReader;

            /* Initialize the Query Arguments. */
            string[] parameters = { "0" };

            /* Create a QueryCondition that will contain all messages
               with userID=ownID */
            IQueryCondition singleUser = loadAdmin.CreateQueryCondition("userID=%0", parameters);
            ErrorHandler.checkHandle(singleUser, "DDS.DataReader.CreateQuerycondition");

            /* Create a ReadCondition that will contain new users only */
            IReadCondition newUser = nameServer.CreateReadCondition(SampleStateKind.NotRead, ViewStateKind.New, InstanceStateKind.Alive);
            ErrorHandler.checkHandle(newUser, "DDS.DataReader.create_readcondition");

            /* Obtain a StatusCondition that triggers only when a Writer
               changes Liveliness */
            IStatusCondition leftUser = loadAdmin.StatusCondition;
            ErrorHandler.checkHandle(leftUser, "DDS.DataReader.GetStatusCondition");
            status = leftUser.SetEnabledStatuses(StatusKind.LivelinessChanged);
            ErrorHandler.checkStatus(status, "DDS.StatusCondition.SetEnabledStatuses");

            /* Create a bare guard which will be used to close the room */
            escape = new GuardCondition();

            /* Create a waitset and add the ReadConditions */
            WaitSet userLoadWS = new WaitSet();
            status = userLoadWS.AttachCondition(newUser);
            ErrorHandler.checkStatus(status, "DDS.WaitSet.AttachCondition (newUser)");
            status = userLoadWS.AttachCondition(leftUser);
            ErrorHandler.checkStatus(status, "DDS.WaitSet.AttachCondition (leftUser)");
            status = userLoadWS.AttachCondition(escape);
            ErrorHandler.checkStatus(status, "DDS.WaitSet.AttachCondition (escape)");

            /* Initialize and pre-allocate the GuardList used to obtain
               the triggered Conditions. */
            ICondition[] guardList = new ICondition[3];

            /* Remove all known Users that are not currently active. */
            NameService[] nsMsgs = null;
            SampleInfo[] nsInfos = null;

            status = nameServer.Take(ref nsMsgs,
                ref nsInfos,
                Length.Unlimited,
                SampleStateKind.Any,
                ViewStateKind.Any,
                InstanceStateKind.NotAlive);
            ErrorHandler.checkStatus(
                status, "Chat.NameServiceDataReader.Take");
            status = nameServer.ReturnLoan(ref nsMsgs, ref nsInfos);
            ErrorHandler.checkStatus(
                status, "Chat.NameServiceDataReader.ReturnLoan");

            /* Start the sleeper thread. */
            new Thread(new UserLoad().doWait).Start();

            bool closed = false;

            int prevCount = 0;
            ChatMessage[] msgs = null;
            SampleInfo[] msgInfos = null;

            while (!closed)
            {
                /* Wait until at least one of the Conditions in the
                   waitset triggers. */
                status = userLoadWS.Wait(ref guardList, Duration.Infinite);
                ErrorHandler.checkStatus(status, "DDS.WaitSet.Wait");

                /* Walk over all guards to display information */
                foreach (ICondition guard in guardList)
                {
                    if (guard == newUser)
                    {
                        /* The newUser ReadCondition contains data */
                        status = nameServer.ReadWithCondition(ref nsMsgs, ref nsInfos, newUser);
                        ErrorHandler.checkStatus(status, "Chat.NameServiceDataReader.read_w_condition");

                        foreach (NameService ns in nsMsgs)
                        {
                            Console.WriteLine("New user: "******"Chat.NameServiceDataReader.ReturnLoan");

                    }
                    else if (guard == leftUser)
                    {
                        // Some liveliness has changed (either a DataWriter
                        // joined or a DataWriter left)
                        LivelinessChangedStatus livelinessStatus = new LivelinessChangedStatus() ;
                        status = loadAdmin.GetLivelinessChangedStatus(ref livelinessStatus);
                        ErrorHandler.checkStatus(status, "DDS.DataReader.getLivelinessChangedStatus");
                        if (livelinessStatus.AliveCount < prevCount)
                        {
                            /* A user has left the ChatRoom, since a DataWriter
                               lost its liveliness. Take the effected users
                               so they will not appear in the list later on. */
                            status = nameServer.Take(
                                ref nsMsgs,
                                ref nsInfos,
                                Length.Unlimited,
                                SampleStateKind.Any,
                                ViewStateKind.Any,
                                InstanceStateKind.NotAliveNoWriters);
                            ErrorHandler.checkStatus(status, "Chat.NameServiceDataReader.Take");

                            foreach (NameService nsMsg in nsMsgs)
                            {
                                /* re-apply query arguments */
                                parameters[0] = nsMsg.userID.ToString();
                                status = singleUser.SetQueryParameters(parameters);
                                ErrorHandler.checkStatus(status, "DDS.QueryCondition.SetQueryParameters");

                                /* Read this user's history */
                                status = loadAdmin.TakeWithCondition(
                                    ref msgs,
                                    ref msgInfos,
                                    singleUser);

                                ErrorHandler.checkStatus(
                                    status,
                                    "Chat.ChatMessageDataReader.TakeWithCondition");

                                /* Display the user and his history */
                                Console.WriteLine("Departed user {0} has sent {1} messages ", nsMsg.name, msgs.Length);
                                status = loadAdmin.ReturnLoan(ref msgs, ref msgInfos);
                                ErrorHandler.checkStatus(status, "Chat.ChatMessageDataReader.ReturnLoan");
                            }
                            status = nameServer.ReturnLoan(ref nsMsgs, ref nsInfos);
                            ErrorHandler.checkStatus(status, "Chat.NameServiceDataReader.ReturnLoan");
                        }
                        prevCount = livelinessStatus.AliveCount;

                    }
                    else if (guard == escape)
                    {
                        Console.WriteLine("UserLoad has terminated.");
                        closed = true;
                    }
                    else
                    {
                        //System.Diagnostics.Debug.Fail("Unknown Condition");
                    }
                } /* for */
            } /* while (!closed) */

            /* Remove all Conditions from the WaitSet. */
            status = userLoadWS.DetachCondition(escape);
            ErrorHandler.checkStatus(status, "DDS.WaitSet.DetachCondition (escape)");
            status = userLoadWS.DetachCondition(leftUser);
            ErrorHandler.checkStatus(status, "DDS.WaitSet.DetachCondition (leftUser)");
            status = userLoadWS.DetachCondition(newUser);
            ErrorHandler.checkStatus(status, "DDS.WaitSet.DetachCondition (newUser)");

            /* Free all resources */
            status = participant.DeleteContainedEntities();
            ErrorHandler.checkStatus(status, "DDS.DomainParticipant.DeleteContainedEntities");
            status = dpf.DeleteParticipant(participant);
            ErrorHandler.checkStatus(status, "DDS.DomainParticipantFactory.DeleteParticipant");
        }
예제 #10
0
 public ReturnCode GetLivelinessChangedStatus(
         ref LivelinessChangedStatus status)
 {
     if (status == null) status = new LivelinessChangedStatus();
     return Gapi.DataReader.get_liveliness_changed_status(GapiPeer, status);
 }
예제 #11
0
 public void OnLivelinessChanged(
     IDataReader the_reader, LivelinessChangedStatus status)
 {
 }
예제 #12
0
 public void OnLivelinessChanged(IDataReader entityInterface, LivelinessChangedStatus status)
 {
     Console.WriteLine("=== [ListenerDataListener::OnlivelinessChanged] triggered");
 }