예제 #1
0
        public void TestAttachCondition()
        {
            // Initialize
            WaitSet        waitSet        = new WaitSet();
            GuardCondition guardCondition = new GuardCondition();

            // Test with null parameter
            ReturnCode result = waitSet.AttachCondition(null);

            Assert.AreEqual(ReturnCode.BadParameter, result);

            // Test with correct parameter
            result = waitSet.AttachCondition(guardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Attach again should return OK but not actually add another condition to the WaitSet
            result = waitSet.AttachCondition(guardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);

            List <Condition> conditions = new List <Condition>();

            result = waitSet.GetConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.IsNotNull(conditions);
            Assert.AreEqual(1, conditions.Count);
            Assert.AreEqual(guardCondition, conditions[0]);
        }
예제 #2
0
        public void TestGetConditions()
        {
            // Initialize
            WaitSet        waitSet             = new WaitSet();
            GuardCondition guardCondition      = new GuardCondition();
            GuardCondition otherGuardCondition = new GuardCondition();
            ReturnCode     result = waitSet.AttachCondition(guardCondition);

            Assert.AreEqual(ReturnCode.Ok, result);
            result = waitSet.AttachCondition(otherGuardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Test with null parameter
            result = waitSet.GetConditions(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);

            // Test with correct parameter
            List <Condition> conditions = new List <Condition>()
            {
                null
            };

            result = waitSet.GetConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.IsNotNull(conditions);
            Assert.AreEqual(2, conditions.Count);
            Assert.IsNotNull(conditions[0]);
            Assert.IsNotNull(conditions[1]);
            Assert.IsTrue(conditions[0] != conditions[1]);
            Assert.IsTrue(guardCondition == conditions[0] || guardCondition == conditions[1]);
            Assert.IsTrue(otherGuardCondition == conditions[0] || otherGuardCondition == conditions[1]);
        }
예제 #3
0
        /// <summary>
        /// Creates a DomainParticipant, Topic, Subscriber and DataReader<HelloWorld>.
        /// </summary>
        public HelloWorldSubscriber(int domainId)
        {
            // Enable network capture.
            // This must be called before any other network capture function, and
            // before creating any participant for which we want to capture traffic.
            NetworkCapture.Enable();

            // Start communicating in a domain, usually one participant per application
            // Load QoS profile from USER_QOS_PROFILES.xml file
            participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic = participant.CreateTopic <HelloWorld>(
                "Network capture shared memory example");

            // Create a subscriber
            Subscriber subscriber = participant.CreateSubscriber();

            // Create a DataReader, loading QoS profile from USER_QOS_PROFILES.xml.
            reader = subscriber.CreateDataReader(topic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = reader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            statusCondition.Triggered += ProcessData;

            // Create a WaitSet and attach the StatusCondition
            waitset.AttachCondition(statusCondition);
        }
예제 #4
0
        public void TestDetachCondition()
        {
            // Initialize
            WaitSet        waitSet        = new WaitSet();
            GuardCondition guardCondition = new GuardCondition();
            ReturnCode     result         = waitSet.AttachCondition(guardCondition);

            Assert.AreEqual(ReturnCode.Ok, result);

            // Test with null parameter
            result = waitSet.DetachCondition(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);

            // Test with correct parameter
            result = waitSet.DetachCondition(guardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Test again the same condition
            result = waitSet.DetachCondition(guardCondition);
            Assert.AreEqual(ReturnCode.PreconditionNotMet, result);

            // Detach a not attached condition
            GuardCondition notAttachedCondition = new GuardCondition();

            result = waitSet.DetachCondition(notAttachedCondition);
            Assert.AreEqual(ReturnCode.PreconditionNotMet, result);
        }
예제 #5
0
        static void Main(string[] args)
        {
            DDSEntityManager     mgr    = new DDSEntityManager("Listener");
            ReturnCode           status = ReturnCode.Error;
            ListenerDataListener myListener;
            String partitionName = "Listener Example";
            int    count         = 0;

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

            // create Type
            MsgTypeSupport msgTS = new MsgTypeSupport();

            mgr.registerType(msgTS);

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

            // create Subscriber
            mgr.createSubscriber();

            // create DataReader
            mgr.createReader(false);

            IDataReader dreader = mgr.getReader();

            myListener       = new ListenerDataListener();
            myListener.MsgDR = dreader as MsgDataReader;

            Console.WriteLine("=== [ListenerDataSubscriber] SetListener");
            StatusKind kind = StatusKind.DataAvailable | StatusKind.RequestedDeadlineMissed;

            status = myListener.MsgDR.SetListener(myListener, kind);
            ErrorHandler.checkStatus(status, "DataReader.SetListener");

            Console.WriteLine("=== [ListenerDataSubscriber] Ready...");
            myListener.terminated = false;

            WaitSet ws = new WaitSet();

            ws.AttachCondition(myListener.guardCond);
            ICondition[] cond = null;

            while (!myListener.terminated && count < 1500)
            {
                Console.WriteLine("=== [SubscriberUsingListener] waiting waitset ...");
                ws.Wait(ref cond, Duration.Infinite);
                myListener.guardCond.SetTriggerValue(false);
                ++count;
            }

            Console.WriteLine("===[ListenerDataSubscriber] Market Closed.");

            mgr.getSubscriber().DeleteDataReader(myListener.MsgDR);
            mgr.deleteSubscriber();
            mgr.deleteTopic();
            mgr.deleteParticipant();
        }
예제 #6
0
        public ShapeWaitSet(ShapeTypeDataReader dataReader, Action <ShapeTypeDataReader> dataAvailableFunc)
        {
            _dataAvailableFunc = dataAvailableFunc;
            _dataReader        = dataReader;

            _waitSet = new WaitSet();
            _thread  = new Thread(DoThreadActivity)
            {
                IsBackground = true
            };

            _cancelCondition = new GuardCondition();
            _statusCondition = dataReader.StatusCondition;
            _waitSet.AttachCondition(_statusCondition);
            _waitSet.AttachCondition(_cancelCondition);
            _statusCondition.EnabledStatuses = StatusKind.DataAvailableStatus;
            _thread.Start();
        }
예제 #7
0
        /// <summary>
        /// Main function, receiving structured command-line arguments
        /// via the System.Console.DragonFruit package.
        /// For example: dotnet run -- --domain-id 54 --sample-count 5
        /// </summary>
        /// <param name="domainId">The domain ID to create the DomainParticipant</param>
        /// <param name="sampleCount">The number of data samples to receive before exiting</param>
        public static void Main(int domainId = 0, int sampleCount = int.MaxValue)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            //
            // A participant needs to be Disposed to release middleware resources.
            // The 'using' keyword indicates that it will be Disposed when this
            // scope ends.
            using DomainParticipant participant = DomainParticipantFactory.Instance
                                                  .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create dynamically-typed
            // Topic named "HelloWorld Topic" with the type definition of
            // "HelloWorld" in hello_world.xml. To get the type we use a QosProvider
            var provider = new QosProvider("../hello_world.xml");
            Topic <DynamicData> topic = participant.CreateTopic(
                "Example HelloWorld",
                provider.GetType("HelloWorld"));

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // This DataReader reads data of type Temperature on Topic
            // "ChocolateTemperature". DataReader QoS is configured in
            // USER_QOS_PROFILES.xml
            DataReader <DynamicData> reader = subscriber.CreateDataReader(topic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = reader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            int samplesRead = 0;

            statusCondition.Triggered += _ => samplesRead += ProcessData(reader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);
            while (samplesRead < sampleCount)
            {
                // Dispatch will call the handlers associated to the WaitSet
                // conditions when they activate
                Console.WriteLine("HelloWorld subscriber sleeping for 4 sec...");
                waitset.Dispatch(Duration.FromSeconds(4));
            }
        }
        private void RunExample(int domainId, int sampleCount)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateTemperature" with type Temperature
            // In this example we use a DynamicType defined in XML, which creates
            // a DynamicData topic.
            var provider = new QosProvider("../chocolate_factory.xml");
            Topic <DynamicData> topic = participant.CreateTopic(
                "ChocolateTemperature",
                provider.GetType("Temperature"));

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // This DataReader reads data of type Temperature on Topic
            // "ChocolateTemperature". DataReader QoS is configured in
            // USER_QOS_PROFILES.xml
            DataReader <DynamicData> reader = subscriber.CreateDataReader(topic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = reader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            int samplesRead = 0;

            statusCondition.Triggered += _ => samplesRead += ProcessData(reader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);
            while (samplesRead < sampleCount && !shutdownRequested)
            {
                // Dispatch will call the handlers associated to the WaitSet
                // conditions when they activate
                Console.WriteLine("ChocolateTemperature subscriber sleeping for 4 sec...");
                waitset.Dispatch(Duration.FromSeconds(4));
            }
        }
예제 #9
0
        public RTIReader(
            DataReader <T> reader,
            ITypeHelper <T> dataType,
            Parameters arguments)
        {
            this.reader    = reader;
            dataTypeHelper = dataType;
            if (arguments.UseReadThread)
            {
                WaitSetProperty property = new WaitSetProperty(
                    (int)arguments.WaitsetEventCount,
                    Duration.FromMilliseconds(arguments.WaitsetDelayUsec / 1000));

                waitset = new WaitSet(property);
                StatusCondition readerStatus = reader.StatusCondition;
                readerStatus.EnabledStatuses = StatusMask.DataAvailable;
                waitset.AttachCondition(readerStatus);
            }
        }
        /// <summary>
        /// Process the data received by the readers
        /// </summary>
        public Task Run(int _, CancellationToken cancellationToken)
        {
            var condition = subscriber.StatusCondition;

            condition.EnabledStatuses = StatusMask.DataOnReaders;
            condition.Triggered      += ProcessData;

            var waitSet = new WaitSet();

            waitSet.AttachCondition(condition);

            return(Task.Run(() =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    waitSet.Dispatch(Duration.FromSeconds(1));
                }
            }, cancellationToken));
        }
        private void RunExample(int domainId, string sensorId)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Uses TemperingApplication QoS profile to set participant name.
            var qosProvider    = new QosProvider("./qos_profiles.xml");
            var participantQos = qosProvider.GetDomainParticipantQos(
                "ChocolateFactoryLibrary::TemperingApplication");
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId, participantQos);

            // A Topic has a name and a datatype.
            Topic <Temperature> temperatureTopic = participant.CreateTopic <Temperature>(
                CHOCOLATE_TEMPERATURE_TOPIC.Value);
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic <ChocolateLotState>(
                CHOCOLATE_LOT_STATE_TOPIC.Value);

            // A Publisher allows an application to create one or more DataWriters
            // Create Publisher with default QoS.
            Publisher publisher = participant.CreatePublisher();

            // Create DataWriter of Topic "ChocolateTemperature"
            // using ChocolateTemperatureProfile QoS profile for Streaming Data
            DataWriter <Temperature> temperatureWriter = publisher.CreateDataWriter(
                temperatureTopic,
                qos: qosProvider.GetDataWriterQos("ChocolateFactoryLibrary::ChocolateTemperatureProfile"));

            // Create DataWriter of Topic "ChocolateLotState"
            // using ChocolateLotStateProfile QoS profile for State Data
            DataWriter <ChocolateLotState> lotStateWriter = publisher.CreateDataWriter(
                lotStateTopic,
                qos: qosProvider.GetDataWriterQos("ChocolateFactoryLibrary::ChocolateLotStateProfile"));

            // A Subscriber allows an application to create one or more DataReaders
            Subscriber subscriber = participant.CreateSubscriber();

            // This DataReader reads data of type Temperature on Topic
            // "ChocolateTemperature" using ChocolateLotStateProfile QoS
            // profile for State Data.
            //
            // We will handle the "requested incompatible qos" event. By doing
            // it as a preEnableAction, we avoid a race condition in which
            // the event could trigger right after the reader creation but
            // right before adding the event handler.
            DataReader <ChocolateLotState> lotStateReader = subscriber.CreateDataReader(
                lotStateTopic,
                qos: qosProvider.GetDataReaderQos("ChocolateFactoryLibrary::ChocolateLotStateProfile"),
                preEnableAction: reader => reader.RequestedIncompatibleQos += OnRequestedIncompatibleQos);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            statusCondition.Triggered +=
                _ => ProcessLot(lotStateReader, lotStateWriter);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            // Create a thread to periodically publish the temperature
            Console.WriteLine($"ChocolateTemperature Sensor with ID: {sensorId} starting");
            var temperatureTask = Task.Run(
                () => PublishTemperature(temperatureWriter, sensorId));

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            temperatureTask.Wait();
        }
