public static void AssemblyInitialize(TestContext context) { Ace.Init(); RtpsDiscovery disc = new RtpsDiscovery(RTPS_DISCOVERY); Assert.AreEqual(RTPS_DISCOVERY, disc.Key); ParticipantService.Instance.AddDiscovery(disc); ParticipantService.Instance.DefaultDiscovery = RTPS_DISCOVERY; Assert.AreEqual(RTPS_DISCOVERY, ParticipantService.Instance.DefaultDiscovery); ParticipantService.Instance.SetRepoDomain(RTPS_DOMAIN, RTPS_DISCOVERY); ParticipantService.Instance.SetRepoDomain(RTPS_OTHER_DOMAIN, RTPS_DISCOVERY); InfoRepoDiscovery infoRepo = new InfoRepoDiscovery(INFOREPO_DISCOVERY, "corbaloc::localhost:12345/DCPSInfoRepo"); ParticipantService.Instance.AddDiscovery(infoRepo); infoRepo.BitTransportIp = "localhost"; infoRepo.BitTransportPort = 0; ParticipantService.Instance.SetRepoDomain(INFOREPO_DOMAIN, INFOREPO_DISCOVERY); _supportProcess = new SupportProcessHelper(context); _infoProcess = _supportProcess.SpawnDCPSInfoRepo(); System.Threading.Thread.Sleep(1000); Factory = ParticipantService.Instance.GetDomainParticipantFactory(); Assert.IsFalse(TransportRegistry.Instance.Released); Assert.IsFalse(ParticipantService.Instance.IsShutdown); }
public static void AssemblyInitialize(TestContext context) { Ace.Init(); RtpsDiscovery disc = new RtpsDiscovery(RTPS_DISCOVERY); ParticipantService.Instance.AddDiscovery(disc); ParticipantService.Instance.DefaultDiscovery = RTPS_DISCOVERY; Assert.AreEqual(RTPS_DISCOVERY, ParticipantService.Instance.DefaultDiscovery); ParticipantService.Instance.SetRepoDomain(RTPS_DOMAIN, RTPS_DISCOVERY); ParticipantService.Instance.SetRepoDomain(RTPS_OTHER_DOMAIN, RTPS_DISCOVERY); InfoRepoDiscovery infoRepo = new InfoRepoDiscovery(INFOREPO_DISCOVERY, "file://" + INFOREPO_IOR); ParticipantService.Instance.AddDiscovery(infoRepo); ParticipantService.Instance.SetRepoDomain(INFOREPO_DOMAIN, INFOREPO_DISCOVERY); _supportProcess = new SupportProcessHelper(context); _infoProcess = _supportProcess.SpawnDCPSInfoRepo(); System.Threading.Thread.Sleep(1000); Factory = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSDebugLevel", "10", "-ORBLogFile", "LogFile.log", "-ORBDebugLevel", "10"); Assert.IsFalse(TransportRegistry.Instance.Released); Assert.IsFalse(ParticipantService.Instance.IsShutdown); }
public override void RunExample(string[] args) { base.RunExample(args); DomainParticipantFactory factory = DomainParticipantFactory.GetInstance(Bootstrap.CreateInstance()); DomainParticipant dp = factory.CreateParticipant(); // Implicitly create TypeSupport and register type: Topic <Greeting> tp = dp.CreateTopic <Greeting>("Greetings Topic"); // Create the publisher Publisher pub = dp.CreatePublisher(); /* DataWriter<Greeting> dw = pub.CreateDataWriter(tp); * */ DataWriter <Greeting> dw = pub.CreateDataWriter <Greeting>(tp, pub.GetDefaultDataWriterQos(), null, null); // Create the subscriber Subscriber sub = dp.CreateSubscriber(); DataReaderListener <Greeting> ls = new MyListener(); /*DataReader<Greeting> dr = sub.CreateDataReader(tp);*/ DataReader <Greeting> dr = sub.CreateDataReader <Greeting>(tp, sub.GetDefaultDataReaderQos(), ls, null); /* * // Now Publish some piece of data * Greeting data = new Greeting("Hello, World with DDS."); * Console.WriteLine("Sending data:\"{0}\"", data.Value); * dw.Write(data); * //and check that the reader has this data * dr.WaitForHistoricalData(10, TimeUnit.SECONDS); * */ int i = 0; // Now Publish some piece of data //Greeting data = new Greeting("Hola Mundo"+ i.ToString()); for (i = 0; i < 1; i++) { Greeting data = new Greeting("Hola Mundo" + i.ToString()); Console.WriteLine("Sending data:\"{0}\"", data.Value); dw.Write(data); dr.WaitForHistoricalData(1500, TimeUnit.MILLISECONDS); } //and check that the reader has this data //dr.WaitForHistoricalData(10000, TimeUnit.SECONDS); dp.Close(); }
static void Main(string[] args) { _dpf = DomainParticipantFactory.Instance; ErrorHandler.checkHandle(_dpf, "Domain Participant Factory"); _dp = _dpf.CreateParticipant(Domain); //Initialize QOS pQos = new PublisherQos(); dwQos = new DataWriterQos(); fdmDataType = new FDMTypeSupport(); string FDMDATATypeName = fdmDataType.TypeName; ReturnCode status = fdmDataType.RegisterType(_dp, FDMDATATypeName); ErrorHandler.checkStatus(status, "FDMDATA: Cannot Register Type"); //Create FDMDATA Topic fdmDataTopic = _dp.FindTopic("FDMDATA", Duration.FromMilliseconds(1000)); if (fdmDataTopic == null) { fdmDataTopic = _dp.CreateTopic("FDMDATA", FDMDATATypeName); } ErrorHandler.checkHandle(fdmDataTopic, "Cannot Create Topic FDMDATA"); //Get Publisher QOS and Set Partition Name _dp.GetDefaultPublisherQos(ref pQos); pQos.Partition.Name = new String[1]; pQos.Partition.Name[0] = PartitionName; //Create Subscriber for FDMDATA Topic Publisher = _dp.CreatePublisher(pQos); ErrorHandler.checkHandle(Publisher, "Cannot Create FDMDATA Publisher"); //Get Data Writer QOS and Set History Depth Publisher.GetDefaultDataWriterQos(ref dwQos); ErrorHandler.checkHandle(dwQos, "Cannot get Data Writer Qos"); dwQos.History.Depth = 5; dwQos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos; //Create DataReader for FDMDATA Topic parentWriter = Publisher.CreateDataWriter(fdmDataTopic, dwQos); ErrorHandler.checkHandle(parentWriter, "Cannot Create FDMDATA Data Writer"); //Narrow abstract parentWriter into its typed representative fdmDataWriter = parentWriter as FDMDataWriter; ErrorHandler.checkHandle(fdmDataWriter, "Cannot Narrow FDMDATA Data Writer"); fdmData = new FDM(); while (true) { StartPublish(); Console.WriteLine("Publishing data! "); Thread.Sleep(10); } }
static void Main(string[] args) { _dpf = DomainParticipantFactory.Instance; ErrorHandler.checkHandle(_dpf, "Domain Participant Factory"); _dp = _dpf.CreateParticipant(Domain); //Initialize QOS sQos = new SubscriberQos(); drQos = new DataReaderQos(); fdmDataType = new FDMTypeSupport(); string FDMDATATypeName = fdmDataType.TypeName; ReturnCode status = fdmDataType.RegisterType(_dp, FDMDATATypeName); ErrorHandler.checkStatus(status, "FDMDATA: Cannot Register Type"); //Create FDMDATA Topic fdmDataTopic = _dp.FindTopic("FDMDATA", Duration.FromMilliseconds(1000)); if (fdmDataTopic == null) { fdmDataTopic = _dp.CreateTopic("FDMDATA", FDMDATATypeName); } ErrorHandler.checkHandle(fdmDataTopic, "Cannot Create Topic FDMDATA"); //Get Subscriber QOS and Set Partition Name _dp.GetDefaultSubscriberQos(ref sQos); sQos.Partition.Name = new String[1]; sQos.Partition.Name[0] = PartitionName; //Create Subscriber for FDMDATA Topic Subscriber = _dp.CreateSubscriber(sQos); ErrorHandler.checkHandle(Subscriber, "Cannot Create FDMDATA Subscriber"); //Get Data Reader QOS and Set History Depth Subscriber.GetDefaultDataReaderQos(ref drQos); ErrorHandler.checkHandle(drQos, "Cannot get Data Reader Qos"); drQos.History.Depth = 5; drQos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos; //Create DataReader for FDMDATA Topic parentReader = Subscriber.CreateDataReader(fdmDataTopic, drQos); ErrorHandler.checkHandle(parentReader, "Cannot Create FDMDATA Data Reader"); //Narrow abstract parentReader into its typed representative fdmDataReader = parentReader as FDMDataReader; ErrorHandler.checkHandle(fdmDataReader, "Cannot Narrow FDMDATA Data Reader"); // drQos.Durability.Kind = DurabilityQosPolicyKind.TransientLocalDurabilityQos; fdmData = new FDM(); //Rececieve Loop while (true) { StartReceive(); Console.WriteLine("abc: " + fdmData.aa.ToString()); } }
/// <summary> /// Create Domain Participant /// </summary> /// <param name="partitionName">Create the participant and assign the partition name.</param> public void createParticipant(String partitionName) { dpf = DomainParticipantFactory.Instance; dpQos = new DomainParticipantQos(); dpf.GetDefaultParticipantQos(ref dpQos); ErrorHandler.checkHandle(dpf, "DomainParticipantFactory.Instance"); participant = dpf.CreateParticipant(null, dpQos); ErrorHandler.checkHandle(participant, "DomainParticipantFactory.CreateParticipant"); this.partitionName = partitionName; }
private static void TestOnInconsistentTopic() { DomainParticipantFactory dpf = ParticipantService.Instance.GetDomainParticipantFactory(); DomainParticipant participant = dpf.CreateParticipant(RTPS_DOMAIN); if (participant == null) { throw new ApplicationException("Failed to create the participant."); } BindRtpsUdpTransportConfig(participant); Subscriber subscriber = participant.CreateSubscriber(); if (subscriber == null) { throw new ApplicationException("Failed to create the subscriber."); } AthleteTypeSupport support = new AthleteTypeSupport(); string typeName = support.GetTypeName(); ReturnCode result = support.RegisterType(participant, typeName); if (result != ReturnCode.Ok) { throw new ApplicationException("Failed to register the type." + result.ToString()); } Topic topic = participant.CreateTopic(nameof(TestOnInconsistentTopic), typeName); if (topic == null) { throw new ApplicationException("Failed to create the topic."); } DataReader reader = subscriber.CreateDataReader(topic); if (reader == null) { throw new ApplicationException("Failed to create the reader."); } while (true) { System.Threading.Thread.Sleep(100); } }
private static void TestOnSubscriptionLostDisconnected() { DomainParticipantFactory dpf = ParticipantService.Instance.GetDomainParticipantFactory(); DomainParticipant participant = dpf.CreateParticipant(INFOREPO_DOMAIN); if (participant == null) { throw new ApplicationException("Failed to create the participant."); } BindTcpTransportConfig(participant); Publisher publisher = participant.CreatePublisher(); if (publisher == null) { throw new ApplicationException("Failed to create the publisher."); } TestStructTypeSupport support = new TestStructTypeSupport(); string typeName = support.GetTypeName(); ReturnCode result = support.RegisterType(participant, typeName); if (result != ReturnCode.Ok) { throw new ApplicationException("Failed to register the type." + result.ToString()); } Topic topic = participant.CreateTopic("TestOnSubscriptionLostDisconnected", typeName); if (topic == null) { throw new ApplicationException("Failed to create the topic."); } DataWriter writer = publisher.CreateDataWriter(topic); if (writer == null) { throw new ApplicationException("Failed to create the writer."); } while (true) { System.Threading.Thread.Sleep(100); } }
private static void RegisterDomain(Topic <T> topicInstance, string domain) { lock (_locker) { DomainParticipantFactory dpf = DomainParticipantFactory.Instance; ErrorHandler.CheckHandle(dpf, "DDS.DomainParticipantFactory.Instance"); var dpQos = new DomainParticipantQos(); dpf.GetDefaultParticipantQos(ref dpQos); topicInstance.Participant = dpf.CreateParticipant(domain, dpQos) ?? (dpf.LookupParticipant(domain) ?? dpf.CreateParticipant(domain, dpQos)); if (topicInstance.Participant == null) { throw new Exception("DDS NOT started, please start / restart your DDS!"); } } }
public void BasicRoundTrip() { var serializer = new JsonCommonSerializer(); var factory = DomainParticipantFactory.get_instance(); var serverQos = new DomainParticipantQos(); factory.get_default_participant_qos(serverQos); //serverQos.transport_builtin.mask = 0; // disable built-in transports //serverQos.property_qos.value serverQos.discovery.initial_peers.from_array(new[] { "1@localhost" }); var serverParticipant = factory.create_participant(0, serverQos, null, StatusMask.STATUS_MASK_NONE); var serverTransport = serverParticipant.GenerateTransportSource("serverResponse", "clientRequest"); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService <EverytingToOwin.IMyService>(new EverytingToOwin.MyService()); var clientQos = new DomainParticipantQos(); factory.get_default_participant_qos(clientQos); clientQos.discovery.initial_peers.from_array(new[] { "1@localhost" }); var clientParticipant = factory.create_participant(0, clientQos, null, StatusMask.STATUS_MASK_NONE); var clientTransport = clientParticipant.GenerateTransportSource("clientRequest", "serverResponse"); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface <EverytingToOwin.IMyService>(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); factory.delete_participant(ref clientParticipant); serverRouter.Dispose(); serverTransport.Dispose(); factory.delete_participant(ref serverParticipant); }
static void Main(string[] args) { Ace.Init(); DomainParticipantFactory dpf = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSConfigFile", "rtps.ini"); DomainParticipant participant = dpf.CreateParticipant(42); if (participant == null) { throw new Exception("Could not create the participant"); } // Include your program here participant.DeleteContainedEntities(); dpf.DeleteParticipant(participant); ParticipantService.Instance.Shutdown(); Ace.Fini(); }
static void Main(string[] args) { bool isPublisher = true; if (args != null && args.Length > 0) { isPublisher = !args[0].ToLowerInvariant().Equals("--sub") && !args[0].ToLowerInvariant().Equals("--subscriber"); } Ace.Init(); DomainParticipantFactory dpf = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSConfigFile", "rtps.ini", "-DCPSDebugLevel", "10", "-ORBLogFile", "LogFile.log", "-ORBDebugLevel", "10"); if (dpf == null) { throw new ApplicationException("Domain participant factory could not be created."); } DomainParticipant participant = dpf.CreateParticipant(42); if (dpf == null) { throw new ApplicationException("Domain participant could not be created."); } if (isPublisher) { TestPublisher(participant); } else { TestSubscriber(participant); } Console.WriteLine("Shutting down... that's enough for today."); participant.DeleteContainedEntities(); dpf.DeleteParticipant(participant); ParticipantService.Instance.Shutdown(); Ace.Fini(); }
private void InitializeDDS() { //string id = usuario.Id; string id = "0"; int.TryParse(id, out domainId); // Create the DomainFactory factory = DomainParticipantFactory.GetInstance(Bootstrap.CreateInstance()); // Create the DomainParticipant with reference to the configuration file with the domain ID dp = factory.CreateParticipant(domainId); // Console.WriteLine("Domain ID = {0} has been created", domainId); // Implicitly create TypeSupport and register type: tp = dp.CreateTopic <ChatMessage>("Greetings Topic"); // Create the subscriber sub = dp.CreateSubscriber(); // Create a Listener for the publishing data ls = new MyListener(backgroundWorker1, backgroundWorker2, backgroundWorker3, backgroundWorker4, backgroundWorker5, backgroundWorker6); ls2 = new MyListener2(); // Create the DataReader using the topic, politics of QoS for DataReader and implemented listener dr = sub.CreateDataReader <ChatMessage>(tp, sub.GetDefaultDataReaderQos(), ls, null); // Create the publisher pub = dp.CreatePublisher(); // Create the DataWriter using the topic specified //dw = pub.CreateDataWriter(tp); dw = pub.CreateDataWriter <ChatMessage>(tp, pub.GetDefaultDataWriterQos(), ls2, null); }
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"); }
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(); }
static void Main(string[] args) { int ownID = 1; string chatterName = null; int domain = DDS.DomainId.Default; string partitionName = "ChatRoom"; /* Options: Chatter [ownID [name]] */ if (args.Length > 0) { ownID = int.Parse(args[0]); if (args.Length > 1) { chatterName = args[1]; } } /* Create a DomainParticipantFactory and a DomainParticipant * (using Default QoS settings. */ DomainParticipantFactory dpf = DomainParticipantFactory.Instance; ErrorHandler.checkHandle(dpf, "DDS.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(); string nameServiceTypeName = nameServiceTS.TypeName; status = nameServiceTS.RegisterType( participant, nameServiceTypeName); ErrorHandler.checkStatus( status, "Chat.NameServiceTypeSupport.RegisterType"); /* Initialise Qos variables */ TopicQos reliableTopicQos = new TopicQos(); TopicQos settingTopicQos = new TopicQos(); PublisherQos pubQos = new PublisherQos(); DataWriterQos dwQos = new DataWriterQos(); DataWriterQos nsDwQos = new DataWriterQos(); /* Set the ReliabilityQosPolicy to RELIABLE. */ status = participant.GetDefaultTopicQos(ref reliableTopicQos); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.GetDefaultTopicQos"); 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. */ 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 (NameService)"); /* Adapt the default PublisherQos to write into the * "ChatRoom" Partition. */ status = participant.GetDefaultPublisherQos(ref pubQos); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.GetDefaultPublisherQos"); pubQos.Partition.Name = new string[1]; pubQos.Partition.Name[0] = partitionName; /* Create a Publisher for the chatter application. */ IPublisher chatPublisher = participant.CreatePublisher(pubQos); ErrorHandler.checkHandle( chatPublisher, "DDS.DomainParticipant.CreatePublisher"); /* Create a DataWriter for the ChatMessage Topic * (using the appropriate QoS). */ chatPublisher.GetDefaultDataWriterQos(ref dwQos); status = chatPublisher.CopyFromTopicQos(ref dwQos, reliableTopicQos); ErrorHandler.checkStatus(status, "DDS.Publisher.CopyFromTopicQos"); IDataWriter parentWriter = chatPublisher.CreateDataWriter(chatMessageTopic, dwQos); ErrorHandler.checkHandle( parentWriter, "DDS.Publisher.CreateDatawriter (chatMessage)"); /* Narrow the abstract parent into its typed representative. */ ChatMessageDataWriter talker = parentWriter as ChatMessageDataWriter; ErrorHandler.checkHandle( talker, "Chat.ChatMessageDataWriter"); /* Create a DataWriter for the NameService Topic * (using the appropriate QoS). */ status = chatPublisher.GetDefaultDataWriterQos(ref nsDwQos); ErrorHandler.checkStatus( status, "DDS.Publisher.GetDefaultDatawriterQos"); status = chatPublisher.CopyFromTopicQos(ref nsDwQos, settingTopicQos); ErrorHandler.checkStatus(status, "DDS.Publisher.CopyFromTopicQos"); WriterDataLifecycleQosPolicy writerDataLifecycle = nsDwQos.WriterDataLifecycle; writerDataLifecycle.AutodisposeUnregisteredInstances = false; IDataWriter nsParentWriter = chatPublisher.CreateDataWriter(nameServiceTopic, nsDwQos); ErrorHandler.checkHandle( nsParentWriter, "DDS.Publisher.CreateDatawriter (NameService)"); /* Narrow the abstract parent into its typed representative. */ NameServiceDataWriter nameServer = nsParentWriter as NameServiceDataWriter; ErrorHandler.checkHandle( nameServer, "Chat.NameServiceDataWriterHelper"); /* Initialize the NameServer attributes. */ NameService ns = new NameService(); ns.userID = ownID; if (chatterName != null) { ns.name = chatterName; } else { ns.name = "Chatter " + ownID; } /* Write the user-information into the system * (registering the instance implicitly). */ status = nameServer.Write(ns); ErrorHandler.checkStatus(status, "Chat.ChatMessageDataWriter.Write"); /* Initialize the chat messages. */ ChatMessage msg = new ChatMessage(); msg.userID = ownID; msg.index = 0; if (ownID == TERMINATION_MESSAGE) { msg.content = "Termination message."; } else { msg.content = "Hi there, I will send you " + NUM_MSG + " more messages."; } System.Console.WriteLine("Writing message: \"" + msg.content + "\""); /* Register a chat message for this user * (pre-allocating resources for it!!) */ InstanceHandle userHandle = talker.RegisterInstance(msg); /* Write a message using the pre-generated instance handle. */ status = talker.Write(msg, userHandle); ErrorHandler.checkStatus(status, "Chat.ChatMessageDataWriter.Write"); Thread.Sleep(1000); /* Write any number of messages . */ for (int i = 1; i <= NUM_MSG && ownID != TERMINATION_MESSAGE; i++) { msg.index = i; msg.content = "Message no. " + i; Console.WriteLine("Writing message: \"" + msg.content + "\""); status = talker.Write(msg, userHandle); ErrorHandler.checkStatus(status, "Chat.ChatMessageDataWriter.Write"); Thread.Sleep(1000); /* do not run so fast! */ } /* Leave the room by disposing and unregistering the message instance */ status = talker.Dispose(msg, userHandle); ErrorHandler.checkStatus( status, "Chat.ChatMessageDataWriter.Dispose"); status = talker.UnregisterInstance(msg, userHandle); ErrorHandler.checkStatus( status, "Chat.ChatMessageDataWriter.unregister_instance"); /* Also unregister our name. */ status = nameServer.UnregisterInstance(ns, InstanceHandle.Nil); ErrorHandler.checkStatus( status, "Chat.NameServiceDataWriter.unregister_instance"); /* Remove the DataWriters */ status = chatPublisher.DeleteDataWriter(talker); ErrorHandler.checkStatus( status, "DDS.Publisher.DeleteDatawriter (talker)"); status = chatPublisher.DeleteDataWriter(nameServer); ErrorHandler.checkStatus(status, "DDS.Publisher.DeleteDatawriter (nameServer)"); /* Remove the Publisher. */ status = participant.DeletePublisher(chatPublisher); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.DeletePublisher"); /* Remove the Topics. */ status = participant.DeleteTopic(nameServiceTopic); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.DeleteTopic (nameServiceTopic)"); status = participant.DeleteTopic(chatMessageTopic); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.DeleteTopic (chatMessageTopic)"); /* Remove the DomainParticipant. */ status = dpf.DeleteParticipant(participant); ErrorHandler.checkStatus( status, "DDS.DomainParticipantFactory.DeleteParticipant"); }
public void Benchmark() { var serializer = new JsonCommonSerializer(); var factory = DomainParticipantFactory.get_instance(); var serverQos = new DomainParticipantQos(); factory.get_default_participant_qos(serverQos); serverQos.discovery.initial_peers.from_array(new[] { "1@localhost" }); const int maxBufferSize = 1 << 24; // 16MB serverQos.receiver_pool.buffer_size = 65530; // max allowed //serverQos.discovery_config.publication_writer_publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS; serverQos.discovery_config.publication_writer_publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME; //serverQos.discovery_config.subscription_writer_publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS; serverQos.discovery_config.subscription_writer_publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME; var len = serverQos.property_qos.value.length + 3; serverQos.property_qos.value.ensure_length(len, len); serverQos.property_qos.value.set_at(len - 3, new Property_t { name = "dds.transport.UDPv4.builtin.recv_socket_buffer_size", value = maxBufferSize.ToString() }); serverQos.property_qos.value.set_at(len - 2, new Property_t { name = "dds.transport.UDPv4.builtin.parent.message_size_max", value = serverQos.receiver_pool.buffer_size.ToString() }); serverQos.property_qos.value.set_at(len - 1, new Property_t { name = "dds.transport.UDPv4.builtin.send_socket_buffer_size", value = serverQos.receiver_pool.buffer_size.ToString() }); //serverQos.resource_limits.type_code_max_serialized_length = maxBufferSize; serverQos.resource_limits.type_object_max_serialized_length = maxBufferSize; serverQos.resource_limits.type_object_max_deserialized_length = maxBufferSize; var serverParticipant = factory.create_participant(0, serverQos, null, StatusMask.STATUS_MASK_NONE); var controller = serverParticipant.lookup_flowcontroller(FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME); var flowProperty = new FlowControllerProperty_t(); controller.get_property(flowProperty); flowProperty.token_bucket.period = Duration_t.from_millis(50); controller.set_property(flowProperty); var serverTransport = serverParticipant.GenerateTransportSource("serverResponse", "clientRequest"); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService <ISumService>(new SumService()); var clientQos = new DomainParticipantQos(); factory.get_default_participant_qos(clientQos); clientQos.discovery.initial_peers.from_array(new[] { "1@localhost" }); clientQos.receiver_pool.buffer_size = 65530; // max allowed //clientQos.discovery_config.publication_writer_publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS; clientQos.discovery_config.publication_writer_publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME; //clientQos.discovery_config.subscription_writer_publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS; clientQos.discovery_config.subscription_writer_publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME; len = clientQos.property_qos.value.length + 3; clientQos.property_qos.value.ensure_length(len, len); clientQos.property_qos.value.set_at(len - 3, new Property_t { name = "dds.transport.UDPv4.builtin.recv_socket_buffer_size", value = maxBufferSize.ToString() }); clientQos.property_qos.value.set_at(len - 2, new Property_t { name = "dds.transport.UDPv4.builtin.parent.message_size_max", value = clientQos.receiver_pool.buffer_size.ToString() }); clientQos.property_qos.value.set_at(len - 1, new Property_t { name = "dds.transport.UDPv4.builtin.send_socket_buffer_size", value = clientQos.receiver_pool.buffer_size.ToString() }); //clientQos.resource_limits.type_code_max_serialized_length = maxBufferSize; clientQos.resource_limits.type_object_max_serialized_length = maxBufferSize; clientQos.resource_limits.type_object_max_deserialized_length = maxBufferSize; var clientParticipant = factory.create_participant(0, clientQos, null, StatusMask.STATUS_MASK_NONE); controller = clientParticipant.lookup_flowcontroller(FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME); flowProperty = new FlowControllerProperty_t(); controller.get_property(flowProperty); flowProperty.token_bucket.period = Duration_t.from_millis(50); controller.set_property(flowProperty); var clientTransport = clientParticipant.GenerateTransportSource("clientRequest", "serverResponse"); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface <ISumService>(); const int randCnt = 100; var rand = new Random(42); var randoms = new int[randCnt]; for (int i = 0; i < randCnt; i++) { randoms[i] = rand.Next(10000000, 20000000); } var sw = new Stopwatch(); long timeFromClient = 0, timeToClient = 0; const int cnt = 1000; for (int j = 0; j < cnt; j++) { sw.Start(); var sum = proxy.Sum(randoms).Result; sw.Stop(); Assert.Equal(randoms.Sum(), sum); for (int i = 0; i < randCnt; i++) { randoms[i] = rand.Next(10000000, 20000000); } var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result; timeFromClient += times.Item1; timeToClient += Stopwatch.GetTimestamp() - times.Item2; } _testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds); _testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10); _testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10); //sw.Reset(); //var tree = new SumServiceTree(); //SumServiceTree.FillTree(tree, rand, 2); //_testOutputHelper.WriteLine("Starting large message transfer."); //sw.Start(); //var result = proxy.Increment(tree).Result; //sw.Stop(); //Assert.Equal(tree.Leaf + 1, result.Leaf); //_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds); clientRouter.Dispose(); clientTransport.Dispose(); factory.delete_participant(ref clientParticipant); serverRouter.Dispose(); serverTransport.Dispose(); factory.delete_participant(ref serverParticipant); }
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(); }
public OpenDDSharpService() { _config = ServiceLocator.Current.GetInstance <IConfigurationService>(); _disc = new RtpsDiscovery(RTPS_DISCOVERY) { ResendPeriod = new TimeValue { Seconds = 1 }, SedpMulticast = true }; ParticipantService.Instance.AddDiscovery(_disc); ParticipantService.Instance.DefaultDiscovery = RTPS_DISCOVERY; long ticks = DateTime.Now.Ticks; string configName = "openddsharp_rtps_interop_" + ticks.ToString();; string instName = "internal_openddsharp_rtps_transport_" + ticks.ToString();; _tConfig = TransportRegistry.Instance.CreateConfig(configName); _inst = TransportRegistry.Instance.CreateInst(instName, "rtps_udp"); _rui = new RtpsUdpInst(_inst); _tConfig.Insert(_inst); TransportRegistry.Instance.GlobalConfig = _tConfig; ParticipantService.Instance.SetRepoDomain(0, RTPS_DISCOVERY); _domainFactory = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSDebugLevel", "10", "-ORBLogFile", "LogFile.log", "-ORBDebugLevel", "10"); _participant = _domainFactory.CreateParticipant(0); if (_participant == null) { throw new Exception("Could not create the participant"); } ShapeTypeTypeSupport support = new ShapeTypeTypeSupport(); ReturnCode result = support.RegisterType(_participant, TYPE_NAME); if (result != ReturnCode.Ok) { throw new Exception("Could not register type: " + result.ToString()); } _squareTopic = _participant.CreateTopic(SQUARE_TOPIC_NAME, TYPE_NAME); if (_squareTopic == null) { throw new Exception("Could not create square topic"); } _circleTopic = _participant.CreateTopic(CIRCLE_TOPIC_NAME, TYPE_NAME); if (_circleTopic == null) { throw new Exception("Could not create circle topic"); } _triangleTopic = _participant.CreateTopic(TRIANGLE_TOPIC_NAME, TYPE_NAME); if (_triangleTopic == null) { throw new Exception("Could not create triangle topic"); } _publisher = _participant.CreatePublisher(); if (_publisher == null) { throw new Exception("Could not create publisher"); } _subscriber = _participant.CreateSubscriber(); if (_subscriber == null) { throw new Exception("Could not create subscriber"); } _shapeWaitSets = new List <ShapeWaitSet>(); _shapeDynamics = new List <ShapeDynamic>(); _cfCircleCount = 0; _cfSquareCount = 0; _cfTriangleCount = 0; }
static void Main(string[] args) { Ace.Init(); DomainParticipantFactory dpf = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSConfigFile", "rtps.ini"); DomainParticipant participant = dpf.CreateParticipant(42); if (participant == null) { throw new Exception("Could not create the participant"); } MessageTypeSupport support = new MessageTypeSupport(); ReturnCode result = support.RegisterType(participant, support.GetTypeName()); if (result != ReturnCode.Ok) { throw new Exception("Could not register type: " + result.ToString()); } Topic topic = participant.CreateTopic("MessageTopic", support.GetTypeName()); if (topic == null) { throw new Exception("Could not create the message topic"); } Subscriber subscriber = participant.CreateSubscriber(); if (subscriber == null) { throw new Exception("Could not create the subscriber"); } DataReader reader = subscriber.CreateDataReader(topic); if (reader == null) { throw new Exception("Could not create the message data reader"); } MessageDataReader messageReader = new MessageDataReader(reader); while (true) { StatusMask mask = messageReader.StatusChanges; if ((mask & StatusKind.DataAvailableStatus) != 0) { List <Message> receivedData = new List <Message>(); List <SampleInfo> receivedInfo = new List <SampleInfo>(); result = messageReader.Take(receivedData, receivedInfo); if (result == ReturnCode.Ok) { bool messageReceived = false; for (int i = 0; i < receivedData.Count; i++) { if (receivedInfo[i].ValidData) { Console.WriteLine(receivedData[i].Content); messageReceived = true; } } if (messageReceived) { break; } } } System.Threading.Thread.Sleep(100); } Console.WriteLine("Press a key to exit..."); Console.ReadKey(); participant.DeleteContainedEntities(); dpf.DeleteParticipant(participant); ParticipantService.Instance.Shutdown(); Ace.Fini(); }
static void Main(string[] args) { string partitionName = "ChatRoom"; int domain = DDS.DomainId.Default; /* Options: MessageBoard [ownID] */ /* Messages having owner ownID will be ignored */ string[] parameterList = new string[1]; if (args.Length > 0) { parameterList[0] = args[0]; } else { parameterList[0] = "0"; } /* Create a DomainParticipantFactory and a DomainParticipant * (using Default QoS settings. */ DomainParticipantFactory dpf = DomainParticipantFactory.Instance; ErrorHandler.checkHandle( dpf, "DDS.DomainParticipantFactory.Instance"); IDomainParticipant parentDP = dpf.CreateParticipant( domain, null, StatusKind.Any); ErrorHandler.checkHandle( parentDP, "DDS.DomainParticipantFactory.CreateParticipant"); /* Register the required datatype for ChatMessage. */ ChatMessageTypeSupport chatMessageTS = new ChatMessageTypeSupport(); string chatMessageTypeName = chatMessageTS.TypeName; ReturnCode status = chatMessageTS.RegisterType(parentDP, 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(parentDP, nameServiceTypeName); ErrorHandler.checkStatus( status, "Chat.NameServiceTypeSupport.RegisterType"); /* Register the required datatype for NamedMessage. */ NamedMessageTypeSupport namedMessageTS = new NamedMessageTypeSupport(); ErrorHandler.checkHandle( namedMessageTS, "new NamedMessageTypeSupport"); string namedMessageTypeName = namedMessageTS.TypeName; status = namedMessageTS.RegisterType(parentDP, namedMessageTypeName); ErrorHandler.checkStatus( status, "Chat.NamedMessageTypeSupport.RegisterType"); /* Narrow the normal participant to its extended representative */ ExtDomainParticipant participant = new ExtDomainParticipant(parentDP); /* Initialise QoS variables */ TopicQos reliableTopicQos = new TopicQos(); TopicQos settingTopicQos = new TopicQos(); SubscriberQos subQos = new SubscriberQos(); /* Set the ReliabilityQosPolicy to RELIABLE. */ status = participant.GetDefaultTopicQos(ref reliableTopicQos); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.GetDefaultTopicQos"); 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. */ 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 (NameService)"); /* Create a multitopic that substitutes the userID * with its corresponding userName. */ ITopic namedMessageTopic = participant.CreateSimulatedMultitopic( "Chat_NamedMessage", namedMessageTypeName, "SELECT userID, name AS userName, index, content " + "FROM Chat_NameService NATURAL JOIN Chat_ChatMessage " + "WHERE userID <> %0", parameterList); ErrorHandler.checkHandle( namedMessageTopic, "ExtDomainParticipant.create_simulated_multitopic"); /* Adapt the default SubscriberQos to read from the "ChatRoom" Partition. */ status = participant.GetDefaultSubscriberQos(ref subQos); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.GetDefaultSubscriberQos"); subQos.Partition.Name = new string[1]; subQos.Partition.Name[0] = partitionName; /* Create a Subscriber for the MessageBoard application. */ ISubscriber chatSubscriber = participant.CreateSubscriber(subQos); ErrorHandler.checkHandle( chatSubscriber, "DDS.DomainParticipant.CreateSubscriber"); /* Create a DataReader for the NamedMessage Topic * (using the appropriate QoS). */ IDataReader parentReader = chatSubscriber.CreateDataReader( namedMessageTopic); ErrorHandler.checkHandle( parentReader, "DDS.Subscriber.CreateDatareader"); NamedMessageDataReader chatAdmin = parentReader as NamedMessageDataReader; /* Print a message that the MessageBoard has opened. */ System.Console.WriteLine( "MessageBoard has opened: send a ChatMessage " + "with userID = -1 to close it....\n"); bool terminated = false; NamedMessage[] messages = null;; SampleInfo[] infos = null; while (!terminated) { /* Note: using read does not remove the samples from * unregistered instances from the DataReader. This means * that the DataRase would use more and more resources. * That's why we use take here instead. */ status = chatAdmin.Take( ref messages, ref infos, SampleStateKind.Any, ViewStateKind.Any, InstanceStateKind.Alive); ErrorHandler.checkStatus( status, "Chat.NamedMessageDataReader.take"); foreach (NamedMessage msg in messages) { if (msg.userID == TERMINATION_MESSAGE) { System.Console.WriteLine("Termination message received: exiting..."); terminated = true; } else { System.Console.WriteLine("{0}: {1}", msg.userName, msg.content); } } status = chatAdmin.ReturnLoan(ref messages, ref infos); ErrorHandler.checkStatus(status, "Chat.ChatMessageDataReader.ReturnLoan"); System.Threading.Thread.Sleep(100); } /* Remove the DataReader */ status = chatSubscriber.DeleteDataReader(chatAdmin); ErrorHandler.checkStatus( status, "DDS.Subscriber.DeleteDatareader"); /* Remove the Subscriber. */ status = participant.DeleteSubscriber(chatSubscriber); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.DeleteSubscriber"); /* Remove the Topics. */ status = participant.DeleteSimulatedMultitopic(namedMessageTopic); ErrorHandler.checkStatus( status, "DDS.ExtDomainParticipant.DeleteSimulatedMultitopic"); status = participant.DeleteTopic(nameServiceTopic); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.DeleteTopic (nameServiceTopic)"); status = participant.DeleteTopic(chatMessageTopic); ErrorHandler.checkStatus( status, "DDS.DomainParticipant.DeleteTopic (chatMessageTopic)"); /* Remove the DomainParticipant. */ status = dpf.DeleteParticipant(parentDP); ErrorHandler.checkStatus( status, "DDS.DomainParticipantFactory.DeleteParticipant"); }
static void Main(string[] args) { Ace.Init(); DomainParticipantFactory dpf = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSConfigFile", "rtps.ini"); DomainParticipant participant = dpf.CreateParticipant(42); if (participant == null) { throw new Exception("Could not create the participant"); } MessageTypeSupport support = new MessageTypeSupport(); ReturnCode result = support.RegisterType(participant, support.GetTypeName()); if (result != ReturnCode.Ok) { throw new Exception("Could not register type: " + result.ToString()); } Topic topic = participant.CreateTopic("MessageTopic", support.GetTypeName()); if (topic == null) { throw new Exception("Could not create the message topic"); } Publisher publisher = participant.CreatePublisher(); if (publisher == null) { throw new Exception("Could not create the publisher"); } DataWriter writer = publisher.CreateDataWriter(topic); if (writer == null) { throw new Exception("Could not create the data writer"); } MessageDataWriter messageWriter = new MessageDataWriter(writer); Console.WriteLine("Waiting for a subscriber..."); PublicationMatchedStatus status = new PublicationMatchedStatus(); do { result = messageWriter.GetPublicationMatchedStatus(ref status); System.Threading.Thread.Sleep(500); }while (status.CurrentCount < 1); Console.WriteLine("Subscriber found, writting data...."); messageWriter.Write(new Message { Content = "Hello, I love you, won't you tell me your name?" }); Console.WriteLine("Press a key to exit..."); Console.ReadKey(); participant.DeleteContainedEntities(); dpf.DeleteParticipant(participant); ParticipantService.Instance.Shutdown(); Ace.Fini(); }