예제 #12
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("*** [ContentFilteredTopicDataSubscriber] Subscription string not specified");
                Console.WriteLine("*** usage : ContentFilteredTopicDataSubscriber <subscription_string>");
                Environment.Exit(-1);
            }

            ITopic           topic;
            DDSEntityManager mgr           = new DDSEntityManager("ContentFilteredTopic");
            String           partitionName = "ContentFilteredTopic example";

            // Create DomainParticipant
            mgr.createParticipant(partitionName);

            // Create Type
            StockTypeSupport msgTS = new StockTypeSupport();

            mgr.registerType(msgTS);

            // Create Topic
            topic = mgr.createTopic("StockTrackerExclusive");

            // ContentFilteredTopic
            mgr.createContentFilter("MyStockTopic", topic, args[0]);
            Console.WriteLine("=== [ContentFilteredTopicDataSubscriber] Subscription filter : ticker = '{0}'", args[0]);
            // create Subscriber
            mgr.createSubscriber();

            // create DataReader
            mgr.createReader(true);

            // Read Events
            IDataReader     dreader       = mgr.getReader();
            StockDataReader WaitSetReader = dreader as StockDataReader;

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

            // Status Condition
            IStatusCondition status;

            status = dreader.StatusCondition;
            status.SetEnabledStatuses(StatusKind.DataAvailable);

            ReturnCode result = ReturnCode.Error;

            result = w.AttachCondition(status);
            ErrorHandler.checkHandle(status, "DataReader.StatusCondition");
            ErrorHandler.checkStatus(result, "WaitSet.AttachCondition");

            DDS.ICondition[] conditionList;
            DDS.SampleInfo[] infoSeq;
            Stock[]          stockSeq;

            Console.WriteLine("=== [ContentFilteredTopicDataSubscriber] Ready ...");

            bool terminate = false;
            int  count     = 0;

            while (!terminate && count < 1500)
            {
                /**
                 * Wait until data will be available
                 */
                Duration wait_timeout = new Duration(Duration.InfiniteSec, Duration.InfiniteNanoSec);
                conditionList = null;
                result        = w.Wait(ref conditionList, wait_timeout);
                ErrorHandler.checkStatus(result, "WaitSet.Wait");

                stockSeq = null;
                infoSeq  = null;

                /**
                 * Read Data
                 */
                result = WaitSetReader.Take(ref stockSeq, ref infoSeq, Length.Unlimited, SampleStateKind.Any, ViewStateKind.Any, InstanceStateKind.Any);
                ErrorHandler.checkStatus(result, "StockDataReader.Take");

                /**
                 * Display Data
                 */
                for (int i = 0; i < stockSeq.Length; i++)
                {
                    if (infoSeq[i].ValidData)
                    {
                        if (stockSeq[i].price == -1)
                        {
                            // We read the last expected sample => exit
                            terminate = true;
                            break;
                        }
                        Console.WriteLine("=== [ContentFilteredTopicDataSubscriber] receives stockQuote :  ( {0} , {1} )",
                                          stockSeq[i].ticker, stockSeq[i].price);
                    }
                }
                result = WaitSetReader.ReturnLoan(ref stockSeq, ref infoSeq);
                ErrorHandler.checkStatus(result, "StockDataReader.ReturnLoan");
                Thread.Sleep(200);
                ++count;
            }

            Console.WriteLine("=== [ContentFilteredTopicDataSubscriber] Market Closed");

            // clean up
            mgr.getSubscriber().DeleteDataReader(WaitSetReader);
            mgr.deleteSubscriber();
            mgr.deleteContentFilteredTopic();
            mgr.deleteTopic();
            mgr.deleteParticipant();
        }
예제 #13
0
        private void RunExample(int domainId, string stationKind)
        {
            if (!Enum.TryParse <StationKind>(stationKind, out var currentStation))
            {
                throw new ArgumentException("Invalid station");
            }

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Uses TemperingApplication QoS profile to set participant name.
            var qosProvider = new QosProvider("./qos_profiles.xml");

            // By specifying a default library, we can later refer to the
            // profiles without the library name
            qosProvider.DefaultLibrary = "ChocolateFactoryLibrary";

            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(
                domainId,
                qosProvider.GetDomainParticipantQos("IngredientApplication"));

            Topic <Temperature> temperatureTopic =
                participant.CreateTopic <Temperature>("ChocolateTemperature");
            Topic <ChocolateLotState> lotStateTopic =
                participant.CreateTopic <ChocolateLotState>("ChocolateLotState");

            ContentFilteredTopic <ChocolateLotState> filteredLotStateTopic =
                participant.CreateContentFilteredTopic(
                    name: "FilteredLot",
                    relatedTopic: lotStateTopic,
                    filter: new Filter(
                        expression: "next_station = %0",
                        parameters: new string[] { $"'{stationKind}'" }));

            Publisher publisher = participant.CreatePublisher();

            // Create DataWriter of Topic "ChocolateLotState"
            // using ChocolateLotStateProfile QoS profile for State Data
            DataWriter <ChocolateLotState> lotStateWriter = publisher.CreateDataWriter(
                lotStateTopic,
                qosProvider.GetDataWriterQos("ChocolateLotStateProfile"));

            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState", filtered by
            // next_station, and using ChocolateLotStateProfile QoS profile for
            // State Data.
            DataReader <ChocolateLotState> lotStateReader = subscriber.CreateDataReader(
                filteredLotStateTopic,
                qosProvider.GetDataReaderQos("ChocolateLotStateProfile"));

            // Monitor the DataAvailable status
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            statusCondition.EnabledStatuses = StatusMask.DataAvailable;
            statusCondition.Triggered      +=
                _ => ProcessLot(currentStation, lotStateReader, lotStateWriter);
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(10));
            }
        }
예제 #14
0
        static void Main(string[] args)
        {
            int domain = DDS.DomainId.Default;

            /* 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");
        }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // Exercise #1.1: Add QoS provider

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Exercise #1.2: Load DomainParticipant QoS profile
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic <ChocolateLotState>(
                CHOCOLATE_LOT_STATE_TOPIC.Value);
            // Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic = participant.CreateTopic <Temperature>(
                CHOCOLATE_TEMPERATURE_TOPIC.Value);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // Exercise #4.1: Load ChocolateLotState DataWriter QoS profile after
            // debugging incompatible QoS
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // Exercise #1.3: Update the lotStateReader and temperatureReader
            // to use correct QoS
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Add a DataReader for Temperature to this application
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(temperatureTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered += _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
예제 #16
0
        public void Run()
        {
#if DBCallTests
            DDS.Test.DatabaseTests();
#endif

            Console.WriteLine("Press enter to enter...");
            Console.ReadLine();
            Data.DataTest detectionData = new Data.DataTest();
            detectionData.TestId    = 3214;
            detectionData.Emergency = true;
            detectionData.TestStr   = "not really";
            //detectionData.SeqInt[3] = 23;
#if TestMarshaling
            //Tactical.DetectionTypeSupport support = new Tactical.DetectionTypeSupport();
            //Tactical.Detection cachedObj = new Tactical.Detection();
            //support.Copy(cachedObj, detectionData);

            //SampleMarshaler marshaler = SampleMarshalerFactory.CreateMarshaler(detectionData);

            //using (SampleMarshalHelper helper = new SampleMarshalHelper(marshaler))
            //{
            //    DDS.OpenSplice.Gapi.Test.test_detection(helper.GapiPtr);

            //    Tactical.Detection detectionData2 = new Tactical.Detection();
            //    SampleMarshaler marshaler2 = SampleMarshalerFactory.CreateMarshaler(detectionData2);
            //    marshaler2.CopyOut(helper.GapiPtr, 0);
            //}

            //Duration d = new Duration(234, 2343);
            //int sec;
            //uint nanosec;
            //DDS.OpenSplice.Gapi.Test.test_duration(d, out sec, out nanosec);

            //LivelinessChangedStatus status;
            //DDS.OpenSplice.Gapi.Test.get_liveliness_changed_status(out status);

            //Time t = new Time(1, 2);
            //int size = Marshal.SizeOf(t);
            //IntPtr ptr = Marshal.AllocHGlobal(size);
            //Marshal.StructureToPtr(t, ptr, true);
#endif

            //DDS.Test.TestDataReaderQos();
            //DDS.Test.TestTopicQos();

            // Create a DomainParticipantFactory
            DomainParticipantFactory dpf = DomainParticipantFactory.Instance;
            Console.WriteLine("DomainParticipantFactory: " + dpf);

            // Tailor the DomainPartipantFactoryQos;
            DomainParticipantFactoryQos dpfQos = null;
            ReturnCode result = dpf.GetQos(ref dpfQos);
            Console.WriteLine("DomainParticipantFactory.get_qos: {0}", result);
            Console.WriteLine("DomainParticipantFactoryQos.entity_factory.autoenable_created_entities: " + dpfQos.EntityFactory.AutoenableCreatedEntities);

            dpfQos.EntityFactory.AutoenableCreatedEntities = false;
            result = dpf.SetQos(dpfQos);
            Console.WriteLine("DomainParticipantFactory.set_qos: {0}", result);

            // Get the QOS settings for the Factory...  Check values without additional changes
            DomainParticipantFactoryQos dpf2Qos = null;
            result = dpf.GetQos(ref dpf2Qos);
            Console.WriteLine("DomainParticipantFactory.get_qos: {0}", result);
            Console.WriteLine("DomainParticipantFactoryQos.entity_factory.autoenable_created_entities: " + dpf2Qos.EntityFactory.AutoenableCreatedEntities);

            // Create the domainParticipant itself.
            DomainParticipantQos dpQos = new DomainParticipantQos();
            dpQos.UserData.Value = new byte[] { (byte)1, (byte)2, (byte)3 };
            dpQos.EntityFactory.AutoenableCreatedEntities        = true;
            dpQos.ListenerScheduling.SchedulingClass.Kind        = SchedulingClassQosPolicyKind.ScheduleDefault;
            dpQos.ListenerScheduling.SchedulingPriorityKind.Kind = SchedulingPriorityQosPolicyKind.PriorityRelative;
            dpQos.ListenerScheduling.SchedulingPriority          = 0;
            dpQos.WatchdogScheduling.SchedulingClass.Kind        = SchedulingClassQosPolicyKind.ScheduleDefault;
            dpQos.WatchdogScheduling.SchedulingPriorityKind.Kind = SchedulingPriorityQosPolicyKind.PriorityRelative;
            dpQos.WatchdogScheduling.SchedulingPriority          = 4;

            IDomainParticipant dp = dpf.CreateParticipant(null, dpQos);
            Console.Write("DomainParticipant: ");
            Console.WriteLine(dp != null ? "yes" : "no");


            if (dp.ContainsEntity(0))
            {
                Console.WriteLine("contains_entity with nil handle incorrect");
            }
            if (dp.ContainsEntity(100))
            {
                Console.WriteLine("contains_entity with incorrect handle incorrect");
            }

            Time currentTime;
            dp.GetCurrentTime(out currentTime);
            Console.WriteLine("Current Local Time: {0}", currentTime.ToDatetime().ToLocalTime());

            // And look up this DomainParticipant.
            IDomainParticipant dp2 = dpf.LookupParticipant(null);

            DomainParticipantQos dp2Qos = null;

            Console.Write("lookup DomainParticipant: ");
            Console.WriteLine(dp2 != null ? "Success" : "Fail");
            result = dp2.GetQos(ref dp2Qos);
            Console.WriteLine("DomainParticipant.get_qos: {0}", result);
            Console.WriteLine("DomainParticipantQos.entity_factory.autoenable_created_entities: " + dp2Qos.EntityFactory.AutoenableCreatedEntities);

            // Create a new PublisherQos and set some values...
            PublisherQos publisherQos = new PublisherQos();
            publisherQos.EntityFactory.AutoenableCreatedEntities = true;
            publisherQos.Partition.Name = new string[] { "howdy" }; //, "neighbor", "partition" };

            // true not supported in 4.1 ??
            publisherQos.Presentation.OrderedAccess = false;

            // Create the Publisher
            dp.Enable();
            IPublisher publisher = dp.CreatePublisher(publisherQos);
            Console.WriteLine("Create Publisher: {0}", publisher);

            //DataWriterQos dwQos;
            //publisher.GetDefaultDataWriterQos(out dwQos);


            // Create a Detection Type Support and register it's type
            Data.DataTestTypeSupport support = new Data.DataTestTypeSupport();

            string test2 = support.TypeName;
            Console.WriteLine("Register Typesupport");
            result = support.RegisterType(dp, support.TypeName);
            Console.WriteLine("Register Typesupport Result: {0}", result);

            // Create a topic for the Detection type
            TopicQos topicQos = null;
            result = dp.GetDefaultTopicQos(ref topicQos);

            //topicQos.Ownership.Kind = OwnershipQosPolicyKind.ExclusiveOwnershipQos;

            //DDS.Test.TestTopicQos2(ref topicQos);

            // Add a listener to the topic
            ITopic topic = dp.CreateTopic("Data_DataTest", support.TypeName, topicQos,
                                          this, StatusKind.InconsistentTopic);

            topicQos.History.Depth = 5;

            ITopic topic2 = dp.CreateTopic("Data_DataTest", support.TypeName, topicQos);

            //			ErrorCode errorCode;
            //			string msg;
            //			result = ErrorInfo.Update();
            //			result = ErrorInfo.GetCode(out errorCode);
            //			result = ErrorInfo.GetMessage(out msg);

            // Create a DataWriter for the topic
            Data.IDataTestDataWriter dataWriter = publisher.CreateDataWriter(topic) as Data.IDataTestDataWriter;

            // Create a SubscriberQos object and set the partition name
            SubscriberQos subscriberQos = null;
            result = dp.GetDefaultSubscriberQos(ref subscriberQos);
            subscriberQos.Partition.Name = new string[] { "howdy" };

            // Create the subscriber
            ISubscriber sub = dp.CreateSubscriber(subscriberQos);
            // Verify that the subsciber was created...
            if (sub == null)
            {
                Console.WriteLine("Subscriber not created");
                return;
            }

            DDS.DataReaderQos readerQos = null;
            sub.GetDefaultDataReaderQos(ref readerQos);

            //readerQos.SubscriptionKeys.KeyList = new string[] { "test" };
            //readerQos.Durability.Kind = DurabilityQosPolicyKind.TransientDurabilityQos;
            //readerQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;

            // Create a DataReader for the Detection topic
            Data.IDataTestDataReader dataReader = sub.CreateDataReader(topic, readerQos, this, StatusKind.DataAvailable)
                                                  as Data.IDataTestDataReader;

            // Create a filtered detection topic (only read detections that have an id != 4)
            IContentFilteredTopic filteredTopic = dp.CreateContentFilteredTopic("Another", topic, "TestId <> %0", "4");

            string[] testParams = null;
            result = filteredTopic.GetExpressionParameters(ref testParams);
            result = filteredTopic.SetExpressionParameters("hello", "test");
            result = filteredTopic.GetExpressionParameters(ref testParams);

            // Create a DataReader to read the filtered topic
            IDataReader reader2 = sub.CreateDataReader(filteredTopic);

            IQueryCondition queryCondition = dataReader.CreateQueryCondition(
                "TestId = %0",
                "234");

            // just for testing...
            //GC.Collect();

            // WaitSet
            WaitSet waitSet = new WaitSet();

            // either use status conditions...or
            IStatusCondition sc = reader2.StatusCondition;
            sc.SetEnabledStatuses(StatusKind.DataAvailable);
            waitSet.AttachCondition(sc);

            IStatusCondition sc2 = reader2.StatusCondition;

            // read conditions...
            // IReadCondition readCond = reader2.CreateReadCondition();
            // waitSet.AttachCondition(readCond);

            ICondition[] cond = null;
            //waitSet.Wait(ref cond, Duration.Infinite);


            Console.WriteLine("Press enter to write data");
            Console.ReadLine();

            detectionData.SequenceTest = new int[1];// new System.Collections.Generic.List<int>();
            //detectionData.SequenceTest.Add(4);
            detectionData.SequenceTest[0] = 4;

            // Write detection data
            result = dataWriter.Write(detectionData);

            detectionData        = new Data.DataTest();
            detectionData.TestId = 234;
            dataWriter.Write(detectionData, InstanceHandle.Nil);

            detectionData        = new Data.DataTest();
            detectionData.TestId = 235;
            dataWriter.Write(detectionData);

            detectionData        = new Data.DataTest();
            detectionData.TestId = 236;
            dataWriter.Write(detectionData);

            detectionData        = new Data.DataTest();
            detectionData.TestId = 237;
            dataWriter.Write(detectionData);

            Console.WriteLine("Press enter to read data");
            Console.ReadLine();

            // Read the data
            SampleInfo[]    infos      = null;
            Data.DataTest[] dataValues = null;

//            result = dataReader.ReadWithCondition(ref dataValues, ref infos, DDS.Length.Unlimited, queryCondition);

            result = dataReader.Read(ref dataValues, ref infos);
            Console.WriteLine("dataReader: {0}", dataReader);

            if (dataValues != null)
            {
                Console.WriteLine("Number of samples received: {0}", dataValues.Length);
                for (int index = 0; index < dataValues.Length; index++)
                {
                    Console.WriteLine("TestId: {0}, ProviderId: {1}, Emergency: {2}, TestStr: {3}", dataValues[index].TestId,
                                      dataValues[index].ProviderId, dataValues[index].Emergency, dataValues[index].TestStr);
                    Console.WriteLine("info: ValidData: {0},  InstHandle: {1},  PubHandle:{2},  SourceTS: {3}, ArrivalTS: {4}, sample: {5}, view: {6}, instance: {7}",
                                      infos[index].ValidData,
                                      infos[index].InstanceHandle, infos[index].PublicationHandle,
                                      infos[index].SourceTimestamp, infos[index].ArrivalTimestamp,
                                      infos[index].SampleState, infos[index].ViewState, infos[index].InstanceState);
                }
            }
            Console.WriteLine("Press enter to cleanup");
            Console.ReadLine();

            Console.WriteLine("DeleteContainedEntities");
            result = dp.DeleteContainedEntities();

            // If you don't use DeleteContainedEntities then you must delete everything that was created
            //result = sub.DeleteDataReader(dataReader);
            //result = publisher.DeleteDataWriter(dataWriter);

            //result = dp.DeleteTopic(topic);
            //result = dp.DeletePublisher(publisher);

            //result = dp.DeleteSubscriber(sub);

            Console.WriteLine("DeleteParticipant");
            result = dpf.DeleteParticipant(dp);

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
        private void RunExample(int domainId, string sensorId)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create Topics using the types
            // defined in chocolate_factory.xml
            var provider = new QosProvider("../chocolate_factory.xml");
            Topic <Temperature> temperatureTopic = participant.CreateTopic(
                "ChocolateTemperature",
                types.Temperature);
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic(
                "ChocolateLotState",
                types.ChocolateLotState);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // Create DataWriters of Topics "ChocolateTemperature" & "ChocolateLotState"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <Temperature> temperatureWriter =
                publisher.CreateDataWriter(temperatureTopic);
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // This DataReader reads data of type Temperature on Topic
            // "ChocolateTemperature". DataReader QoS is configured in
            // USER_QOS_PROFILES.xml
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            statusCondition.Triggered +=
                _ => ProcessLot(lotStateReader, lotStateWriter);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            // Create a thread to periodically publish the temperature
            Console.WriteLine($"ChocolateTemperature Sensor with ID: {sensorId} starting");
            var temperatureTask = Task.Run(
                () => PublishTemperature(temperatureWriter, sensorId));

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            temperatureTask.Wait();
        }
예제 #18
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();
        }
예제 #19
0
        static void Main(string[] args)
        {
            bool automatic = true;

            if (args.Length > 1)
            {
                automatic = args[0].Equals("true");
            }

            string           hostName;
            DDSEntityManager mgr = new DDSEntityManager("BuiltInTopics");

            // create domain participant
            mgr.createParticipant("BuiltInTopics");

            // Resolve the built-in Subscriber
            ISubscriber builtInSubscriber = mgr.getParticipant().BuiltInSubscriber;

            // Lookup the DataReader for the DCPSParticipant built-in Topic
            IDataReader reader = builtInSubscriber.LookupDataReader("DCPSParticipant");

            // Cast the DataReader to a ParticipantBuiltInTopicDataReader
            ParticipantBuiltinTopicDataDataReader participantReader = reader as ParticipantBuiltinTopicDataDataReader;

            ErrorHandler.checkHandle(participantReader, "ParticipantBuiltInTopicDataReader narrow");

            // Allocate a new typed seq for data samples
            ParticipantBuiltinTopicData[] data = null;

            // Allocate a new seq for sample infos
            SampleInfo[] info = null;

            Console.WriteLine("=== [BuiltInTopicsDataSubscriber] : Waiting for historical data ... ");
            participantReader.WaitForHistoricalData(Duration.Infinite);
            Console.WriteLine("=== [BuiltInTopicsDataSubscriber] : done");

            // Create a new ReadCondition for the reader that matches all samples
            IReadCondition readCond = participantReader.CreateReadCondition(SampleStateKind.Any, ViewStateKind.Any, InstanceStateKind.Any);

            ErrorHandler.checkHandle(readCond, "DataReader.CreateReadCondition");

            // Create a waitset and add the ReadCondition created above
            WaitSet    aWaitSet = new WaitSet();
            ReturnCode status   = aWaitSet.AttachCondition(readCond);

            ErrorHandler.checkStatus(status, "WaitSet.AttachCondition");

            // Initialize and pre-allocate the seq used to obtain the triggered Conditions.
            ICondition[] condSeq = new ICondition[0];

            // Allocate a map store node information later on
            // The key of map is the id of the node and the value is the
            // number of active participants on that node. A Dictionary is used
            // as an UnorderedMap.
            Dictionary <int, int> nodes = new Dictionary <int, int>();

            // Allocate a map to store node information later on.
            // The key of the map is the id of the node and the value is the
            // name of the node. A Dictionary is used as an UnorderedMap.
            Dictionary <int, string> nodeNames = new Dictionary <int, string>();

            Console.WriteLine("=== [BuiltInTopicsDataSubscriber] Ready ...");

            // Block the current thread until the attached condition becomes true
            // or the user interrupts.
            status = aWaitSet.Wait(ref condSeq, Duration.Infinite);
            ErrorHandler.checkStatus(status, "WaitSet.Wait");

            bool done = false;

            // Continue processing until interrupted.
            while (!done)
            {
                // Take all the available data from the reader
                status = participantReader.Take(ref data, ref info, Length.Unlimited,
                                                SampleStateKind.Any, ViewStateKind.Any, InstanceStateKind.Any);
                ErrorHandler.checkStatus(status, "ParticipantBuiltinTopicDataDataReader.Take");

                // Verify the data has been taken
                if (status == ReturnCode.Ok)
                {
                    // Iterate the list of taken samples.
                    for (int i = 0; i < data.Length; i++)
                    {
                        // Resolve the node identification
                        int nodeId = data[i].Key[0];

                        // Initialise the number of participants for a node
                        int participantCount = 0;

                        // Check if we saw a participant for the node before.
                        if (nodes.ContainsKey(nodeId))
                        {
                            participantCount = nodes[nodeId];
                        }

                        // Check sample info to see whether the instance is ALIVE.
                        if (info[i].InstanceState == InstanceStateKind.Alive)
                        {
                            // The splicedaemon publishes the host-name in the
                            // user_data field
                            if (data[i].UserData.Value.Length != 0)
                            {
                                hostName          = Encoding.UTF8.GetString(data[i].UserData.Value);
                                nodeNames[nodeId] = hostName;
                            }
                            else
                            {
                                hostName = null;
                            }

                            // Increase the number of participants.
                            participantCount++;

                            // Update the number of participants for the node.
                            nodes[nodeId] = participantCount;

                            // If it's the first participant, report the node is up.
                            if (participantCount == 1)
                            {
                                Console.WriteLine("=== [BuiltInTopicsDataSubscriber] Node ' {0} ' started (Total nodes running: {1} ) participantCount = {2}",
                                                  nodeId, nodes.Count, participantCount);
                            }
                            if (hostName != null)
                            {
                                Console.WriteLine("=== [BuiltInTopicsDataSubscriber] Hostname for node ' {0} ' is hostname: {1}", nodeId, hostName);
                            }
                        }
                        else
                        {
                            // Decrease the number of participants.
                            participantCount--;

                            // If no more participants exist, report the node is down.
                            if (participantCount == 0)
                            {
                                hostName = nodeNames[nodeId];
                                nodeNames.Remove(nodeId);
                                nodes.Remove(nodeId);

                                if (hostName != null)
                                {
                                    Console.WriteLine("=== [BuiltInTopicsDataSubscriber] Node {0} ({1}) stopped (Total nodes running: ({2})",
                                                      nodeId, hostName, nodes.Count);
                                }
                                else
                                {
                                    Console.WriteLine("=== [BuiltInTopicsDataSubscriber] Node {0} stopped (Total nodes running : {1})",
                                                      nodeId, nodes.Count);
                                }
                            }
                            else if (participantCount > 0)
                            {
                                nodes[nodeId] = participantCount;
                            }
                        }
                    }
                }

                status = participantReader.ReturnLoan(ref data, ref info);
                ErrorHandler.checkStatus(status, "ParticipantReader.ReturnLoan");

                if (!automatic)
                {
                    // Block the current thread until the attached condition becomes
                    // true or the user interrupts.
                    Console.WriteLine("=== [BuiltInTopicsDataSubscriber] Waiting ... ");
                    status = aWaitSet.Wait(ref condSeq, Duration.Infinite);
                    done   = (status != ReturnCode.Ok);
                }
                else
                {
                    done = true;
                }
            }

            // Delete read condition
            status = participantReader.DeleteReadCondition(readCond);
            ErrorHandler.checkStatus(status, "DataReader.DeleteReadCondition");

            // Recursively delete all entities in the DomainParticipant.
            mgr.getParticipant().DeleteContainedEntities();

            // Delete DomainParticipant
            mgr.getDomainParticipantFactory().DeleteParticipant(mgr.getParticipant());
        }
예제 #20
0
        public void TestDetachConditions()
        {
            // Initialize
            WaitSet        waitSet               = new WaitSet();
            GuardCondition guardCondition        = new GuardCondition();
            GuardCondition otherGuardCondition   = new GuardCondition();
            GuardCondition anotherGuardCondition = new GuardCondition();
            ReturnCode     result = waitSet.AttachCondition(guardCondition);

            Assert.AreEqual(ReturnCode.Ok, result);
            result = waitSet.AttachCondition(otherGuardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);
            result = waitSet.AttachCondition(anotherGuardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Test with null parameter
            result = waitSet.DetachConditions(null);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Test with empty list parameter
            List <Condition> conditions = new List <Condition>();

            result = waitSet.DetachConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Test with single element list parameter
            conditions = new List <Condition>()
            {
                guardCondition
            };
            result = waitSet.DetachConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);

            conditions = new List <Condition>()
            {
                null
            };
            result = waitSet.GetConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.IsNotNull(conditions);
            Assert.AreEqual(2, conditions.Count);
            Assert.IsNotNull(conditions[0]);
            Assert.IsNotNull(conditions[1]);
            Assert.IsTrue(conditions[0] != conditions[1]);
            Assert.IsTrue(anotherGuardCondition == conditions[0] || anotherGuardCondition == conditions[1]);
            Assert.IsTrue(otherGuardCondition == conditions[0] || otherGuardCondition == conditions[1]);

            // Detach the other conditions
            conditions = new List <Condition>()
            {
                otherGuardCondition, anotherGuardCondition
            };
            result = waitSet.DetachConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);

            conditions = new List <Condition>()
            {
                null
            };
            result = waitSet.GetConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.IsNotNull(conditions);
            Assert.AreEqual(0, conditions.Count);

            // Detach a not attached conditions
            GuardCondition notAttachedCondition = new GuardCondition();

            conditions = new List <Condition>()
            {
                notAttachedCondition
            };
            result = waitSet.DetachConditions(conditions);
            Assert.AreEqual(ReturnCode.PreconditionNotMet, result);
        }
        private void RunExample(int domainId, string sensorId)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Uses TemperingApplication QoS profile to set participant name.
            var qosProvider    = new QosProvider("./qos_profiles.xml");
            var participantQos = qosProvider.GetDomainParticipantQos(
                "ChocolateFactoryLibrary::TemperingApplication");
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId, participantQos);

            // Create the topics
            Topic <Temperature> temperatureTopic =
                participant.CreateTopic <Temperature>("ChocolateTemperature");
            Topic <ChocolateLotState> lotStateTopic =
                participant.CreateTopic <ChocolateLotState>("ChocolateLotState");

            // Exercise #1.1: Create a Content-Filtered Topic that filters out
            // chocolate lot state unless the next_station = TEMPERING_CONTROLLER

            // A Publisher allows an application to create one or more DataWriters
            // Create Publisher with default QoS.
            Publisher publisher = participant.CreatePublisher();

            // Create DataWriter of Topic "ChocolateTemperature"
            // using ChocolateTemperatureProfile QoS profile for Streaming Data
            DataWriter <Temperature> temperatureWriter = publisher.CreateDataWriter(
                temperatureTopic,
                qos: qosProvider.GetDataWriterQos("ChocolateFactoryLibrary::ChocolateTemperatureProfile"));

            // Create DataWriter of Topic "ChocolateLotState"
            // using ChocolateLotStateProfile QoS profile for State Data
            DataWriter <ChocolateLotState> lotStateWriter = publisher.CreateDataWriter(
                lotStateTopic,
                qos: qosProvider.GetDataWriterQos("ChocolateFactoryLibrary::ChocolateLotStateProfile"));

            // A Subscriber allows an application to create one or more DataReaders
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // using ChocolateLotStateProfile QoS profile for State Data
            // Exercise #1.2: Change the DataReader's Topic to use a
            // Content-Filtered Topic
            DataReader <ChocolateLotState> lotStateReader = subscriber.CreateDataReader(
                lotStateTopic,
                qos: qosProvider.GetDataReaderQos("ChocolateFactoryLibrary::ChocolateLotStateProfile"),
                preEnableAction: reader => reader.RequestedIncompatibleQos += OnRequestedIncompatibleQos);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            statusCondition.Triggered +=
                _ => ProcessLot(lotStateReader, lotStateWriter);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            // Create a thread to periodically publish the temperature
            Console.WriteLine($"ChocolateTemperature Sensor with ID: {sensorId} starting");
            var temperatureTask = Task.Run(
                () => PublishTemperature(temperatureWriter, sensorId));

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(10));
            }

            temperatureTask.Wait();
        }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState
            // In this example we use a DynamicType defined in XML, which creates
            // a DynamicData topic.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic(
                "ChocolateLotState",
                types.ChocolateLotState);
            // Exercise #4.1: Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic = participant.CreateTopic(
                "ChocolateTemperature",
                types.Temperature);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // DataReader QoS is configured in USER_QOS_PROFILES.xml
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Exercise #4.2: Add a DataReader for Temperature to this application
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(temperatureTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered += _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            WaitSet waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Exercise #4.3: Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
예제 #23
0
        // Exercise #4.4: Add monitor_temperature function

        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic <ChocolateLotState>(
                "ChocolateLotState");
            // Exercise #4.1: Add a Topic for Temperature to this application

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // DataReader QoS is configured in USER_QOS_PROFILES.xml
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Exercise #4.2: Add a DataReader for Temperature to this application

            // Obtain the DataReader's Status Condition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            WaitSet waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Exercise #4.3: Add the new DataReader's StatusCondition to the Waitset

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // Loads the QoS from the qos_profiles.xml file.
            var qosProvider = new QosProvider("./qos_profiles.xml");

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Load DomainParticipant QoS profile
            var participantQos = qosProvider.GetDomainParticipantQos(
                "ChocolateFactoryLibrary::MonitoringControlApplication");
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId, participantQos);

            // A Topic has a name and a datatype. Create a Topic with type
            // ChocolateLotState.  Topic name is a constant defined in the IDL file.
            Topic <ChocolateLotState> lotStateTopic =
                participant.CreateTopic <ChocolateLotState>("ChocolateLotState");
            // Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic =
                participant.CreateTopic <Temperature>("ChocolateTemperature");
            ContentFilteredTopic <Temperature> filteredTemperatureTopic =
                participant.CreateContentFilteredTopic(
                    name: "FilteredTemperature",
                    relatedTopic: temperatureTopic,
                    filter: new Filter(
                        expression: "degrees > %0 or degrees < %1",
                        parameters: new string[] { "32", "30" }));

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            var writerQos = qosProvider.GetDataWriterQos(
                "ChocolateFactoryLibrary::ChocolateLotStateProfile");
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic, writerQos);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // DataReader QoS is configured in USER_QOS_PROFILES.xml
            var readerQos = qosProvider.GetDataReaderQos(
                "ChocolateFactoryLibrary::ChocolateLotStateProfile");
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic, readerQos);

            // Add a DataReader for Temperature to this application
            readerQos = qosProvider.GetDataReaderQos(
                "ChocolateFactoryLibrary::ChocolateTemperatureProfile");
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(filteredTemperatureTopic, readerQos);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered +=
                _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
예제 #25
0
        public void TestWait()
        {
            // Initialize
            WaitSet        waitSet        = new WaitSet();
            GuardCondition guardCondition = new GuardCondition();
            ReturnCode     result         = waitSet.AttachCondition(guardCondition);

            Assert.AreEqual(ReturnCode.Ok, result);

            // Test with null conditions
            result = waitSet.Wait(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);

            // Attach again should return OK but not actually add another condition to the WaitSet
            result = waitSet.AttachCondition(guardCondition);
            Assert.AreEqual(ReturnCode.Ok, result);

            List <Condition> conditions = new List <Condition>();

            result = waitSet.GetConditions(conditions);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.IsNotNull(conditions);
            Assert.AreEqual(1, conditions.Count);
            Assert.AreEqual(guardCondition, conditions[0]);

            // Test thread wait infinite
            int    count  = 0;
            Thread thread = new Thread(() =>
            {
                result = waitSet.Wait(conditions);
                Assert.AreEqual(ReturnCode.Ok, result);
                Assert.IsNotNull(conditions);
                Assert.AreEqual(1, conditions.Count);
                Assert.AreEqual(guardCondition, conditions[0]);
                guardCondition.TriggerValue = false;
                count++;
            });

            thread.Start();

            guardCondition.TriggerValue = true;
            thread.Join();
            Assert.AreEqual(1, count);

            // Test timeout
            count  = 0;
            thread = new Thread(() =>
            {
                result = waitSet.Wait(conditions, new Duration {
                    Seconds = 0, NanoSeconds = 100000000
                });
                Assert.AreEqual(ReturnCode.Timeout, result);
                Assert.IsNotNull(conditions);
                Assert.AreEqual(0, conditions.Count);
                count++;
            });
            thread.Start();
            thread.Join();
            Assert.AreEqual(1, count);

            // Test exit before timeout
            count  = 0;
            thread = new Thread(() =>
            {
                result = waitSet.Wait(conditions, new Duration {
                    Seconds = 5
                });
                Assert.AreEqual(ReturnCode.Ok, result);
                Assert.IsNotNull(conditions);
                Assert.AreEqual(1, conditions.Count);
                Assert.AreEqual(guardCondition, conditions[0]);
                Assert.IsTrue(guardCondition.TriggerValue);
                guardCondition.TriggerValue = false;
                count++;
            });
            thread.Start();

            guardCondition.TriggerValue = true;
            thread.Join();
            Assert.AreEqual(1, count);
        }
예제 #26
0
        static void Main(string[] args)
        {
            bool useListener = true;

            OpenDDSharp.Ace.Init();

            ParticipantService       participantService = ParticipantService.Instance;
            DomainParticipantFactory domainFactory      = participantService.GetDomainParticipantFactory(args);
            DomainParticipantQos     qos = new DomainParticipantQos();

            qos.EntityFactory.AutoenableCreatedEntities = false;
            qos.UserData.Value = Encoding.UTF8.GetBytes("sometext");
            DomainParticipant participant = domainFactory.CreateParticipant(42, qos);

            if (participant == null)
            {
                throw new Exception("Could not create the participant");
            }

            DomainParticipantQos aux = new DomainParticipantQos();
            ReturnCode           ret = participant.GetQos(aux);

            aux.EntityFactory.AutoenableCreatedEntities = true;
            ret = participant.SetQos(aux);

            if (participant != null)
            {
                TestStructTypeSupport support = new TestStructTypeSupport();
                string     typeName           = support.GetTypeName();
                ReturnCode result             = support.RegisterType(participant, typeName);
                if (result != ReturnCode.Ok)
                {
                    throw new Exception("Could not register the type");
                }

                Topic     topic     = participant.CreateTopic("TopicName", typeName);
                Publisher publisher = participant.CreatePublisher();
                if (publisher == null)
                {
                    throw new Exception("Could not create the publisher");
                }

                DataWriter dw = publisher.CreateDataWriter(topic);
                if (dw == null)
                {
                    throw new Exception("Could not create the datawriter");
                }
                TestStructDataWriter dataWriter = new TestStructDataWriter(dw);
                Subscriber           subscriber = participant.CreateSubscriber();
                if (subscriber == null)
                {
                    throw new Exception("Could not create the subscribre");
                }

                MyDataListener listener = null;
                if (useListener)
                {
                    listener = new MyDataListener();
                }
                DataReader dataReader = subscriber.CreateDataReader(topic, listener, StatusKind.DataAvailableStatus);
                if (dataReader == null)
                {
                    throw new Exception("Could not create the datareader");
                }

                WaitSet         waitSet         = null;
                StatusCondition statusCondition = null;
                if (!useListener)
                {
                    waitSet         = new WaitSet();
                    statusCondition = dataReader.StatusCondition;
                    waitSet.AttachCondition(statusCondition);
                    statusCondition.EnabledStatuses = StatusKind.DataAvailableStatus;

                    new System.Threading.Thread(delegate()
                    {
                        ICollection <Condition> conditions = new List <Condition>();
                        Duration duration = new Duration
                        {
                            Seconds = Duration.InfiniteSeconds
                        };
                        waitSet.Wait(conditions, duration);

                        foreach (Condition cond in conditions)
                        {
                            if (cond == statusCondition && cond.TriggerValue)
                            {
                                StatusCondition sCond = (StatusCondition)cond;
                                StatusMask mask       = sCond.EnabledStatuses;
                                if ((mask & StatusKind.DataAvailableStatus) != 0)
                                {
                                    DataAvailable(dataReader);
                                }
                            }
                        }
                    }).Start();
                }

                TestStruct test = new TestStruct
                {
                    RawData = "Hello, I love you, won't you tell me your name?"
                };

                test.LongSequence.Add(20);
                test.LongSequence.Add(10);
                test.LongSequence.Add(0);

                test.StringSequence.Add("Hello,");
                test.StringSequence.Add("I love you");
                test.StringSequence.Add("won't you tell me your name?");

                test.LongDoubleType = 1.1;

                test.LongDoubleSequence.Add(1.1);
                test.LongDoubleSequence.Add(2.2);
                test.LongDoubleSequence.Add(3.3);

                test.LongArray[0, 0] = 1;
                test.LongArray[0, 1] = 2;
                test.LongArray[0, 2] = 3;
                test.LongArray[0, 3] = 4;
                test.LongArray[1, 0] = 1;
                test.LongArray[1, 1] = 2;
                test.LongArray[1, 2] = 3;
                test.LongArray[1, 3] = 4;
                test.LongArray[2, 0] = 1;
                test.LongArray[2, 1] = 2;
                test.LongArray[2, 2] = 3;
                test.LongArray[2, 3] = 4;

                test.StringArray[0, 0] = "Hello,";
                test.StringArray[0, 1] = "I love you,";
                test.StringArray[1, 0] = "won't you tell me";
                test.StringArray[1, 1] = "your name?";

                test.StructArray[0, 0] = new BasicTestStruct()
                {
                    Id = 0
                };
                test.StructArray[0, 1] = new BasicTestStruct()
                {
                    Id = 1
                };
                test.StructArray[1, 0] = new BasicTestStruct()
                {
                    Id = 2
                };
                test.StructArray[1, 1] = new BasicTestStruct()
                {
                    Id = 3
                };

                test.LongDoubleArray[0, 0] = 1.1;
                test.LongDoubleArray[0, 1] = 2.2;
                test.LongDoubleArray[1, 0] = 3.3;
                test.LongDoubleArray[1, 1] = 4.4;

                test.StructSequence.Add(new BasicTestStruct()
                {
                    Id = 1
                });

                test.StructSequence.Add(new BasicTestStruct()
                {
                    Id = 2
                });

                test.StructSequence.Add(new BasicTestStruct()
                {
                    Id = 3
                });

                result = dataWriter.Write(test);

                System.Threading.Thread.Sleep(1000);

                if (!useListener)
                {
                    waitSet.DetachCondition(statusCondition);
                }

                participant.DeleteContainedEntities();
                domainFactory.DeleteParticipant(participant);
            }

            participantService.Shutdown();
            OpenDDSharp.Ace.Fini();

            Console.WriteLine("Press ENTER to finish the test.");
            Console.ReadLine();
        }