programmer’s guide - twin oaks computing, inc · iii coredx data distribution service –...

Post on 01-May-2018

230 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CoreDX DDS

Data Distribution Service The leading Small Footprint DDS Middleware

Programmer’s Guide Version4.0

January2017

ii

Copyright2008-2017TwinOaksComputing,Inc,755MaletaLn,Ste203CastleRock,Colorado80108U.S.A.Allrightsreserved.

ThisdocumentdescribeshowtoinstallandusetheCoreDXDDSsoftware.

CoreDX,CoreDXDDS,andtheCoreDXDDSlogoaretrademarksofTwinOaksComputing,Inc.ObjectManagementGroup,OMG,andDDSaretrademarksoftheObjectManagementGroup.Allotherproductsorcompanynamesmentionedareusedforidentificationpurposesonly,andmaybetrademarksoftheirrespectiveowners.

DISCLAIMEROFWARRANTY.THISDOCUMENTISPROVIDED"ASIS”ANDALLEXPRESSORIMPLIEDCONDITIONS,REPRESENTATIONSANDWARRANTIES,INCLUDINGANYIMPLIEDWARRANTYOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEORNON-INFRINGEMENT,AREDISCLAIMED,EXCEPTTOTHEEXTENTTHATSUCHDISCLAIMERSAREHELDTOBELEGALLYINVALID.

iii

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Preface

CoreDXDDSisasmall-footprint,high-performancecommunicationsmiddlewarecompliantwiththeOMGDataDistributionService(DDS)standard.CoreDXDDSsupportsmultiplehardwarearchitecturesandoperatingsystems,andisintendedtofacilitatethedevelopmentofrobust,nearreal-time,highlydistributedsystems.

ThismanualdescribeshowtoinstallandusetheCoreDXDDSsoftware.Itisfordeveloperswhowanttointegrateahigh-performance,OMGcompliantdatadistributionmiddlewareserviceintotheirapplication.

HowthisGuideisOrganized

ThisProgrammer’sGuidecontainsanumberofChaptersorganizedinParts.ThefirstPartprovidesanoverviewoftheDDStechnologyandCoreDXDDS.Part2providesguidanceoninstallingCoreDXDDS,andwalksthereaderthroughcreatingasimplefirstCoreDXDDSapplication.

ThenextseveralchaptersinPart3makeupthemajorityofthisdocument,andgointodetailondifferentaspectsofCoreDXDDSfeaturesandfunctionality.Thisincludes:DDSEntities,developingpublishingandsubscribingapplications,QualityofService(QoS)settings,communicationstatuses,datainstancesandsamples,dataarchitecture,built-intopics,andtheCoreDXDDStransports.

ThelastfewchaptersincludeadiscussionofextensionsprovidedbyCoreDXDDSsuchastheloggingfacility,CoreDXDDSlicensemanagement,troubleshootingassistance,andfinallybackgroundaboutTwinOaksComputing.

RelatedDocumentation

CoreDXDDSTypeSystem

CoreDXRPCoverDDS

CoreDXDDSSecure

CoreDXDDSReferenceManuals

iv

IntendedAudience

ThisdocumentisintendedforsoftwaredeveloperswhoareintegratingtheCoreDXDDSsoftwareintotheirapplication(s).Theguideassumesthatthereaderiscompetentinprogramminglanguagesandsoftwaredevelopmentconcepts.CoreDXDDSsupportsmultipleprogramminglanguages,andthisguideincludesexamplesinCandC++.

TypographicConventions

Typeface Meaning Examples

Courier Example code struct StringMsg { string msg; };

Courier Example Commands gunzip –c coredx-2.x.tar.gz

Figure0-1:TypographicConventions

Feedback

TwinOaksComputingwelcomesyourcomments.Weareinterestedinimprovingourproductsandwewelcomeyourcommentsandsuggestions.Youcanprovideemailfeedbackaboutthisdocumenttodocuments@twinoakscomputing.com.

v

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TableofContents

Preface iiiHowthisGuideisOrganized.........................................................................................................iiiRelatedDocumentation................................................................................................................iiiIntendedAudience.......................................................................................................................ivTypographicConventions.............................................................................................................ivFeedback.......................................................................................................................................iv

Part1: Introduction............................................................................................................................2Chapter1 AnIntroductiontoCoreDXDDS...................................................................................4

1.1 WhyDDS?...........................................................................................................................41.2 ThecaseforMiddleware....................................................................................................41.3 ThecaseforPublishSubscribeDDS....................................................................................51.4 ThecaseforCoreDXDDS..................................................................................................11

Part2: GettingStarted.....................................................................................................................16Chapter2 InstallingCoreDXDDS.................................................................................................18

2.1 InstallationRequirements................................................................................................182.2 CoreDXDDSDistributionContents...................................................................................212.3 CoreDXDDSInstallationProcedure..................................................................................232.4 CompilingforadifferentTargetPlatform........................................................................23

Chapter3 FirstCoreDXDDSApplication.....................................................................................253.1 UsingaLicense.................................................................................................................253.2 WritingtheApplication....................................................................................................253.3 CompilingYourApplicationwithCoreDXDDS.................................................................293.4 RunningYourApplicationwithCoreDXDDS....................................................................32

Chapter4 ExampleCoreDXDDSApplications.............................................................................334.1 EnvironmentSetup...........................................................................................................334.2 Example1:TheBasic“HelloWorld”Applications............................................................344.3 Example2:PerformanceTests........................................................................................354.4 Example3:Filtering..........................................................................................................354.5 Example4:DynamicTypes...............................................................................................35

vi

4.6 Example5:NoThreads.....................................................................................................354.7 Example6:RPC.................................................................................................................354.8 Example7:QoSProvider..................................................................................................364.9 Example8:ShapesDemonstration...................................................................................36

Chapter5 AdvancedCompileOptions........................................................................................375.1 LinuxandotherUNIX-variantOperatingSystems............................................................375.2 WindowsOperatingSystem.............................................................................................41

Part3: CoreDXDDSProgrammingConcepts...................................................................................47Chapter6 DDSEntities................................................................................................................50

6.1 DDSEntityHierarchy........................................................................................................506.2 DDSEntityCommonOperations......................................................................................516.3 DDSEntityQualityofService............................................................................................526.4 DDSStatus,Listeners,ConditionsandWaitSets...............................................................52

Chapter7 DevelopingaPublishingApplication..........................................................................547.1 SummaryofDevelopingaPublishingApplication............................................................547.2 TheData...........................................................................................................................547.3 ThePublishingApplication...............................................................................................547.4 AvailableQoSSettings......................................................................................................597.5 AvailableListeners............................................................................................................62

Chapter8 DevelopingaSubscribingApplication........................................................................648.1 SummaryofDevelopingaSubscribingApplication..........................................................648.2 TheData...........................................................................................................................648.3 TheSubscribingApplication.............................................................................................648.4 SampleStatusInformation(SampleInfo).........................................................................708.5 AdditionalSubscriber/DataReaderFeatures..................................................................728.6 QoSPolicies......................................................................................................................748.7 AvailableListeners............................................................................................................76

Chapter9 Topics.........................................................................................................................809.1 Overview..........................................................................................................................809.2 Built-InTopics...................................................................................................................819.3 ContentFilteredTopics....................................................................................................84

vii

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

9.4 MultiTopics......................................................................................................................88Chapter10 InstancesandSamples...............................................................................................90

10.1 Overview..........................................................................................................................9010.2 PublishingData.................................................................................................................9210.3 SubscribingtoData..........................................................................................................9310.4 InstanceLifecycles............................................................................................................9310.5 DataCache........................................................................................................................97

Chapter11 ApplicationDataTypes.............................................................................................10211.1 Overview........................................................................................................................10211.2 WhyDefinetheDataTypes?..........................................................................................10211.3 DataTypesandDiscovery..............................................................................................10311.4 DataArchitecture...........................................................................................................10311.5 DataTypeDefinition.......................................................................................................10311.6 DataDefinitionSyntax....................................................................................................10411.7 IDLandXMLLanguageMappings...................................................................................10511.8 CreatingDataTypes.......................................................................................................10711.9 ConfiguringDataTypes..................................................................................................10911.10 UsingtheCoreDXDDSDataTypeCompiler...................................................................11411.11 GeneratedCode.............................................................................................................117

Chapter12 QualityofServiceFeatures......................................................................................12012.1 QoSCompatibility...........................................................................................................12112.2 QoSMutability................................................................................................................12212.3 QualityofServiceDetails................................................................................................122

Chapter13 CommunicationStatus.............................................................................................13613.1 CommunicationStatusDetails.......................................................................................13813.2 ApplicationAccesstoCommunicationStatus................................................................150

Part4: CoreDXDDSExtensions......................................................................................................166Chapter14 CoreDXDDSLogging.................................................................................................168Chapter15 CoreDXDDSTransport.............................................................................................171

15.1 Overview........................................................................................................................171Chapter16 CoreDXDDSDiscovery.............................................................................................185

viii

16.1 OverviewofCoreDXDDSDiscovery...............................................................................18516.2 DiscoveringDomainParticipants....................................................................................18616.3 MatchingDataReadersandDataWriters........................................................................18716.4 StaticDiscovery..............................................................................................................18916.5 CentralizedDiscovery.....................................................................................................19116.6 WaitforDiscovery..........................................................................................................19516.7 DiscoveryandDeterministicMachines..........................................................................196

Chapter17 ConfiguringReliabilityProtocol................................................................................20017.1 ReliabilityProtocol.........................................................................................................20017.2 ReliabilityQoSConfiguration..........................................................................................204

Chapter18 DynamicTypes.........................................................................................................20718.1 Overview........................................................................................................................20718.2 SubscribewithDynamicTypes.......................................................................................20718.3 PublishwithDynamicTypes...........................................................................................208

Chapter19 ThreadingOptions....................................................................................................20919.1 Overview........................................................................................................................20919.2 ConfiguringThreadingOptions......................................................................................209

Chapter20 TransmitBuffers.......................................................................................................21320.1 Overview........................................................................................................................21320.2 DynamicTransmitBuffers..............................................................................................21320.3 StaticTransmitBuffers...................................................................................................215

Chapter21 ReceiveBuffers.........................................................................................................21721.1 Overview........................................................................................................................217

Chapter22 DataBatching...........................................................................................................219Chapter23 Licensing...................................................................................................................222

23.1 DevelopmentLicenses....................................................................................................22223.2 Run-timeLicenses...........................................................................................................223

Chapter24 Troubleshooting.......................................................................................................22624.1 GeneralTroubleshootingTools......................................................................................22624.2 NoCommunicationsbetweenDDSapplications............................................................22624.3 Missingorlostsamples..................................................................................................227

ix

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

24.4 TypeSupportversionmismatch......................................................................................23024.5 Can’tfindithere?...........................................................................................................230

Chapter25 AboutTwinOaksComputing....................................................................................232Chapter26 ContactInformation.................................................................................................234

x

xi

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TableofFigures

Figure0-1:TypographicConventions....................................................................................................ivFigure1-1:Middleware.........................................................................................................................5Figure1-2:ClientServerArchitecture...................................................................................................6Figure1-3:PublishSubscribeArchitecture...........................................................................................7Figure1-4:ExampleDDSUsage............................................................................................................7Figure1-5:DDSArchitecture...............................................................................................................11Figure2-1:CoreDXDDSDirectoryStructure.......................................................................................22Figure6-1:DDSEntityHierarchy.........................................................................................................50Figure10-1:RegisterInstancesExample.............................................................................................94Figure11-1:ExampleIDLfile.............................................................................................................108Figure11-2:IDLkeysexample...........................................................................................................114Figure12-1:ConfiguringQoS-SampleCCode.................................................................................120Figure13-1:InconsistentTopicStatusStructure..............................................................................139Figure13-2:SampleRejectedStatusStructure.................................................................................141Figure13-3:LivelinessChangedStatusStructure.............................................................................142Figure13-4:RequestedDeadlineMissedStatusStructure...............................................................143Figure13-5:RequestedIncompatibleQoSStatusStructure.............................................................144Figure13-6:SampleLostStatusStructure........................................................................................145Figure13-7:SubscriptionMatchedStatusStructure........................................................................146Figure13-8:LivelinessLostStatusStructure.....................................................................................147Figure13-9:OfferedDeadlineMissedStatusStructure....................................................................148Figure13-10:OfferedIncompatibleQoSStatusStructure................................................................149Figure13-11:PublicationMatchedStatusStructure........................................................................150Figure13-12:ListenerHierarchy.......................................................................................................152Figure13-13:ListenerExampleCCode.............................................................................................156Figure13-14:ListenerExampeC++Code..........................................................................................157Figure13-15:ConditionExampleCcode..........................................................................................163Figure13-16:ConditionExampleC++code......................................................................................164Figure17:StandardDiscovery(peer-to-peer)architecture..............................................................191Figure18:CentralizedDiscoveryarchitecture..................................................................................192Figure19:ExampleCentralizedDiscoverydeployment....................................................................195Figure17-1:ExampleDDSUsage......................................................................................................201Figure17-2:ExampleDDSUsage......................................................................................................202Figure23-1:ExampleCoreDXDDSlicensefile..................................................................................222Figure24-1:ExampleCoreDXDDSlicensefile..................................................................................230

xii

xiii

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TableofTables

Table2-1:CoreDXDDSArchitecturesandOperatingSystems...........................................................18Table2-2:CoreDXDDSLanguagesandCompilers..............................................................................20Table3-1:SampleIDLFile...................................................................................................................26Table4-1:Example-Runningcdxenv.sh.............................................................................................34Table5-1:CoreDXDDSLibraries(UNIXOperatingSystems)...............................................................37Table5-2:CoreDXDDSLibraries(WindowsOperatingSystem).........................................................41Table5-3:WindowsDynamicLibraryDependencies..........................................................................45Table7-1:QoSPoliciesforPublishingEntities....................................................................................59Table7-2:ListenersforPublishingEntities.........................................................................................62Table8-1:QoSPoliciesforSubscribingEntities..................................................................................74Table8-2:ListenersforSubscribingEntities.......................................................................................76Table9-1:TopicVariants.....................................................................................................................80Table9-2:Built-inTopics.....................................................................................................................81Table9-3:ParticipantBuilt-inDataType............................................................................................82Table9-4:TopicBuilt-inDataType.....................................................................................................83Table9-5:PublicationBuilt-inDataType............................................................................................83Table9-6:SubscriptionBuilt-inDataType..........................................................................................84Table9-7:create_contentfilteredtopic()parameters.........................................................................85Table9-8:ValidConditionOperatorsforContentFilters....................................................................85Table9-9:CreatingaContentFilteredTopic........................................................................................87Table10-1:InstanceExample.............................................................................................................92Table10-2:InstanceExample.............................................................................................................97Table11-1:BasicUserDefinedTypes...............................................................................................104Table11-2:ConstructedUserDefinedTypes....................................................................................105Table11-3:PrimitiveDataTypeMapping.........................................................................................106Table11-4:coredx_ddlcommandlineoptions.................................................................................114Table11-5:Generatedsourcecodefilenames.................................................................................118Table12-1:QoSSummary.................................................................................................................122Table13-1:CommunicationStatuses................................................................................................136Table13-2:ListenerMethodSignatures...........................................................................................153Table14-1:CoreDXDDSLoggingFlags..............................................................................................169Table14-2:LoggingQoSConfigurationExample..............................................................................169Table15-1:UDPTransportConfigurationParameters......................................................................177Table15-2:UDPTransportEnvironmentVariables...........................................................................178Table15-3:TCPTransportEnvironmentVariables...........................................................................181Table15-4:LMTTransportEnvironmentVariables...........................................................................183Table16-1:CodeExampleofpeer_participantsQoS........................................................................190Table17-1:CoreDXDDSRTPS_ProtocolQoSPolicy..........................................................................204Table20-1:InstanceExample...........................................................................................................213

iii

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

2

Part1: Introduction

ThissectionprovidesanintroductionoftheDataDistributionService(DDS)andtheCoreDXDDSimplementationfromTwinOaksComputing,Inc.

3

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

4

Chapter1 AnIntroductiontoCoreDXDDS

WelcometoCoreDXDDS,ahigh-performance,small-footprintimplementationoftheOMGDataDistributionService(DDS)standard.TheCoreDXDDSData-Centric,Publish-Subscribemessaginginfrastructureprovideshigh-throughput,low-latencydatacommunications.

ThischapterprovidesanoverviewoftheDataDistributionService(DDS),howapplicationsmightuseDDStomeettheircommunicationrequirements,andfeaturesoftheCoreDXDDSproduct.

1.1 WhyDDS?

Today’senterprisesystems,embeddedsystems,andallsystemsinbetween,needflexible,openinformationsystems.Mostsystemsspanmultipletechnologies,hardwareplatforms,operatingsystems,andprogramminglanguages.Inaddition,componentsofthesesystemshavereal-timerequirements.CoreDXDDSisanopenstandards-based,communicationmiddlewaresolutiontomeettheneedsofthesereal-timedistributedsystems.

1.2 ThecaseforMiddleware

MiddlewareisaclassofsoftwarethatexistsbetweenanapplicationandtheOperatingSystem.Indeeplyembeddedenvironments,middlewareexistsbetweenthefunctionalsoftwareandanetworkstackofthedevice.ItprovidesusefulcapabilitiesthatareaboveandbeyondthosefoundinstandardOperatingSystems.InthecaseofCoreDXDDS,themiddlewareprovidesafacilityforbothpublish-subscribeandclient-servercommunications.Figure1-1illustrateswheremiddlewarecomponentsfitintheapplication,andhowtheylogicallybridgeacrossmultipleoperatingsystemsandhardwarearchitectures.

5

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure1-1:Middleware

ApplicationsthatemployacommunicationsmiddlewarelikeCoreDXDDSrealizemanybenefits.Therequirementsandcomplexityofdatacommunicationsinadistributedsystemaremetbythemiddlewarecomponent-leavingdevelopersmoretimetofocusontheimportantapplicationlogic.CoreDXDDSmiddlewaresupportsmanyoperatingsystemsandhardwarearchitectures-thetaskofportingcomplexcommunicationssoftwareisalreadycomplete.

1.3 ThecaseforPublishSubscribeDDS

Manycommunicationmiddlewaretechnologiesareavailable.Mostarebasedonafunctionalmodel.Forexample,RPC(RemoteProcedureCall)andCORBA(ObjectRequestBroker)aretwoexamplesofmiddlewarethatallowfunctioncallstobedistributedacrossthenetworkbetweenaclientandaserver.However,thesearchitecturesleadtotightcouplingbetweentheclientandtheserver;thismakesthesesystemsdifficulttoextend.

Middleware

OperatingSystem HARDWA

RE

Application

OperatingSystem HARDWA

RE

CoreDXDDSProgrammer’sGuide

6

Figure1-2:ClientServerArchitecture

Theclient-serverarchitectureisappropriateforcentralizeddataprocessingandworkswellinsomesystemsandsomeusecases.Insomeclient-servertechnologies,thedrawbacksareincreasedintegrationcostsfornewcapabilitiesandpotentialsinglepointoffailure.

AnalternativetothisapproachisthePublish-SubscribearchitectureembodiedinDDS.Thisarchitecturepromotesaloosecouplingbetweendataproducersanddataconsumers.Thearchitectureisflexibleanddynamic;itiseasytoadaptandextendsystemstochangingenvironmentsandrequirements.Figure1-3illustratestheDDSPublishSubscribearchitecturewheremultiplePublishersandSubscribersexchangestronglytypeddatathroughacommonTopic.ThecommunicationsarecontrolledbyaQualityofServicemodel.

Client Server

7

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure1-3:PublishSubscribeArchitecture

Figure1-4isanexampleofhowDDSmightbeappliedinasystem.Thisexamplehasseveralsourcesof“rawdata”,adataprocessorthatperformssomeprocessingontherawdatatoproduce“processeddata”,severalendusersworkingwiththeprocesseddata,andanadministrativeuserperforminganalysis,maintenance,orauditingfunctions.

Figure1-4:ExampleDDSUsage

Publisher

Subscriber

Subscriber

Subscriber

DataType

Data

QoS

Topic

Publisher

CoreDXDDSProgrammer’sGuide

8

Inthisexample,thedarkerblueboxesrepresentapplicationscommunicatingoveraDDSnetwork.Theseapplicationsmightberunningtogetheron1host,ortheymightbedistributedovermultiplehosts.ADDSapplicationsimplypublishesorsubscribestotheirdata,withoutconcernforwhat,ifanything,mightbeontheotherendofitscommunications.Anyoftheapplicationscanbedynamicallyremoved(andnewapplicationsmaybeadded)withoutimpactingtheexistingnetwork.

Becausemanysystemsincludesomenaturalpublish-subscribeusecasesaswellassomenaturalclient-serverusecases,theDDSstandardsincludebothcommunicationmechanisms.Thisdocumentfocusesonthepublish-subscribeinterfacetoDDS.Forinformationonprogrammingwiththeremoteprocedurecall(RPC)orrequestreplyAPIs,pleaseusetheCoreDXDDSRPCoverDDSProgrammer’sGuide.

1.3.1 DDSisanOpenStandardDDSisanopenspecification(documentedbymultiplestandards)managedbytheObjectManagementGroup(OMG).TheOMGisaninternational,openmembership,non-profitorganizationthatdevelopsandmanagescomputerindustryspecifications.Hundredsoforganizations,includingsoftwareend-usersandcommercialvendors,makeuptheOMG.Togethertheydevelopandmanagemanyofthestandardswidelyusedinthecomputerindustrytoday.ThesetofDataDistributionService(DDS)standardsisanexampleofoneofthetechnologystandardsmanagedbytheOMG.OtherexamplesincludetheUnifiedModelingLanguage(UML),ModelDrivenArchitecture(MDA)andtheCommonObjectRequestBrokerArchitecture(CORBA).

Thereareseveraladvantagestousingatechnologythatconformstoanopenstandard,andmoreadvantagesifthatopenstandardismanagedbyanopenmembershiporganizationliketheOMG.First,anopenstandardpromotesinteroperability.Anyone,eveniftheyarenotconnectedwiththemanagingorganization,canpickupanOpenStandardandwriteaconformingapplication.Second,openstandardsreducethedependenceonaparticularvendor.Whenanopenstandardproductisavailablefrommultiplevendors,theconsumercaneasilychangebetweenthem.Finally,anyonecanjointhemanagingorganizationandvoteonthedirectionandadvancementofthetechnology.InthecaseofDDS,thismeansvendorsandusers,bothpublicandprivate,caninfluencethefutureofthetechnology.

9

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

1.3.2 DDSisMorethanaCommunicationsMiddlewareTheDDSstandardsspecifythemechanismformovingdata–atypicalcommunicationsmiddlewaretechnologystandard.However,DDSissomuchmore.Inadditiontocommunications,DDSprovidesadvanceddatamanagement,storage,organization,filtering,redundancy,extensibility,andsecurity.Witharichsetoffeatures,interoperabilityacrosslanguages,operatingsystems,hardwareplatforms,andimplementations,DDSprovidesarobust,secureinfrastructurefoundationforyoursmall-scale,large-scale,enterprise,embedded,andeverythinginbetweensoftwaresystem.

1.3.3 RemoteProcedureCall(RPC)inadditiontoPublish-SubscribeTheDataDistributionServiceisapublish-subscribetechnology,whichprovidesaflexible,looselycoupledarchitecturesuitableformanyreal-timeapplications.However,manysophisticatedprojectsareanaturalmixofpublish-subscribeandclient-server(orRPC)requirements.

TheDDSStandardsincludeAPI’sforpublish-susbscribe,request-response,andRPC–allimplementedontopoftheoriginalDDSpublish-subscribearchitecture.DDSrequest-responseandRPChavesomeuniquefeaturesoverotherclient-servertypemiddleware,includingautomaticdiscovery,security,andtheabilitytousethefullsetofDDSQualityofService(QoS)configurations.

TheCoreDXDDSRPCAPIisfullydescribedintheCoreDXDDSRPCProgrammer’sGuide.

1.3.4 DDSisflexibleandscalableApplicationscommunicatingwithDDSmightberunningtogetheron1host,ortheymightbedistributedovermultiplehosts,eachwithdifferentarchitecturesandoperatingsystems.ApplicationsusingDDSforcommunicationsdonotneedtoknowthedetailsofwherethereotherapplicationsareresiding,oreveniftheyexist.

ThediscoverymechanismbuiltintoDDSallowsapplicationstocomeandgofromaDDSnetworkwithoutrequiringanychangestotheapplicationsorthenetwork.Thismeansanewsystemcanbebroughtintothenetwork,andstartsendingorreceivingdata,withoutanychangestoexistingapplications.

CoreDXDDSProgrammer’sGuide

10

1.3.5 DDSissecureTheDDSSecuritystandardcontainsacompletestate-of-the-artsecuritysolutionthatiscompletelyintegratedintotheDDSprotocols(notsimplylayeredontopofSSL).DDSSecurityincludes:Identification,Authentication,AccessControl,Integrity,andConfidentiality,allowingthedesignerfullflexibilityonatopic-by-topiclevel.

SecurityconfigurationandusageisdocumentedintheCoreDXDDSSecurityProgrammer’sGuide.

1.3.6 DDSFeaturesADDSapplicationcanbeapublisherofdata,asubscriberofdata,orboth.

APublisherisresponsiblefordatadistribution.Itmaypublishdataofdifferentdatatypes.TheapplicationusesatypedDataWriterattachedtothepublishertocommunicatethedatatobepublished.BoththePublisherandtheDataWriterhaveaQualityofService(QoS)thataffectsthebehaviorofthepublication.

ASubscriberisresponsibleforreceivingpublisheddataandmakingitavailabletothereceivingapplication.Itmayreceivedataofdifferentdatatypes.TheapplicationusesatypedDataReaderattachedtothesubscribertoaccessthedata.BoththeSubscriberandDataReaderhaveaQoSthataffectsthebehaviorofthesubscription.ThesubscribingapplicationcanchoosetoblockwaitingfordatausingWaitSetsorreceivedataasynchronously,usingListeners.

ATopicfitsbetweenpublicationsandsubscriptions.Subscriptionsmustbeabletorefertospecificpublications.Atopicfulfillsthispurpose:itassociatesaname,adata-type,andaQoSrelatedtothedataitself.

Whenanapplicationwantstopublishdataofagiventype,itmustuseaPublisherandDataWriterwithallthecharacteristicsofthedesiredpublication.Whenanapplicationwantstosubscribetodataofagiventype,itmustuseaSubscriberandDataReaderwithallthecharacteristicsofthedesiredsubscription.

ThefollowingfiguredepictsthecommonDDSobjectsusedinexchangingdata.

11

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure1-5:DDSArchitecture

ThefollowingdescribestheactionsdepictedinFigure1-5.

1. DataReadersandDataWritersareassociatedwithaTopic2. ThepublishingapplicationcallsDataWriter::write()towritethedata3. ThePublisherpublishesthedata4. TheSubscriberreceivesthedata5. TheListenernotifiesthesubscribingapplicationofavailabledata6. ThesubscribingapplicationcallsDataReader::read()toaccessthedata

1.4 ThecaseforCoreDXDDS

TheCoreDXDDSprovidesaquality,high-performance,verysmallfootprintimplementationoftheDDSstandards,includingtheoriginalpublish-subscribeDDSAPI,RTPSwireprotocol,X-Types,RPCoverDDS,andDDSSecurity.

1.4.1 CoreDXDDSisFastCoreDXDDSwasbuiltfromthegroundupwithperformanceinmind.TheengineeringstaffatTwinOaksComputinghasalonghistoryofwritingandmaintainingreal-timeandnearreal-timesoftware,andthisexpertisewasusedincreatingCoreDXDDS.CoreDXDDSiswrittenin‘C’(withadditional

Deleted: Figure1-5

CoreDXDDSProgrammer’sGuide

12

applicationlanguagebindingsavailable)forlowoverheadandmemorysavings.TheCoreDXDDSbaselineistestedandenhancedforperformanceateverystepofthedevelopmentprocess.TheresultisaqualityDDSimplementationwithextremelylowlatencyandhighthroughputcapacity.

CoreDXDDSdataaggregation,multi-coredatapipeline,andlowlatencyeventnotificationprovideforthroughputinthe+900Mbpsrangeandlatenciesbelow75usecovera1GbpsETHERNETnetwork.Butdon’ttakeourwordforit.TheCoreDXDDSreleaseincludessourcecodeforexamplebenchmarkingapplications.UsetheseexamplestocompileyourownbenchmarktestsandseehowCoreDXDDSperformsinyourenvironment,withyourdata.

1.4.2 CoreDXDDSisSmallTheCoreDXDDSproductis100%designedanddevelopedbyTwinOaksComputingtomeettheOMG’sDDSspecification.Thereisnohistoricalcode,nocodeborrowedfromtheopensourcecommunity,nocoderetrofittedtomeettheCoreDXDDSrequirements.Thisallowsustodeliveraquality,fully-functionalDDSimplementationwiththesmallestfootprint.Ourentirecorelibraryislessthan500KB,andrunsinenvironmentswithaslittleas100KBofRAM.ThefullCoreDXDDSimplementationisdeployedonFPGA’s,DSP’s,PLC’s,ECU’sandotherembeddedenvironments.

ThissmalllibrarysizecomeswithaproportionallysmallLineofCodeCount,perfectforsafetycriticalapplicationsrequiringDO-178Bcertification.

CoreDXDDSismodularandcontainsadditionalrun-timememorytuningparameters.SpaceconstrainedprojectscanselectcomponentsofCoreDXDDStomeettheirrequirements,andtunethosecomponentstoreduceunnecessarymemoryutilization.

Forthoseenvironmentsthatareevensmaller:truemicrocontrollers,CoreDXDDSMicrorequiresnomorethan8KofRAM,allowingthebenefitoftheinteroperabilityDDSprotocolsdowntothecomponentlevelofanysystem.

CoreDXDDSMicroisdocumentedintheCoreDXDDSMicroProgrammer’sGuide.

13

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

1.4.3 CoreDXDDSisProven&RobustThesmallfootprintCoreDXDDSsoftwarehasover10yearsofdeploymentusageinawidevarietyofmission-critical,andbusiness-critialapplications.

Withover1milliondeployedinstancesaroundtheworldandinspace,connectingcomponentsinsurgicaldevices,militaryandcommercialvehicles,spaceexplorationplatforms,electricalgrids,CoreDXDDShasaproventrackrecordofreliability,robustness,andcompententtechnicalandbusinesssupport.

1.4.4 CoreDXDDSisSecureCoreDXDDScomplieswiththeDDSSecuritystandards,providingintegratedandsophisticatedsecurityfeaturesthatarefullyconfigurable.Usingstate-of-the-artsecurityalgorithms,TheDDSSecuritystandardwasdesignedtomeettherequirementsofmilitaryandcriticalnationalinfrastructuresystems.

SystemdesignersmaychoosetousethestandardscompliantTwinOaksComputingdevelopedsecurityplug-insforidentification,authentication,accesscontrol,integrity,andconfidentiality,ordeveloptheirownwiththestandardizedplug-inAPI.

1.4.5 CoreDXDDSUsesMulti-CoreTechnologiesHardwareismovingtomultiplecoretechnology.Evenembeddedprocessorsareshippingwithmorethanonecore.Thispresentsachallengetoapplicationdevelopers,becausemakinguseofmultiplecoresrequirescomplexcodethatisdifficultandexpensivetodevelopandmaintain.Thesolution:useamultithreadedcommunicationsmiddlewarelikeCoreDXDDS.

CoreDXDDSwasarchitectedfromthestarttotakeadvantageofmulti-coreenvironments.Withadvancedthreadingandprotections,eachCoreDXDDSparticipantwilluseaminimumof3cores,andtypicalCoreDXDDSapplicationswillusebetween4and8cores.Thesearesinglethreadedapplications,takingadvantageofquad-coreandhigherhardware,justbyusingCoreDXDDSfordatacommunications.

1.4.6 CoreDXDDSisSelfContainedInordertouseCoreDXDDSforcommunications,theapplicationlinksintheappropriateCoreDXDDSlibrariesandthatisit.Withnodaemonsandnooperatingsystemservicesthatneedtobestartedandmaintained,thereis

CoreDXDDSProgrammer’sGuide

14

noplacefordatatobecome“stuck”orforcommunicationstatestobecomecorrupted.

1.4.7 CoreDXDDShasComprehensivePlatformSupportWiththewidearrayoflanguagebinding,operatingsystemandarchitecturesupport,CoreDXDDSrunsonawidevarietyofplatforms,fromenterpriseservers,tocommondesktopconfigurations,toembeddedenvironmentsandreal-timeoperatingsystems,toFPGA’sand‘bare-metal’configurations.SeetheInstallationRequirementssectionfordetailsonsupportedplatforms.

Ifyoudon’tfindyourspecificplatformlisted,justcontactus.Weofferextensiveengineeringservices,including(oftenfree!)customportstonewOperatingSystemsandArchitectures,andwellaslanguageports.Andwithourlowlineofcodecount,customportingisquickandeasy.

1.4.8 CoreDXDDShasagreatteambehinditAqualityDDSimplementationisimportant.Buttheorganizationbehindtheimplementationiscritical.Whenyoumakeacommitmenttopurchaseasoftwareproduct,youarenotonlyobtainingtherightstorunthesoftwarecontainedontheinstallationdisk(ordownloadedfromtheweb).Youarealsoobtainingsupportservices,trainingservices,andproductenhancementsforatleastthenextyear.

ThestaffatTwinOaksComputinghasbeendevelopingandsupportinglargesoftwaresystemsandglobalsoftwarecompaniesforover50years.WehaveworkedbesidesoldiersinKuwait,sailorsonboardaircraftcarriers,andotherwarfightersaroundtheworld.WehavesupportedcommercialIoTandIIoTcompanieswithmillionsofproductsdeployedworld-wide.Weunderstandnotonlytheimportanceofdeliveringasoftwareproductthatworks,butalsotheimportanceofhelpingcompaniesandtheirendusersmakethemostoftheirinvestment.

Wewilldothesameforyou.Giveusacallorsendusanemail.Wepromiseyouwillreceiveprompt,friendly,andhelpfulservice.

Formatted: Font:Italic

Deleted: InstallationRequirements

15

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

16

Part2: GettingStarted

TheGettingStartedsectionincludesinformationtoestablishadevelopmentenvironmentandbuildasimpleDDSpublisherandsubscriber.Thisprovidesaquickoverviewofthedevelopmentprocessandtheassociatedtools.

17

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

18

Chapter2 InstallingCoreDXDDS

ThischapterexplainshowtoinstallCoreDXDDSontoyourdevelopmentsystem.

2.1 InstallationRequirements

2.1.1 SupportedArchitecturesandOperatingSystems:CoreDXDDSisportedandbuiltforadditionalenvironmentsonaregularbasis.Thefollowingtableisintendedtoprovidethereaderwithanexamplesetofsupportedplatforms–itisnotacompletelist.

Table2-1:CoreDXDDSArchitecturesandOperatingSystems

OperatingSystem Architecture BuildTools

Linux2.6 x86(32bit),x86_64,atom gcc-4.3.2/glibc2.8

gcc-3.4.6/glibc2.3

sun4u gcc-4.1.2/glibc2.8

ARMv5,ARMv7,RaspberryPi,aarch64

gcc-4.1.2

PPC750,7400,440,e500 gcc

PPC32 gcc

MIPS32,MIPS64 gcc-3.4/uclibc0.9.29

Microblaze(softCPU) gcc-4.1

OSX10.7,10.8 X86,x86_64 Llvm

WindowsXP,Vista,7,and8

x86(32bit) VisualStudio2015,2012,2010,2008,2005

19

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

OperatingSystem Architecture BuildTools

x86_64(64bit) VisualStudio2015,2012,2010,2008

MinGW/gcc-3.4.5

WinCE,WindowsEmbedded

X86 VisualStudio2008

Arm VisualStudio2008

Solaris10 i86pc gcc-3.4.3

SunStudio12

sun4u gcc-3.4.3

SunStudio12

QNX6.4,6.5,6.6 x86(32bit) gcc-4.2.4

ARMv5 Gcc

VxWorks5.5 x86(32bit) gcc-4.1.2

ARMv7 Gnu

PPC405ep Diab

VxWorks6.6,6.8,6.9(RTPandDKM)

x86(32bit) gcc-4.1.2

PPC32 gcc

NexusWare12.3 x86 gcc

PowerPC440gx gcc

LynxOSSE6.0 x86 gcc-4.3

LynxOS178 PPC gcc

CoreDXDDSProgrammer’sGuide

20

OperatingSystem Architecture BuildTools

INTEGRITY178B PPC gcc

INTEGRITY11 PPC,x86,arm gcc

uClinux NIOS2(softcpu) gcc

ThreadX x86 gcc

PPCe300 gcc

Android x86 gcc

ARMv5 gcc

iOS ARMv7 Apple

DSP/BIOS TIDSP TI

2.1.2 SupportedLanguagesandCompilersCoreDXDDSisportedandbuiltforadditionalenvironmentsonaregularbasis.Thefollowingtableisintendedtoprovidethereaderwithanexamplesetofsupportedplatforms–itisnotacompletelist.

Table2-2:CoreDXDDSLanguagesandCompilers

Language Compiler CompilerVersion

C gcc

MSVisualStudio

MinGW/gcc

WindRiverDiab

multiple

VS2005,VS2008,VS2010,VS2012,VS2015,VC6

3.4.5

21

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

SunStudio12

GreenHillsMulti

C++ g++

MSVisualStudio

WindRiverDiab

SunStudio12

3.4.6,4.3.2,5.4.0

VS2005,VS2008,VS2010,VS2012,VS2015,VC6

Java javac 1.5

C# Mono(Linux)

VisualStudio

2.4

VS2008

2.2 CoreDXDDSDistributionContents

TheCoreDXDDSdistributionincludesatop-leveldirectory:coredx-version.Thistop-leveldirectoryisreferredtothroughoutthissdocumentasCOREDX_TOP,andcontainsthefollowingfilesandsubdirectories:

COPYRIGHT : File(s)describingtheCopyrightinformationforthisCoreDXDDSbaseline

examples : ContainsexampleCoreDXDDSapplications

host : ContainsthefilesrequiredfortheHOST(orbuild)machinesforallinstalledplatforms

README : File(s)describingtheCoreDXDDSversionandbuild

RELEASE_NOTES : InformationonchangesfrompreviousCoreDXDDSversions

scripts : Containshelpful,platformindependent,scripts

CoreDXDDSProgrammer’sGuide

22

target : ContainsthefilesrequiredfortheTARGET(ordeployment)machinesforallinstalledplatforms.

ThehostandtargetsubdirectoriescontaintheCoreDXDDSlibrariesandbinariesinplatformspecificdirectories.ThisconfigurationallowsyoutoinstallCoreDXDDSformultipleplatformsinoneCOREDX_TOPdirectory.Figure2-1showsthedirectorystructureunderCOREDX_TOP.

Figure2-1:CoreDXDDSDirectoryStructure

ThehostsubdirectorycontainstheHOSTtoolsforCoreDXDDS.TheHOSTtoolsincludeCoreDXDDSDDLcompilerandtheTwinOaksComputinglicensehostidutilityforalltheinstalledplatforms.Thehostsubdirectorycontainstwocopiesoftheseutilitiesforeacharchitectureinstalled.Forexample,considerthecoredx_ddlutilityforanx86Linuxsystemusingthegcc4.3compiler.Thisutilitycanbefoundintwolocations:

COREDX_TOP/host/bin/Linux_2.6_x86_gcc43_coredx_ddl COREDX_TOP/host/Linux_2.6_x86_gcc43/bin/coredx_ddl

ThetargetsubdirectorycontainstheTARGETtoolsforCoreDXDDS.TheTARGETtoolsincludetheCoreDXDDSheaderfiles,theCoreDXDDSlibrary

23

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

files,andtheTwinOaksComputinglicensehostidutility.TheCoreDXDDSlibrariesarelocatedarchitecture-namedsubdirectories.Forexample,considertheDDSlibraryforanx86Linuxsystemusingthegcc4.3compiler.Thislibraryislocated:

COREDX_TOP/target/Linux_2.6_x86_gcc43/lib/libdds.a

Section3.3providesexamplesforconfiguringMakefilestousetheCoreDXDDSdirectorystructure.

2.3 CoreDXDDSInstallationProcedure

OnceyouhaveobtainedCoreDXDDSfromTwinOaksComputing(orfromanEvaluationCDorUSBdrive),unpackthedistributionsomewhereonyoursystem.Forexample,onaUNIXsystemthiscommandwillextractthedistributionintothecurrentdirectory:

gunzip –c coredx-4.x.x-{platform}.tgz | tar xvf –

Or,forWindows:

unzipcoredx-4.x.x-{platform}.zip(It’sOKtooverwritefilesifpromptedhere.)

Andthat’sit.Thereisnoadditionalconfigurationrequired.

CustomersinstallingCoreDXDDSformultipleplatformscanunpackalltheCoreDXDDSreleasesintothesameCOREDX_TOPdirectory.CoreDXDDSusesplatform-specificdirectorynamesinordertoavoidconflictswhenworkingwithmultipleoperatingsystemsandhardwarearchitectures.

2.4 CompilingforadifferentTargetPlatform

CoreDXDDSsupportscrosscompilingforadifferenttargetplatform.Forexample,ifyouaredevelopingaVxWorksapplication,youmightbedeveloping(compiling)onaWindowsplatform.EachplatformreleaseofCoreDXDDScontainsboththeHOSTandTARGETtoolsforoneplatform,sointheaboveexample,youwillrequiretwoplatformversionsofCoreDXDDS,onefortheHOST(development)platform,andanotherfortheTARGET(run-time)platform.AllplatformversionsofCoreDXDDSmaybeinstalledintothesameCOREDX_TOPdirectory.

TheDDLcompiler(coredx_ddl)isaHOSTtoolthatgeneratescodetoberunontheTARGETplatform.WhentheendianoftheHOSTisdifferentthantheendianoftheTARGET,itisimportanttonotifytheDDLcompiler,sothatit

CoreDXDDSProgrammer’sGuide

24

cangeneratethecorrectmarshalandun-marshalcodefortheTARGETplatform.Thisisdoneusingthe“-e”optiontotheDDLcompiler.SeeChapter11.10foradditionalinformationontheDDLcompiler.

25

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter3 FirstCoreDXDDSApplication

ThischapterdescribeshowtousetheCoreDXDDStoolsandlibrariestointegratebasicDDScapabilitiesintoyourapplication.We’veprovidedasampledatatypeandapplicationthatisportedtoallCoreDXDDSsupportedlanguagesandplatformswiththedistribution(locatedinCOREDX_TOP/examples).Youcanusetheseexamplesorcreateyourownwhilegoingthoughthefollowingsteps.

OurexampleLinuxMakefileswerebuiltforgcc/g++.TheexamplescontaindifferentMakefilesforadditionalplatforms.AllexampleMakefilesusethreeenvironmentvariables:COREDX_TOP,COREDX_HOST,andCOREDX_TARGET.TheenvironmentscriptprovidedwithCoreDXDDSreleasescanhelpdeterminethecorrectsettingsforthesevariables(COREDX_TOP/scripts/cdxenv.shandcdxenv.bat).

3.1 UsingaLicense

CompilingwithCoreDXDDSrequiresadevelopmentorevaluationlicense.ThelicensemaybesetusingenvironmentvariablesorsoftwareAPI.(SoftwareAPIisdescribedintheLicensingsectionofthisguide.)Usetheenvironmentvariable:TWINOAKS_LICENSE_FILEtosetthelocationofyourCoreDXDDSlicense.

Forexample:

linux% export TWINOAKS_LICENSE_FILE=LICENSE_FILE

or

windows> set TWINOAKS_LICENSE_FILE=LICENSE_FILE

3.2 WritingtheApplication

WhileCoreDXDDSprovidesaconsistentlookingAPIacrossalllanguagebindings,thereareslightdifferencesinthecodegenerationandcompilinginstructions.

Formatted: Font:Italic

Deleted: Licensing

CoreDXDDSProgrammer’sGuide

26

3.2.1 The‘C’LanguageApplicationCreatethedatadefinitionforthedatatype(s)youwilluseforcommunications.ThesyntaxusedfordatadefinitioncomplieswiththeOMGIDLv4.0syntaxfordescribingdatatypes.

Note:Therearereferencesto“DDL”and“IDL”throughoutthisdocumentandtheCoreDXDDSexamples.PreviousversionsofCoreDXDDSusedtheterm“DataDefinitionLanguage”or“DDL”todescribedatatypes.DDLsimplyreferstothesubsetofIDLthatdefinesdatatypes.

Hereisthe“helloworld”exampleprovidedwiththedistribution:

Table3-1:SampleIDLFile

hello.ddl

struct StringMsg { string msg; };

CompiletheIDLtogeneratethetypespecificcodeusingtheCoreDXDDSdatatypecompiler.ThisrequiresyourTWINOAKS_LICENSE_FILEenvironmentvariablebesetasdescribedabove.AssumingthenameoftheIDLfileishello.ddl:

% COREDX_TOP/host/COREDX_HOST/bin/coredx_ddl –f hello.ddl

Thecompilationwillgeneratethefollowingfiles(namesarebasedontheIDLfilename):

hello.h and .c helloTypeSupport.h and .c helloDataReader.h and .c helloDataWriter.h and .c

Createcodetopublishdataofthisdatatype.OursampleHelloWorldpublisherislocatedinCOREDX_TOP/examples/hello_c/hello_pub.c.

27

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Createcodetosubscribetodataofthisdatatype.OursampleHelloWorldsubscriberislocatedinCOREDX_TOP/examples/hello_c/hello_sub.c.

3.2.2 The‘C++’LanguageApplicationCreatethedatadefinitionforthedatatype(s)youwilluseforcommunications.ThesyntaxusedfordatadefinitioncomplieswiththeOMGIDLv4.0syntaxfordescribingdatatypes.TheC++applicationusesthesameIDLtypedefinitionastheCprogramintheprevioussection.

CompiletheIDLtogeneratethetypespecificcodeusingtheCoreDXDDSdatatypecompiler.ThisrequiresyourTWINOAKS_LICENSE_FILEenvironmentvariablebesetasdescribedabove.AssumingthenameoftheDDLfileishello.ddl:

% COREDX_TOP/host/COREDX_HOST/bin/coredx_ddl –l cpp –f hello.ddl

Thecompilationwillgeneratethefollowingfiles(namesarebasedontheIDLfilename):

hello.hh and .cc helloTypeSupport.hh and .cc helloDataReader.hh and .cc helloDataWriter.hh and .cc

Createcodetopublishdataofthisdatatype.OursampleHelloWorldpublisherislocatedinCOREDX_TOP/examples/hello_cpp/hello_pub.cc.

Createcodetosubscribetodataofthisdatatype.OursampleHelloWorldsubscriberislocatedinCOREDX_TOP/examples/hello_cpp/hello_sub.cc.

3.2.3 The‘Java’LanguageApplicationCreatethedatadefinitionforthedatatype(s)youwilluseforcommunications.ThesyntaxusedfordatadefinitioncomplieswiththeOMGIDLv4.0syntaxfordescribingdatatypes.TheJavaapplicationusesthesameIDLtypedefinitionastheCprogramintheprevioussection.

CompiletheIDLtogeneratethetypespecificcodeusingtheCoreDXDDSdatatypecompiler.ThisrequiresyourTWINOAKS_LICENSE_FILEenvironmentvariablebesetasdescribedabove.AssumingthenameoftheIDLfileishello.ddl:

CoreDXDDSProgrammer’sGuide

28

% COREDX_TOP/host/COREDX_HOST/bin/coredx_ddl –l java –f hello.ddl

Thecompilationwillgeneratethefollowingfiles(namesarebasedonthedatatype(s)definedintheIDLfile):

StringMsg.java StringMsgTypeSupport.java StringMsgDataReader.java StringMsgDataWriter.java

Createcodetopublishdataofthisdatatype.OursampleHelloWorldpublisherislocatedinCOREDX_TOP/examples/hello_java/HelloPub.java.

Createcodetosubscribetodataofthisdatatype.OursampleHelloWorldsubscriberislocatedinCOREDX_TOP/examples/hello_java/HelloSub.java.

3.2.4 The‘C#’LanguageApplicationCreatethedatadefinitionforthedatatype(s)youwilluseforcommunications.ThesyntaxusedfordatadefinitioncomplieswiththeOMGIDLv4.0syntaxfordescribingdatatypes.TheC#applicationusesthesameIDLtypedefinitionastheCprogramintheprevioussection.

CompiletheIDLtogeneratethetypespecificcodeusingtheCoreDXDDSdatatypecompiler.ThisrequiresyourTWINOAKS_LICENSE_FILEenvironmentvariablebesetasdescribedabove.AssumingthenameoftheIDLfileishello.ddl:

% COREDX_TOP/host/COREDX_HOST/bin/coredx_ddl –l csharp –f hello.ddl

Thecompilationwillgeneratethefollowingfiles(namesarebasedonthedatatype(s)definedintheIDLfile):

StringMsg.cs StringMsgTypeSupport.cs StringMsgDataReader.cs StringMsgDataWriter.cs

Createcodetopublishdataofthisdatatype.OursampleHelloWorldpublisherislocatedinCOREDX_TOP/examples/hello_csharp/hello_pub.cs.

Createcodetosubscribetodataofthisdatatype.OursampleHelloWorldsubscriberislocatedinCOREDX_TOP/examples/hello_csharp/hello_sub.cs

29

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

3.3 CompilingYourApplicationwithCoreDXDDS

Compileyourapplication(s).OurHelloWorldexamplecreatestwoapplications,oneforthepublisherandoneforthesubscriber.Thisisnotnecessary,andiscompletelydependentonyourapplicationarchitecture.Yourapplicationwillrequiretheobjectsfromthegeneratedtypesupportcodeabove,aswellasyourpublisherand/orsubscribercode.

TheexamplesinthissectionassumeaUNIX-basedoperatingsystem.Compilingforotheroperatingsystemsmayrequireadditionalconsiderations.PleaserefertoPart2:Chapter5:AdvancedCompileOptionsforadditionalinformationoncompilingCoreDXDDSapplicationsforyourspecificoperatingsystem.

3.3.1 The‘C’LanguageApplicationCoreDXDDSwillrequirethefollowingpathsandlibrarieswhencompilingyourapplication:

Include Path: \ -I${COREDX_TOP}/target/include

Library Path: \ -L${COREDX_TOP}/target/${COREDX_TARGET}/lib

Static Libraries: -ldds

We’veprovidedMakefilesandVisualStudioprojectfilesforcompilingourexamples,andyoucanusetheseasareferenceforcompilingyourapplication.OurMakefilesrequirethreeenvironmentvariables:

1. COREDX_TOP 2. COREDX_HOST 3. COREDX_TARGET

TheCOREDX_TOPisapathnametothelocationofyourCoreDXDDSdistribution(s).COREDX_HOSTandCOREDX_TARGETaretheplatformarchitecturesyouarecompilingonandcompilingfor(thesecanbethesame).Thesevaluescanbesetmanually,ordeterminedbyrunningthescript:COREDX_TOP/scripts/cdxenv.shorcdxenv.bat.

OurMakefileswillruntheCoreDXDDSdatatypecompilertogeneratethetypespecificcodeaswellascompiletheapplications.TocompiletheHelloWorldsampleapplicationusingourMakefileyouwillneedamakeprogram(forexamplegnumakeorMicrosoftnmake)andthecompiler(forexample,gccorcl.exe)inyourpath.Then,simplytype‘make’(or‘nmake-f

CoreDXDDSProgrammer’sGuide

30

NMakefile’)intheappropriatedirectory.Thiswillcompiletwoapplications:hello_pubandhello_sub.

3.3.2 The‘C++’LanguageApplicationCoreDXDDSwillrequirethefollowingpathsandlibrarieswhencompilingyourapplication:

Include Path: \ -I${COREDX_TOP}/target/include

Library Path: \ -L${COREDX_TOP}/target/${COREDX_TARGET}/lib

Static Libraries: -lddscpp –ldds

We’veprovidedMakefilesforcompilingourexamples,andyoucanusetheseasareferenceforcompilingyourapplication.OurMakefilerequiresthreeenvironmentvariables:

1. COREDX_TOP 2. COREDX_HOST 3. COREDX_TARGET

TheCOREDX_TOPisapathnametothelocationofyourCoreDXDDSdistribution(s).COREDX_HOSTandCOREDX_TARGETaretheplatformarchitecturesyouarecompilingonandcompilingfor(thesecanbethesame).Thesevaluescanbesetmanually,ordeterminedbyrunningthescript:COREDX_TOP/scripts/cdxenv.shorcdxenv.bat.

OurMakefileswillruntheCoreDXDDSdatatypecompilertogeneratethetypespecificcodeaswellascompiletheapplications.TocompiletheHelloWorldsampleapplicationusingourLinuxMakefileyouwillneeda‘make’programandaC++compilerinyourpath.Then,simplytype‘make’(or‘nmake-fNMakefile’)intheappropriatedirectory.

Thiswillcompiletwoapplications:hello_pubandhello_sub.

3.3.3 The‘Java’LanguageApplicationWe’veprovidedscriptsforcompilingourjavaexamples,andyoucanusetheseasareferenceforcompilingyourapplication.Ourscriptsrequirethreeenvironmentvariables:

1. COREDX_TOP 2. COREDX_HOST 3. COREDX_TARGET

31

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TheCOREDX_TOPisapathnametothelocationofyourCoreDXDDSdistribution(s).COREDX_HOSTandCOREDX_TARGETaretheplatformarchitecturesyouarecompilingonandcompilingfor(thesecanbethesame).Thesevaluescanbesetmanually,ordeterminedbyrunningthescript:COREDX_TOP/scripts/cdxenv.shorcdxenv.bat.

OurscriptswillruntheCoreDXDDSdatatypecompilertogeneratethetypespecificcodeaswellascompiletheapplications.TocompiletheHelloWorldsampleapplicationusingourLinuxscriptsyouwillneed‘javac’inyourpath.Then,simplytype‘compile.sh’(or‘compile.bat’forWindows)intheappropriatedirectory.

Thiswillcreateajarfilewiththetwohelloapplications:HelloPubandHelloSub.Wealsoprovidescriptstorunthesejavaapplications:run_pub.shandrun_sub.sh(.batscriptsareprovidedforWindows).

3.3.4 The‘C#’LanguageApplicationWe’veprovidedMakefilesandVisualStudioprojectfilesforcompilingourexamples,andyoucanusetheseasareferenceforcompilingyourapplication.OurMakefilesrequirethreeenvironmentvariables:

1. COREDX_TOP 2. COREDX_HOST 3. COREDX_TARGET

TheCOREDX_TOPisapathnametothelocationofyourCoreDXDDSdistribution(s).COREDX_HOSTandCOREDX_TARGETaretheplatformarchitecturesyouarecompilingonandcompilingfor(thesecanbethesame).Thesevaluescanbesetmanually,ordeterminedbyrunningthescript:COREDX_TOP/scripts/cdxenv.shorcdxenv.bat.

OurMakefileswillruntheCoreDXDDSdatatypecompilertogeneratethetypespecificcodeaswellascompiletheapplications.TocompiletheHelloWorldsampleapplicationusingourMakefileonLinuxyouwillneedtheMONOCSharpcompiler(gmcs)inyourpath.Then,simplytype‘make’intheappropriatedirectory.Thiswillcompiletwoapplications:hello_pub.exeandhello_sub.exe.

CoreDXDDSProgrammer’sGuide

32

3.4 RunningYourApplicationwithCoreDXDDS

YouwillneedatleastoneenvironmentvariabletorunyourapplicationswithCoreDXDDS:

TWINOAKS_LICENSE_FILE: (refer to Using a License, above)

Runyourapplication(s).ThesampleHelloWorldhastwoapplications:hello_pub(orhello_pub.exeorHelloPub.class)andhello_sub(orhello_sub.exeorHelloSub.class).Thesubscriberapplication(hello_sub)willprintoutthemessagesitreceivesfromthepublishingapplication(hello_pub).Thepublisherwillkeepsendingoutmessagesuntilkilled.Thesubscriberwillkeeplisteningformessagesuntilkilled.

YoucanrunmultiplePublishersandmultipleSubscriberstoimmediatelyseethedynamicnatureoftheDDSnetworkinfrastructure.

Formatted: Font:Italic

Deleted: Using a License

33

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter4 ExampleCoreDXDDSApplications

CoreDXDDSisbundledwithanumberofexampleapplications.TheseapplicationsincludingworkingsourcecodeandMakefilestodemonstratehowtowrite,compile,andrunCoreDXDDSapplications.Mostoftheexampleapplicationsareincludedinthe${COREDX_TOP}/examplesdirectory(exceptionsarenotedbelow).

ThissectionincludesadescriptionofeachoftheexampleprogramsincludedintheCoreDXDDSrelease.

4.1 EnvironmentSetup

AlltheMakefilesintheCoreDXDDSexampleapplicationrequireafewenvironmentvariables.

1. COREDX_TOP 2. COREDX_HOST 3. COREDX_TARGET

TheCOREDX_TOPisapathnametothelocationofyourCoreDXDDSdistribution(s).COREDX_HOSTandCOREDX_TARGETaretheplatformarchitecturesyouarecompilingonandcompilingfor(thesecanbethesame).Thesevaluescanbesetmanually,ordeterminedbyrunningthescript:COREDX_TOP/scripts/cdxenv.shorcdxenv.bat.

IfyouhaveoneCoreDXDDSplatformarchitectureinstalled,thecdxenvscriptwillprintouttheappropriatecommandstosettheseenvironmentvariables.IfyouhavemultipleCoreDXDDSplatformarchitecturesinstalled,thecdxenvscriptwilllistallyourplatformarchitecturesandpromptyouforthecorrectHOSTandPLATFORMarchitecturesbeforeprintingthecommandstosettheseenvironmentvariables.

Table4-1:Example-Runningcdxenv.shprovidesanexampleofrunningcdxenv.shonaLinuxmachinewheremultipleCoreDXDDSplatformarchitecturesareinstalled.

CoreDXDDSProgrammer’sGuide

34

Table4-1:Example-Runningcdxenv.sh

cdxenvExample

/home/bob/coredx-4.0.2/scripts> ./cdxenv.sh 1: Linux_2.6_mips32_gcc34 2: Linux_2.6_x86_64_gcc43 3: Linux_2.6_x86_gcc43 4: NexusWare_ppc440_gcc 5: SunOS_5.10_sun4u_gcc 6: VxWorks_6.6_x86_gcc Please select the HOST platform [2]: 2 1: Linux_2.6_mips32_gcc34 2: Linux_2.6_x86_64_gcc43 3: Linux_2.6_x86_gcc43 4: NexusWare_ppc440_gcc 5: NexusWare_x86_gcc 6: SunOS_5.10_sun4u_gcc 7: VxWorks_6.6_x86_gcc Please select the TARGET platform [2]: 7 export COREDX_TOP=/home/bob/coredx_v3.1.0; export COREDX_HOST=Linux_2.6_x86_64_gcc43; export COREDX_TARGET=VxWorks_6.6_x86_gcc; export LD_LIBRARY_PATH=/home/bob/coredx_v3.1.0/target/VxWor ks_6.6_x86_gcc/lib

4.2 Example1:TheBasic“HelloWorld”Applications

CoreDXDDSprovidesthreeexample“HelloWorld”applications:a‘C’version,a‘C++’version,a‘C#’version,andaJavaversion.ThesearesimpleapplicationsthatshowthebasicusageoftheCoreDXDDSentitiesforsendingandreceivingdata.

Eachofthese“HelloWorld”examplescontainstwoapplications:onethatwillpublisha“HelloWorld”messageandonethatwillsubscribetoandreceivethe“HelloWorld”message.

Thehelloworldexamplesarelocatedintheexamplesdirectory:

hello_c/ hello_cpp/ hello_csharp/ hello_java/

35

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

MakefilesareprovidedforallplatformarchitecturessupportedbyCoreDXDDS,sotheseapplicationscanberunonavarietyofoperatingsystemsandlanguages.

4.3 Example2:PerformanceTests

CoreDXDDSalsoprovidessampleperformancebenchmarkingsourcecodeforlatencyandbandwidthbenchmarking.TheseapplicationsprovideanexampleofamoresophisticatedCoreDXDDSapplication.Inaddition,theyallowyoutodeterminetheperformanceofCoreDXDDSwithyourcomputersandnetworkinghardware.

Theperformanceexamplesarelocatedintheexamplesdirectory:

latency_test\ bwtest\

Makefilesareprovidedforavarietyofplatformarchitectures.

4.4 Example3:Filtering

CoreDXDDSprovidesanexampleofusingContentFilteredToipcsinthe“dds_filter”and“dds_filter_cpp”exampleapplications.Makefilesareprovidedforavarietyofplatformarchitectures.

4.5 Example4:DynamicTypes

CoreDXDDSprovidesanexampleofusingDynamicTypesinthe“dyntype”exampleapplication.Makefilesareprovidedforavarietyofplatformarchitectures.

4.6 Example5:NoThreads

CoreDXDDSprovidesanexampleofusingCoreDXDDSinasingle-threadedmode:the“hello_nothr”exampleapplication.ThisapplicationdemonstratestheAPIforusingCoreDXDDSwithoutadditionalthreads.

4.7 Example6:RPC

CoreDXDDSprovidesanexampleofusingtheCoreDXDDSRPCAPI:the“rpc_fcall”exampleapplication.FormoreinformationaboutusingtheRPCandrequest-responseAPI,refertotheRPCProgrammer’sGuide.

CoreDXDDSProgrammer’sGuide

36

4.8 Example7:QoSProvider

CoreDXDDSprovidesaneampleofconfiguringQoSpoliciesinanexternalXMLfile,andapplyingthemdynamicallytoentitiescreatedatrun-time.Thisexampleapplicationcanbefoundinthe“qos_provider”directory.

4.9 Example8:ShapesDemonstration

ThejavasourcecodefortheCoreDXDDSShapesdemonstrationisfreelyavailablefromtheTwinOaksComputingwebsite(itisnotpackagedaspartoftheCoreDXDDSrelease).TheShapesdemonstrationprovidesexamplesofmediumcomplexityCandJavaapplicationsusingCoreDXDDSforcommunications.AspecializedversionoftheCoreDXDDSShapesdemonstrationisavailableforAndroidplatforms.

Foradditionalinformationandinstructionsfordownloadingandusing,visittheTwinOaksComputingwebsite:

http://www.twinoakscomputing.com/coredx/shapes_demo

37

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter5 AdvancedCompileOptions

CoreDXDDSincludesseverallibrariesthatcanbeusedtodevelopCoreDXDDSapplications.SomelibrariesarerequiredforanyCoreDXDDSapplication.SomelibrariesincludeadvancedDDSfeaturesthatshouldonlybeusedifnecessary.Somelibrariesprovideadditionaldebugginginformation.Foralloftheselibraries,weincludeastaticanddynamiclibraryoption(foroperatingsystemsthatsupportthisdistinction).

ThissectiondescribesthedifferentoptionsavailabletocompileaCoreDXDDSapplicationfordifferentoperatingsystemenvironments.

5.1 LinuxandotherUNIX-variantOperatingSystems

Table5-1listsallthelibrariesprovidedwiththeLinuxplatformreleaseofCoreDXDDS.OtherUNIX-variantoperatingsystemsmayincludeasub-setoftheselibraries(dependingontheCoreDXDDSfeaturessupportedforeachparticularoperatingsystem).

Table5-1:CoreDXDDSLibraries(UNIXOperatingSystems)

Language libraryfilename Description

Clibraries libdds corelibrary(staticanddynamiclibraries)

libdds_cf corewithcontentfilterlibrary(staticanddynamiclibraries)

libdds_noto Minimalcorelibrary:notypeobject(staticanddynamiclibraries)

libdds_dyntype DynamicTypesextension(staticanddynamiclibraries)

libdds_qos_provider QoSProviderextension(staticanddynamiclibraries)

CoreDXDDSProgrammer’sGuide

38

Language libraryfilename Description

libdds_libxml2api XMLAPIextension(staticanddynamiclibraries)

libcdx_tport_lmt LocalMachineTransportextension(staticanddynamiclibraries)

libcdx_tport_tcp TCPtransportextension(staticanddynamiclibraries)

libxxx_log EveryClibraryhasanequivalentlibraryversionwithloggingenabled.

C++libraries

libdds_cpp C++languagebindingextension(staticanddynamiclibraries)

libdds_cpp_cf C++languagebindingforcontentfiltersextention,thisextensionreplacesthelibdds_cppextension(staticanddynamiclibraries)

Libdds_cpp_noto MinimalC++languagebinding:notypeobject,thisextensionreplacesthelibdds_cppextension(staticanddynamiclibraries)

libdds_cpp_dyntype C++DynamicTypesextension(staticanddynamiclibraries)

libdds_cpp_qos_provider QoSProviderextensionforthecpplanguagebinding(staticanddynamiclibraries)

libdds_rpc_cpp RPCandrequest-replyextension(staticanddynamiclibraries)

libxxx_cpp_log EveryC++libraryhasanequivalentlibraryversionwithloggingenabled.

C#libraries

39

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Language libraryfilename Description

coredx_csharp.dll C#languagebinding:containsallfeaturesinonelibrary

libdds_csharp C#languagebinding:nativelibrary

libdds_csharp_log C#languagebinding–nativelibrarywithlogging

Javalibraries

libdds_java Javalanguagebinding–nativelibrary

libdds_java_log Javalanguagebinding–nativelibrarywithlogging

CoreDXDDSprovidesbothstatic(“.a”)anddynamic(“.so”)libraries,sotheapplicationdevelopercanchoosetheappropriatetypeoflibrarytouse.AllourexampleapplicationscontainMakefilesthatillustratetheuseofthedifferentlibrariesandprovideagoodreferenceforCoreDXDDSlibraryusage.

5.1.1 LinkingwithStaticLibrariesAsimpleCoreDXDDSapplicationwrittenin‘C’requiresthecorelibrary:libdds.a.TheMakefileinthe“hello_c”sampleapplicationprovidesanexampleofusingthecorelibrary.

AsimpleCoreDXDDSapplicationwrittenin‘C++’requirestheC++languagebindinglibrary:libdds_cpp.ainadditiontothecorelibrary:libdds.a.TheMakefileinthe“hello_cpp”sampleapplicationprovidesanexampleofusingtheC++library.

Thereare4versionsofthebase(required)CoreDXDDSlibrary:

Þ libdds Þ libdds_cf Þ libdds_noto Þ libdds_log

CoreDXDDSProgrammer’sGuide

40

Anapplicationwilllinkonly1oftheabovelibraries.Otherlibrariesareextensionsofonetheabovebaselibraries,andwillbelinkedinadditiontothebaselibrary.Forexample:aCoreDXDDSapplicationusingcontentfiltersmustusethecontentfilterlibraryinplaceofthecorelibrary.A‘C’applicationwilluselibdds_cf.a.A‘C++’applicationwilluselibdds_cf.aandlibdds_cpp_cf.a(toprovidetheC++languagebindingextension).TheMakefileinthe“dds_filter”sampleapplicationprovidesanexampleofusingthecontentfilterlibrary.

ToenableCoreDXDDSlogging(refertoPart4:Chapter14CoreDXDDSLoggingforinformationonCoreDXDDSlogging),aCoreDXDDSapplicationmustusethelogginglibraryinplaceofthecorelibrary,andtobecomplete,mayalsolinkinthelogversionsofalltheextensionlibraries.A‘C’applicationwilluselibdds_log.a.A‘C++applicationwilluselibdds_log.aandlibdds_cpp_log.a.

ThereisnospecialconfigurationrequiredtorunaCoreDXDDSapplicationlinkedwithstaticlibraries.SimplysettheTWINOAKS_LICENSE_FILEenvironmentvariableappropriatelyasforanyCoreDXDDSapplication.

5.1.2 LinkingwithDynamicLibrariesInadditiontolinkinginthecorrectCoreDXDDSlibraries,theLD_LIBRARY_PATHenvironmentvariablemustbesetinordertorundynamicallylinkedCoreDXDDSapplications.

Tolinkwithdynamiclibraries,refertosection5.1.1:LinkingwithStaticLibrariesaboveandreplacethe“.a”librarieswiththe“.so”versionofthelibraries.

TorunaCoreDXDDSapplicationcompiledwithdynamiclibraries,theLD_LIBRARY_PATHenvironmentvariablemustbeset,inadditiontotheTWINOAKS_LICENSE_FILEenvironmentvariable.

5.1.3 Comilingwith–fPIC(Linuxplatforms)ForLinuxbilds,CoreDXDDSalsoprovidesversionsofthelibrariesthatmaybecompiledwiththe–fpicoption.Theselibrariesarelocatedinan“fpic”subdirectory:<COREDX_TARGET>/lib/fpic.

Formatted: Font:Italic

Deleted: Part4:Chapter14

Formatted: Font:Italic

Deleted: CoreDXDDSLogging

Formatted: Font:Italic

Deleted: LinkingwithStaticLibraries

41

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

5.2 WindowsOperatingSystem

Table5-2listsallthelibrariesprovidedwiththeWindowsplatformreleaseofCoreDXDDS.

Table5-2:CoreDXDDSLibraries(WindowsOperatingSystem)

Language libraryfilename Description

Clibraries

dds corelibrary(staticanddynamiclibraries)

dds_cf corewithcontentfilterlibrary(staticanddynamiclibraries)

dds_noto Minimalcorelibrary:notypeobject(staticanddynamiclibraries)

dds_dyntype DynamicTypesextension(staticanddynamiclibrary)

dds_qos_provider

QoSProviderextension(staticanddynamiclibraries)

dds_libxml2api XMLAPIextension(staticanddynamiclibraries)

cdx_tport_tcp TCPtransportextension(staticanddynamiclibraries)

dds_xxx_logdds_xxx_ddds_xxx_d_log

EveryClibraryhasanequivalentlibraryversionwithloggingenabled,withdebugenabled,andwithbothlogginganddebugenabled.

C++libraries

CoreDXDDSProgrammer’sGuide

42

Language libraryfilename Description

dds_cpp C++languagebindingextension(staticanddynamiclibraries)

dds_cpp_cf C++languagebindingforcontentfiltersextention,thisextensionreplacesthelibdds_cppextension(staticanddynamiclibraries)

dds_cpp_noto MinimalC++languagebinding:notypeobject,thisextensionreplacesthelibdds_cppextension(staticanddynamiclibraries)

dds_cpp_dyntype C++DynamicTypeextension(dynamiclibrary)(debugversion)

dds_cpp_qos_provider C++DynamicTypesextension(staticlibrary)(debugversion)

dds_rpc_cpp RPCandrequest-replyextension(staticanddynamiclibraries)

dds_cpp_xxx_logdds_cpp_xxx_ddds_cpp_xxx_d_log

EveryC++libraryhasanequivalentlibraryversionwithloggingenabled,withdebugenabled,andwithbothlogginganddebugenabled.

C#libraries coredx_csharp C#languagebinding:contains

allfeaturesinonelibrary

43

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Language libraryfilename Description

dds_csharp C#languagebinding–nativelibrary

dds_csharp_log C#languagebinding–nativelibrarywithlogging

Javalibraries dds_java Javalanguagebinding–native

library(staticanddynamiclibraries)

dds_java_log Javalanguagebinding–nativelibrarywithlogging

Bothstatic(“_static.lib”)anddynamic(“.dlland.lib”)librariesareprovided,alongwithvariantlibrarieswithdebugandloggingenabled.Theapplicationdevelopercanchoosetheappropriatetypeoflibrarytouse.AllourexampleapplicationscontainMakefilesthatillustratetheuseofthedifferentlibrariesandprovideagoodreferenceforCoreDXDDSlibraryusage.

5.2.1 LinkingwithStaticLibrariesAsimpleCoreDXDDSapplicationwrittenin‘C’requiresthecorelibrary:dds_static.lib.TheNMakefileinthe“hello_c”sampleapplicationprovidesanexampleofusingthecorelibrary.

AsimpleCoreDXDDSapplicationwrittenin‘C++’requirestheC++languagebindinglibrary:dds_cpp_static.libinadditiontothecorelibrary:dds_static.lib.TheNMakefileinthe“hello_cpp”sampleapplicationprovidesanexampleofusingtheC++library.

ACoreDXDDSapplicationusingcontentfiltersmustusethespecialcontentfilterlibraryinplaceofthecorelibrary.A‘C’applicationwillusedds_cf_static.lib.A‘C++’applicationwillusedds_cf_static.libanddds_cpp_cf_static.lib.TheNMakefileinthe“dds_filter”sampleapplicationprovidesanexampleofusingthecontentfilterlibrary.

ACoreDXDDSapplicationusingdynamictypesmustusethespecialdynamictypelibraryinadditiontothecorelibrary.A‘C’applicationwill

CoreDXDDSProgrammer’sGuide

44

usedds_static.libanddds_cf_static.lib.DynamictypesforC++arenotyetsupported.TheNMakefileinthe“dyntype”sampleapplicationprovidesanexampleofusingthedynamictypelibrary.

ToenableCoreDXDDSlogging(refertoPart4:Chapter14CoreDXDDSLoggingforinformationonCoreDXDDSlogging),aCoreDXDDSapplicationmustusethelogginglibraryinplaceofthecorelibrary.A‘C’applicationwillusedds_log_static.lib.A‘C++applicationwillusedds_log_static.libanddds_cpp_log_static.lib.Therearealsocontentfilteranddynamictypelibrarieswithloggingenabled.

ThereisnospecialconfigurationrequiredtorunaCoreDXDDSapplicationlinkedwithstaticlibraries.SimplysettheTWINOAKS_LICENSE_FILEenvironmentvariableappropriatelyasforanyCoreDXDDSapplication.

NOTE:Tobuildanapplicationlinkedtostaticlibraries,donotinclude/DCOREDX_DLLinthecompileflags.

5.2.2 LinkingwithDynamicLibrariesAdditionalcompilerflagsarerequiredtobuildanapplicationlinkedwithdynamiclibraries.Includethefollowinginthecompileflags:

/MD/DCOREDX_DLL

Note:the“/MD”specifiesdynamicallylinkedapplications,while“/MT”isforstaticallylinkedapplications.Tolinkadynamicapplicationwithdebugsupport,replace“/MD”with“/MDd”andlinktothelibrarieswith“_d”intheirname.

Tolinkwithdynamiclibraries,refertosection5.2.1:LinkingwithStaticLibrariesabovebutreplacethe“_static.lib”librarieswiththe“.lib”versionofthelibraries.

ThereareafewadditionalrulesforlinkingthecorrectCoreDXDDSWindowsdynamiclibraries,duetothenatureofWindowsdynamiclibraries.Theserulesaredescribedbelow.

Formatted: Font:Italic

Deleted: CoreDXDDSLogging

Formatted: Font:Italic

Deleted: LinkingwithStaticLibraries

45

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Table5-3:WindowsDynamicLibraryDependencies

Ifyourapplicationisusing: Itmustalsolinkinthefollowing:

dds_cf.dll,.lib N/A(standalonelibrary)

dds_cf_log.dll,.lib N/A(standalonelibrary)

dds_cpp_cf.dll,lib dds_cf.lib

dds_cpp_cf_log.dll,.lib dds_cf_log.lib

dds_cpp.dll,lib dds.lib

dds_cpp_log.dll,lib dds_log.lib

dds.dll,lib N/A(standalonelibrary)

dds_dyntype.dll,lib dds_cf.lib

dds_dyntype._log.dll,lib dds_cf_log.lib

dds_java.dll,lib N/A(applicationsdonotlinkthislibrary)

dds_log.dll,lib N/A(standalonelibrary)

TorunanapplicationlinkedtoCoreDXDDSdynamiclibraries,theCoreDXDDSlibrariesmustbeinyourPATHenvironmentvariable.Forexample:

set PATH=%PATH%;%COREDX_TOP%\target\%COREDX_TARGET%\lib

Inaddition,theTWINOAKS_LICENSE_FILEenvironmentvariablemustbesetcorrectly.

5.2.3 DynamicTypeSupportLibraryItmaybedesirabletocreateadynamiclibrarycontainingtheCoreDXDDSgeneratedtypesupportcode.ThisrequiressomespecialconfigurationforWindows.

CoreDXDDSProgrammer’sGuide

46

First,thegeneratedtypesupportcodemustbecompiledwiththeseadditionalflags:

/MD (fordynamicapplications.Replacewith“/MDd”fordebug) /DCOREDX_DLL /DCOREDX_DLL_TS /DCOREDX_DLL_TS_EXPORTS /LD

Notethe“/MD”isfordynamicallylinkedapplications,while“/MT”isforstaticallylinkedapplications.Tolinkadynamicapplicationwithdebug,replace“/MD”with“/MDd”.

Theapplicationlinkinginthedynamictypesupportlibrarymustbecompiledwiththeseadditionalflags:

/MD /DCOREDX_DLL /DCOREDX_DLL_TS

ThenincludethedynamictypesupportlibraryonthelinklinewiththeappropriateCoreDXDDSlibraries.

Torunthisresultingapplication,ensurethegenerateddynamictypesupportlibraryisavailableinyourpath(inadditiontotheCoreDXDDSlibraries).Inaddition,theTWINOAKS_LICENSE_FILEmustbesetappropriately.

47

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Part3: CoreDXDDSProgrammingConcepts

ThissectionprovidesamoredetailedexaminationoftheconsiderationsfordesigninganddevelopingapplicationsthatmakeeffectiveuseoftheCoreDXDDSmiddleware.Thisincludesdataarchitecture,QualityofServiceconfiguration,dataaccesspatterns,andstatuseventhandling.

49

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

50

Chapter6 DDSEntities

TheDDSStandarddefinesanarchitecturethatrepresentsanobject-orientedmodelofentitiesthatcomposetheDDSAPI.Theseentitiesserveastheinterfacebetweenthemiddlewareandtheapplicationsoftware.InordertodevelopaDDSenabledapplication,adevelopermustcreate,interactwith,anddestroytheseDDSentities.

ThischapterprovidesanoverviewoftheDDSEntitiesandrelatedconcepts.SubsequentchapterswillprovidemoredetailsandexamplestofullyillustratetheAPI.

6.1 DDSEntityHierarchy

TheprimaryentitiesthatmakeuptheDDSAPIarestructuredinahierarchy.EachentityinthehierarchyexposesarelatedsetofoperationsfromtheAPI.TheprogrammerinteractswiththeCoreDXDDSmiddlewarethroughtheseDDSentities.Forexample,thecommonoperationsontheseentitiesincludecreation,destruction,getandsetQoS,getandsetlisteners,getstatus.

Figure6-1:DDSEntityHierarchy

TheDomainParticipantFactoryistheinitialobjectavailabletoapplications.Itisasingleton,meaningthatonlyoneinstanceofthisobjectexistswithin

DomainParticipantFactory

DomainParticipant

Topic Publisher

DataWriter

Subscriber

DataReader

51

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

anapplication.ItisusedasafactorytocreateanddeleteDomainParticipants.

TheDomainParticipantobjectisthefactoryforPublishers,Subscribers,andTopics.TheDomainParticipantisacontainerforalloftheentitiesthatitcreates.TheDomainParticipantexistswithina‘DOMAIN’.AllentitiescreatedfromaDomainParticipantbelongtothesameDOMAINastheirparentparticipant.EntitieswithinaDOMAINmaycommunicate.EntitiesindifferentDOMAINSwillnotcommunicate.TheDOMAINspecifiesafundamentalseparationorscopeofdata.

TheTopicentityprovidesalogicalsetofhomogenousdata.TheTopicexistswithinadomain,andhasanameandadatatype.DataReadersandDataWritersarelogicallyconnectedbyacommontopic.

APublisherentityisafactoryforDataWriters.ThePublisherisacontainerforalltheDataWritersthatitcreates.ADataWriterexistswithinasinglePublisher,andisassociatedwithasingleTopic.ADataWriteriscapableofpublishingasingledatatypethatmatchesitsTopic.

ASubscriberentityisafactoryforDataReaders.TheSubscriberisacontainerforalltheDataReadersthatitcreates.ADataReaderexistswithinasingleSubscriber,andisassociatedwithasingleTopic.ADataReaderiscapableofreadingasingledatatypethatmatchesitsTopic.

6.2 DDSEntityCommonOperations

EachEntitysharesasetofcommonoperations.Theseoperationsallowtheapplicationtocontrolbasicaspectsoftheentity.Forexample,anEntitymustbeenabledbeforeitwillparticipateincommunications.Iftheentityisnotenabledautomaticallybyitsparentfactory,thentheenable()methodmustbecalledmanually.

enable()

get_qos()

set_qos()

get_listener()

set_listener()

get_statuscondition()

get_status_changes()

CoreDXDDSProgrammer’sGuide

52

6.3 DDSEntityQualityofService

ThebehaviorofDDScommunicationishighlyconfigurable.ThisconfigurationisperformedusingQualityofServicepolicies.EachoftheseprimaryDDSEntitiesacceptsQualityofServiceparameterstocontroltheirbehavior.TheparentfactorymaintainsadefaultconfigurationofQoSforitschildren.IfnoQoSisprovidedacreationtime,thenthesedefaultsareused.Anentity’sQoScanbeaccessedbycallingget_qos()ontheentity.Afteranentityiscreated,itsQoScanbechangedbydirectlycallingset_qos()ontheentity.Iftheentityisnotyetenabled,thenanyQoSpolicycanbechanged.However,aftertheentityisenabled,onlyasubsetofQoSpoliciescanbechangedonthefly.SeetheChapteronQoSPoliciesfordetails.

6.4 DDSStatus,Listeners,ConditionsandWaitSets

Eachentitymaintainsasetofstatusinformation.Thisinformationrepresentstheoccurrenceofsignificanteventswithinthemiddleware.Forexample,the“DataAvailable”or“PublicationMatched”statuses.TheCoreDXDDSmiddlewaresupportsmultiplenotificationmethodstocommunicatestatusinformationtotheapplication.Listenercallbackscanbeinstalled,supportingasynchronousnotification.Alternatively,theapplicationcaninitializeaWaitSetandblockwaitingforaspecificsetofstatusconditions.Thisrepresentssynchronousnotification.Finally,theapplicationcanchoosetopollthemiddlewareusingtheget_status_changes()method.

53

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

54

Chapter7 DevelopingaPublishingApplication

ThischapterdescribesthedevelopmentprocessforDDSpublishingapplications.

7.1 SummaryofDevelopingaPublishingApplication

Thestepsforcreatingapublishingapplicationareasfollows:

1. Createorobtainthedatatypesfortheapplicationdata.

2. UsetheCoreDXDDSdatatypescompilertocompilethedatatypes.Thetype-specificsupportandDataWriterarecreatedasaresultofcompilingthedatatypes.

3. Writethepublishingapplication.

4. Compilethepublishingapplication,linkingwiththegeneratedcodefromstep2andtheapplicableCoreDXDDSlibraries.

7.2 TheData

DDSenabledapplicationsareinherentlydata-centric.Inorderforthesedata-centricapplicationstoperformefficiently,itisnecessarytohaveawell-considereddatamodel,whichisimplementedineitherIDLorXML.

FormoreinformationonthedatatypessupportedbytheCoreDXDDSdatatypecompiler,seeApplicationDataTypes.

7.3 ThePublishingApplication

Note:DDSnamesmaybedifferentbetweenthedifferentlanguagebindings.SomelanguagesuseaDDSnamespace,whiletheClanguagebindingaugmentsnamestoincludethenamespaceasaprefix.Forexample,inC++wemightreferenceDDS::DomainParticipantFactory::create_participant(),whereasinC,thiswouldlooklikeDDS_DomainParticipantFactory_create_participant().Forpurposesofillustration,theexamplesinthissectionarewritteninC++,andassumethattheDDSnamespaceisinuse.

ApublishingapplicationmustincludethegeneratedType,TypeSupport,andDataWriterheaderfiles.

Formatted: Font:Italic

Deleted: ApplicationDataTypes

55

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

7.3.1 InitializetheDomainParticipantFactoryThisisthefirststepforanyapplicationcommunicatingusingDDS,andinitializestheCoreDXDDSmiddlewareforuse.

DomainParticipantFactory * dpf = DomainParticipantFactory::get_instance();

7.3.2 CreateaDomainParticipantTheDomainParticipantrepresentstheparticipationofanapplicationinavirtualDDSnetwork,linkingallapplicationsthatsharethesameDomainID.SeveralindependentDDS“networks”(inDDSterms,thesearedifferentDomains)cancoexistinthesamephysicalnetworkwithoutinterfering(orevenbeingaware)ofeachother.

ADDSapplicationmaycontainmorethan1DomainParticipant,inordertocommunicateinmultipleDDSDomains,orotherwiseorganizetheapplication’scommunicationevents.

Inaddition,theDomainParticipantactsasafactoryforcreatingTopics,Publishers(andSubscribers).

WhencreatingaDomainParticipant,youwillbeabletospecify:

DomainID Theuniqueidentifierforthedomainthisapplicationwillbepublishingin

QoSfortheDomainParticipant

DescribestheQoSfortheDomainParticipant

Listener Allowstheapplicationtoattachlistenerstothedomainparticipant.

ListenerStatusMask Setswhichlistenersareactive

[ThereareadditionalitemstoinitializeasecureDomainParticipant,thisisdescribedintheCoreDXDDSSecurityProgrammer’sGuide.]TocreateaDomainParticipantinthe123domain,usingthedefaultDomainParticipantQoS,andnolisteners,usethefollowing:

DomainParticipant * dp = dpf->create_participant( 123, PARTICIPANT_QOS_DEFAULT, NULL, 0);

CoreDXDDSProgrammer’sGuide

56

Bydefault,thecreate_participant()callwillinitializeandenabletheDomainParticipantforcommunications.

7.3.3 CreateaPublisherThepublisherisresponsiblefordisseminating(publishing)data.ItalsoactsasafactoryforcreatingDataWriters.

WhencreatingaPublisher,youwillbeabletospecify:

QoSforthePublisher DescribestheQoSforthePublisher

Listeners Allowstheapplicationtoattachlistenerstothepublisher

ListenerStatusMask Setswhichlistenersareactive

TocreateaPublisherusingthedefaultPublisherQoSandnolisteners,usethefollowing:

Publisher * pub = dp->create_publisher( PUBLISHER_QOS_DEFAULT, NULL, 0 );

Bydefault,thecreate_publisher()callwillinitializeandenablethePublisherforcommunications.

7.3.4 RegisteraDataTypeInordertopublish(orsubscribeto)data,thedatatypemustberegisteredintheCoreDXDDSmiddleware.

ThemostcommonmechanismtoregisteradatatypeistousetheTypeSupportgeneratedfromtheIDLorXML.(RefertotheDDSTypeSystemProgrammer’sGuideforadditionalinformationonregisteringdatatypes.)Theexamplecodeusesatypename:StringMsg.Toregisterthistypeusingthedefaulttypename(StringMsg)usethefollowing:

StringMsgTypeSupport ts; ts.register_type( dp, NULL );

57

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Thedefaulttypenameisthe‘base’typename,withoutanynamespaceprefixes.Youcansupplyanalternatetypenamebyreplacingthe2ndargumentwithastringname.

7.3.5 CreateaTopicTheTopicessentiallylinksthepublishersofdatawiththesubscribersofdata.ATopicisidentifiedbyauniquetopicname,andonedatatype.

WhencreatingaTopic,youareabletospecify:

TopicName MustbeuniqueintheDomain

TypeName MustalreadyberegisteredintheDomain

QoSfortheTopic DescribestheQoSfortheTopic

Listeners AllowstheapplicationtoattachlistenerstotheTopic

ListenerStatusMask Setswhichlistenersareactive

TocreateaTopicnamed“HelloTopic”withthe“StringMsg”type,defaultQoS,andnolistenersusethefollowing:

Topic topic = dp->create_topic( “HelloTopic”, “StringMsg”, TOPIC_QOS_DEFAULT, NULL, 0 );

7.3.6 CreateaDataWriterTheDataWriterisassociatedwithexactly1Topic,andcanwritedataofthespecificdatatypeassignedtothatTopic.Theapplicationtypicallyusesatype-specificDataWritertopublishdata.[Thealternativetoatype-specificDataWriterisaDynamicTypeDataWriter.MoreinformationmaybefoundintheDynamicTypessectionofthisProgrammer’sGuide.]

WhencreatingaDataWriter,youwillbeabletospecify:

Topic TheTopictowrite“on”

QoSfortheDataWriter

DescribestheQoSfortheDataWriter

CoreDXDDSProgrammer’sGuide

58

Listeners AllowstheapplicationtoattachlistenerstotheDataWriter

ListenerStatusMask Setswhichlistenersareactive

TocreateaDataWriterwiththeTopiccreatedabove,defaultQoS,andnolisteners,usethefollowing:

DataWriter * dw = pub->create_datawriter( topic, DATAWRITER_QOS_DEFAULT, NULL, 0 );

ForC++only:Thiscommandcreatesa“generic”DataWriter(thepublisherdoesnotknowwhattypeofdatawillbewritten).ThisgenericDataWriterwillwork,however,thereisnotypecheckingonthedatapassedtothisgenericDataWriteronawrite().Inordertohavethattypechecking,usethenarrow()methodtoobtainatype-specificDataWriter:

StringMsgDataWriter * sdw = StringMsgDataWriter::narrow( dw );

7.3.7 WriteDataAllthenecessarypiecesarenowinplacetostartpublishing(writing)data.Therearetwomethodsthatcanbeusedforwriting:

ReturnCode_t retval = sdw->write( data, HANDLE_NIL );

And:

ReturnCode_t retval = sdw->write_w_timestamp( data, HANDLE_NIL, time );

Thewrite()methodwritesthedataandusesthecurrenttimeasthesourcetimestamp.Thewrite_w_timestamp()methodallowstheapplicationtospecifythesourcetimestamp.Thesourcetimestampissentalongwiththedata,andislocatedintheSampleInfoonthesubscribingend.

Boththewrite()andwrite_w_timestamp()methodstakeaninstancehandleargument(theexamplesaboveusedtheemptyhandle:HANDLE_NIL).EachpieceofdatawrittenisassociatedintheCoreDXDDSmiddlewarebyaninstancehandle.Formoreinformationoninstancehandles,seetheInstancesandSampleschapter.Whenthedatacontainsa

59

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

key,callingwrite()withHANDLE_NILresultsintheinfrastructurelookingupthekeydatatofindtheassociatedinstancehandle.Ifyouaredoingmultiplewriteswithdatacontainthesamekey(orsetofkeys),youcanoptimizethecodebycallingregister()beforewrite().Forexample:

InstanceHandle_t handle = sdw->register_instance(data); ReturnCode_t retval = sdw->write( data, handle ); ReturnCode_t retval = sdw->write( data, handle );

Thewrite()APIisasynchronous:thewrite()callreturnsoncetheCoreDXDDSmiddlewarehasscheduledtheSampletobewritten,butthesampleisnotnecessarilywritten‘onthewire’atthattime.ThereturnvaluefromwriteindicatesCoreDXDDShassuccessfullyacceptedthissample,ornot.Possiblereasonsforwrite()returninganon-successreturncodeinclude:

1. ThereisnoroomintheDataWritercachetoholdthewrittensample,orthewrittensample’sinstance.

2. Theprovidedinstance_handle(ifnotHANDLE_NIL)doesnotrefertoavalidinstance

7.4 AvailableQoSSettings

EverycreatedDDSentityhasanassociatedQualityofService(QoS)thatcanbespecifiedwhencreatingtheentity,orlaterbycallingtheset_qos()methodonthatentity.TheQoSforeachentityisacomprehensivesetofconfigurationpoliciesthataffectthebehaviorofthatentity.ThemiddlewaredefinesadefaultQoSforeachentity,whichwasusedintheexamplesabove.

BelowisatablelistingtheavailableQoSforthepublishingentities(DomainParticipant,Publisher,Topic,andDataWriter).Thistablelistsonlybriefdescriptions.AmorecompletelistofQoSPoliciesandtheirdescriptionscanbefoundintheQualityofServiceFeatureschapter.

Table7-1:QoSPoliciesforPublishingEntities

QoSPolicy Description AvailableTo

USER_DATA DatanotusedbytheCoreDXDDSmiddleware,theapplicationcanusethisdataforitsownpurposes.

DomainParticipant,DataWriter

Formatted: Font:Italic

Deleted: QualityofServiceFeatures

CoreDXDDSProgrammer’sGuide

60

TOPIC_DATA DatanotusedbytheCoreDXDDSmiddleware,theapplicationcanusethisdataforitsownpurposes.

Topic

GROUP_DATA DatanotusedbytheCoreDXDDSmiddleware,theapplicationcanusethisdataforitsownpurposes.

Publisher

DURABILITY Specifiesifpublisheddatashouldbesavedforlater-joiningDataReaderstoreceive.

Topic,DataWriter

DURABILITY_SERVICE NotYetImplemented

Specifiesconfigurationforthedisabilities:TRANSIENTandPERSISTENT.

Topic,DataWriter

PRESENTATION Affectshowdataispresentedtothesubscribingapplication.Forexample,publisheddatacanbegroupedtogethersuchthattheDataReadersreceiveallcoherentdatatogether.

Publisher

DEADLINE EstablishesanagreementthattheDataWriterwillupdateeachinstanceofthedataatleastonceeveryspecifiedtimeperiod.Ifthewritingapplicationfailstomeetthiscontract,thedeadline_missedstatusontheDataWriteristriggered.

Topic,DataWriter

OWNERSHIP SpecifiesifmultipleDataWritersareallowedtowrite(orupdate)thesameinstanceofthedata,andhowthesemodificationsshouldbehandled.

Topic,DataWriter

OWNERSHIP_STRENGTH SpecifiesthestrengthusedtoarbitrateamongmultipleDataWriterswriting(orupdating)thesameinstanceofthedata.

DataWriter

61

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

LIVELINESS IndicatesacommitmentbytheDataWritertosignalit’slivelinesstoDataReadersinthespecifiedinterval.ThismaymeantheDataWriterupdatesitssamples,orsimplyassertsitisstillalive.IftheDataWriter(orapplication)failstomeetthislivelinesscontract,theLIVELINESS_LOSTstatusistriggeredontheDataWriter.

Topic,DataWriter

PARTITION AlogicalpartitionamongTopicsvisibletoPublishersandSubscribers.ApublisherwillonlycommunicatewithasubscriberiftheirPartitionsmatch(wildcardsallowed).

Publisher

RELIABILITY IndicatesthelevelofreliabilityofferedbytheDataWriter.

Topic,DataWriter

DESTINATION_ORDER Specifiestheorderinwhichchangestoaninstancewillbepublished.

Topic,DataWriter

HISTORY Specifiesifthepublishingmiddlewareshouldkeepany(orall)updatestoaninstanceonbehalfofexistingDataReaders.

Topic,DataWriter

RESOURCE_LIMITS SpecifiestheresourcesthemiddlewarecanconsumeinordertomeettherequestedQoS.

Topic,DataWriter

ENTITY_FACTORY Specifiesifafactoryshouldautomaticallyenablecreatedentities.Ifthefactorydoesnotautomaticallyenablethoseentities,theapplicationmustspecificallyenablethembeforetheycanbeusedforpublishingorwritingdata.

DomainParticipantFactory,DomainParticipant,Publisher

CoreDXDDSProgrammer’sGuide

62

7.5 AvailableListeners

ListenersareonemechanismallowingtheapplicationtobemadeawareofeventsandchangesintheCoreDXDDSmiddlewarecommunicationstatus.Alistenerhasanumberofmethodsdefined,oneforeachapplicablecommunicationstatus.TheapplicationcandefineoneormorelistenermethodsandattachthemtoanappropriateDDSentitywhentheentityiscreated,orlaterbyusingtheset_listener()methodontheentity.

ThetablebelowliststhelistenersthatcanbeattachedtopublishingEntities.AmorecompletelistanddescriptionoflistenerscanbefoundintheCommunicationStatuschapter.

Table7-2:ListenersforPublishingEntities

Listener ListenerMethods Description

DataWriterListener on_offered_deadline_missed() AdeadlineofferedthroughtheDEADLINEQoSsettingwasmissed.

on_offered_incompatible_qos() ADataReaderwasdiscoveredforthesameTopicasthisDataWriter,buttheQoSrequestedbythatDataReaderwasincompatiblewiththisDataWriter’sofferedQoS.

on_liveliness_lost() ThelivelinessspecifiedintheLIVELINESSQoSwasnotrespected,andDataReaderswillconsiderthisDataWriternolongeractive.

on_publication_matched() ADataReaderhasbeenfoundthatmatchestheTopicandQosofthisDataWriter(oraDataReaderthatwaspreviouslymatchedisnolongermatched.

Formatted: Font:Italic

Deleted: CommunicationStatus

63

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

PublisherListener (none) (PublisherListenerinheritsmethodsfromtheDataWriterListener)

TopicListener on_inconsistent_topic() Another,different,TopicexistswiththesamenameasthisTopic.

DomainParticipantListener

(none) (DomainParticipantListenerinheritsmethodsfromtheDataWriterListener,PublisherListener,andTopicListener)

CoreDXDDSProgrammer’sGuide

64

Chapter8 DevelopingaSubscribingApplication

ThischapterdescribesthedevelopmentprocessforDDSsubscribingapplications.

8.1 SummaryofDevelopingaSubscribingApplication

Thestepsforcreatingasubscribingapplicationareasfollows:

1. CreateorobtainthedatadefinitionsfortheDDSinterfaces

2. UsetheCoreDXDDSdatatypecompilertocompilethedatatypes.Thetype-specificsupportandDataReaderarecreatedasaresultofcompilingthedatatypes.

3. Writethesubscribingapplication

4. Compilethesubscribingapplication,linkingwiththegeneratedcodefromstep2andtheapplicableCoreDXDDSlibraries.

8.2 TheData

DDSenabledapplicationsareinherentlydata-centric.Inorderforthesedata-centricapplicationstoperformefficiently,itisnecessarytohaveawell-considereddatamodel,whichisimplementedineitherIDLorXML.

FormoreinformationonthedatatypessupportedbytheCoreDXDDSdatatypecompiler,seeApplicationDataTypes.

8.3 TheSubscribingApplication

Note:Namesmaybedifferentbetweenthedifferentlanguagebindings.ThisisbecausesomelanguagebindingsuseaDDSnamespace,andtheClanguagebindingaugmentsnamestoincludethenamespaceasaprefix.Forexample,inC++wemightreferenceDDS::DomainParticipantFactory::create_participant(),whereasinC,thisisthesyntax:DDS_DomainParticipantFactory_create_participant().Forpurposesofillustration,theexamplesinthissectionarewritteninC++,andassumethattheDDSnamespaceisinuse.

AsubscribingapplicationmustincludethegeneratedType,TypeSupport,andDataReaderheaderfiles.

Formatted: Font:Italic

Deleted: ApplicationDataTypes

65

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

8.3.1 InitializetheDomainParticipantFactoryThisisthefirststepforanyapplicationcommunicatingusingDDS,andinitializestheCoreDXDDSmiddlewareforuse.

DomainParticipantFactory * dpf = DomainParticipantFactory::get_instance();

8.3.2 CreateaDomainParticipantTheDomainParticipantrepresentstheparticipationofanapplicationinavirtualnetwork,linkingallapplicationsthatsharethesamedomainID.SeveralindependentDDS“networks”(inDDSterms,thesearedifferentDomains)cancoexistinthesamephysicalnetworkwithoutinterfering(orevenbeingaware)ofeachother.

Inaddition,theDomainParticipantactsasafactoryforcreatingTopicsandSubscribers(andPublishers),orotherwiseorganizetheapplication’scommunicationevents.

WhencreatingaDomainParticipant,youwillbeabletospecify:

DomainID Theuniqueidentifierforthedomainthisapplicationwillbepublishingin

QoSfortheDomainParticipant

DescribestheQoSfortheDomainParticipant

Listener Allowstheapplicationtoattachlistenerstothedomainparticipant.

Listenerstatusmask Setswhichlistenersareactive

TocreateaDomainParticipantinthe123domain,usingthedefaultDomainParticipantQoS,andnolistenersusethefollowing:

DomainParticipant * dp = dpf->create_participant( 123, PARTICIPANT_QOS_DEFAULT, NULL, 0);

Bydefault,thecreate_publisher()callwillinitializeandenablethePublisherforcommunications.

CoreDXDDSProgrammer’sGuide

66

8.3.3 CreateaSubscriberThesubscriberisresponsibleforreceivingdata.ItalsoactsasafactoryforcreatingDataReaders.WhencreatingaSubscriber,youareabletospecify:

QoSfortheSubscriber

DescribestheQoSfortheSubscriber

Listeners Allowstheapplicationtoattachlistenerstothesubscriber

ListenerStatusMask Setswhichlistenersareactive

TocreateaSubscriberusingthedefaultPublisherQoSandnolisteners,usethefollowing:

Subscriber * sub = dp->create_subscriber( SUBSCRIBER_QOS_DEFAULT, NULL, 0 );

8.3.4 RegisteraDataTypeInordertosubscribetodata,thedatatypemustberegisteredintheCoreDXDDSmiddleware.

Toregisteradatatype,usetheTypeSupportgeneratedfromtheCoreDXDDSdatatypecompiler.Theexamplecodeusesatypename:StringMsg.Toregisterthistypeusingthedefaulttypename(StringMsg)usethefollowing:

StringMsgTypeSupport ts; ts.register_type( dp, NULL );

Youcansupplyanalternatetypenamebyreplacingthe2ndargumentwithastringname.

8.3.5 CreateaTopicTheTopicessentiallylinksthepublishersofdatawiththesubscribersofdata.ATopicisidentifiedbyauniquetopicname,andatype.

WhencreatingaTopic,youwillbeabletospecify:

67

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TopicName MustbeuniqueintheDomain

TypeName MustalreadyberegisteredintheDomain

QoSfortheTopic DescribestheQoSfortheTopic

Listeners AllowstheapplicationtoattachlistenerstotheTopic

ListenerStatusMask Setswhichlistenersareactive

TocreateaTopicnamed“HelloTopic”withthe“StringMsg”type,defaultQoS,andnolistenersusethefollowing:

Topic topic = dp->create_topic( “HelloTopic”, “StringMsg”, TOPIC_QOS_DEFAULT, NULL, 0 );

8.3.6 CreateaDataReaderTheDataReadercanreaddataofaspecifictype.Theapplicationusesatype-specificDataReadertoreaddata.WhencreatingaDataReader,youwillbeabletospecify:

Topic TheTopictoread“on”

QoSfortheDataReader

DescribestheQoSfortheDataReader

Listeners AllowstheapplicationtoattachlistenerstotheDataReader

ListenerStatusMask Setswhichlistenersareactive

TocreateaDataReaderwiththeTopiccreatedabove,defaultQoS,andnolisteners,usethefollowing:

DataReader * dr = sub->create_datareader( topic, DATAREADER_QOS_DEFAULT, NULL, 0 );

CoreDXDDSProgrammer’sGuide

68

ForC++applications:AnapplicationcannotshouldcasttheDataReadertoatypespecificDataReadertouseitinatype-safemanner.Thenarrow()operationcanbeusedtoobtainthetypespecificDataReader.Forexample:

StringMsgDataReader * sdr = StringMsgDataReader::narrow( dr );

8.3.7 Read(orTake)DataUltimately,theapplicationwillcalloneoftheread()ortake()methodsontheDataReadertoaccessdata.Theseoperationsarenon-blocking,anddeliverthedatathathasbeenreceivedandiscurrentlyavailabletotheapplication.Theread()andtake()operationsreturnanorderedcollectionofdatasamples,andtheirassociatedsampleinformation,thatmatchtheQoSpoliciessetontheSubscriberandDataReaderandtheparameterspassedtoread()andtake().

Theread()andtake()operationshaveasimilarAPIsignature,andasetofvariantsthatprovidetheapplicationwithadditionalcontroloverthereturneddata.Thebasicread()operationprovidestheapplicationwithaccesstodatamanagedbytheDataReader.Aftertheread()operation,thedataisstillmanagedbytheDataReader,andisavailableforaccessbysubsequentread()operations.Thetake()operation,alsoprovidesaccesstodatamanagedbytheDataReader.Itdiffersfromread()becausedatasamplesaccessedbythetake()operationareremovedfromtheDataReader,andarenotavailabletosubsequentread()ortake()operations.Asananalogy,read()peeksatthedataavailableintheDataReaderwhiletake()actuallyremovesthedatafromtheDataReader.

Thebasicread()andtake()operationsbothallowtheapplicationtospecifyafilterforview,sample,andinstancestates.Thisallowstheapplicationtorequestonlythosesamplesthathavetherequestedstate.FormoreinformationonthesestatesseetheSampleStatusInformation(SampleInfo)section.

Thevariationsofread()andtake()providedbytheAPIareasfollows:

method Behavior

read_w_condition()

take_w_condition()

AppliesaReadConditionfiltertothesamplesbeforereturning.TheReadConditioncanbeaQueryCondition(specialization)whichincludesanSQLlikeselectstatement.This

Formatted: Font:Italic

Deleted: SampleStatusInformation(SampleInfo)

69

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

providesforcomplexfilteringofdatasamplesbasedonstatusanddatacontent.

read_next_sample()

take_next_sample()

ThisaccessesasinglesampleinorderasdictatedbytheQoSsettings.

read_instance()

take_instance()

Thisaccessesthedatasamplesofaparticularinstancespecifiedasanargument.

read_next_instance()

take_next_instance()

Thisprovidesamechanismtoiterativelyaccessthedatasamplesofallinstances.ByprovidingaNILHANDLEtothefirstinvocation,andthenprovidingtheinstancehandleofthereturnedsamplestosubsequentinvocations,itispossibletoiteratethroughallinstancescontainedintheDataReader.

read_next_instance_w_condition()

take_next_instance_w_condition()

Thiscombinesfilteringcapabilitieswithinstanceiteration.

8.3.8 NotificationOptions(DetermineWhenDataisAvailable)CoreDXDDSprovidesanumberofstatusandnotificationsthatareavailablefortheapplicationtolearnabouteventswithintheCoreDXDDSmiddleware.AnexampleistheeventthatdatahasbeenreceivedbytheDataReaderandisavailablefortheapplicationtoread(ortake).ThesenotificationoptionsmayalsobeusedtonotifytheapplicationofothereventsthatmayhappenwithintheCoreDXDDSmiddleware.

8.3.8.1 UsingListeners

Listenersprovideasynchronousnotificationwhendataisavailable.Therearetwolisteneroperationsthatindicatedataisavailable:theon_data_available()methodintheDataReaderListenerandtheon_data_on_readers()methodintheSubscriberListener.Thesubscribing

CoreDXDDSProgrammer’sGuide

70

applicationattachesalistenertotheDataReaderorSubscriber,andthatlistenerisinvokedwhendataisavailable.

AdditionalinformationonlistenersandexamplelistenercodecanbefoundintheListenerssectionofthismanual.

8.3.8.2 UsingConditions

Conditions,whencombinedwithWaitSetsprovidesynchronousnotificationwhendataisavailablebyallowingthesubscribingapplicationtoblockuntildataisavailable.Therearetwotypesofconditionsthesubscribingapplicationcanusetobenotifiedofavailabledata.ThefirstisaStatusCondition.TheDataReaderandSubscriberbothhaveaStatusCondition.TheDataReader’sStatusConditionwilltriggerwhentheDATA_AVAILABLE_STATUSontheDataReaderchanges.TheSubscriber’sStatusConditionwilltriggerwhenthesubscriber’sDATA_ON_READERS_STATUSchanges.ThesecondtypeofconditionisaReadCondition,whichistriggeredwhendataisavailableontheDataReader.TheReadConditionallowstheapplicationtospecifyadditionalcriteriathatmustbemetbeforetheConditionistriggered,includinginstancestate,samplestate,andviewstate.

AdditionalinformationonConditionsandWaitSets,alongwithexamplecodecanbefoundintheConditionsandWaitSetssectionofthismanual.

8.3.8.3 UsingPolling

Theapplicationcanchoosetopollfordata,ratherthanblockingorusingcallbacks.Whenpollingfordata,theapplicationcallsDataReader::read()ortake()operationinaloop.Ifthereisdataavailable,thesemethodsreturnDDS::RETCODE_OK,otherwisetheyreturnDDS::RETCODE_NO_DATA.

8.4 SampleStatusInformation(SampleInfo)

Callstoanyoftheread()ortake()variantsdescribedabovereturnoneoremoresamplesandcorrespondingSampleInfostructures.TheSampleInfo

structurecontainsmetadataaboutthereceivedsampleandincludesthefollowinginformation:

8.4.1 sample_stateThesamplestateisthestateofthedatasample.Validstatesare:READandNOT_READ.

Formatted: Font:Italic

Deleted: Listeners

Formatted: Font:Italic

Deleted: ConditionsandWaitSets

71

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

ThesamplestateisREADifthisDataReaderhasreadthissamplepreviously,otherwisethestateisNOT_READ.

8.4.2 view_stateTheviewstateindicatesthisDataReader’sviewofthedatainstance.Validstatesare:NEWandNOT_NEW.

TheviewstateisNEWifthisDataReaderhasneverreadasamplefromthisinstance,otherwisethestateisNOT_NEW.TheviewstatecanalsobeNEWifthisisthefirstsamplereceivedsincetheinstancewasdisposed.

8.4.3 instance_stateTheinstancestateisthestateoftheinstance.Validstatesare:ALIVE,NOT_ALIVE_DISPOSED,andNOT_ALIVE_NO_WRITERS.

TheinstancestateisALIVEifthereisatleastoneDataWriteractivelywritingsamplesonthisinstance.TheinstancestateisNOT_ALIVE_DISPOSEDiftheinstancewasexplicitlydisposedbyaDataWriter.TheinstancestateisNOT_ALIVE_NO_WRITERSiftherearenoDataWritersactivelywritingthisinstance.

8.4.4 source_timestampThesourcetimestampisthetimestampprovidedbytheDataWriteratthetimethesamplewasproduced.

8.4.5 instance_handleTheinstancehandleisauniqueidentifierforthissample’sinstance.

8.4.6 publication_handleThepublicationhandleisauniqueidentifierfortheDataWriterwhowrotethissample.

8.4.7 disposed_generation_countThedisposedgenerationcountisacountofthenumberoftimestheinstancehascomealiveafterbeingdisposed.Inotherwords,anytimetheinstancestatechangesfromNOT_ALIVE_DISPOSEDtoALIVE.

Thiscountcanbeusedtodeterminethenumberoftimesaninstancehasbeendisposed.Initially,itis0.

CoreDXDDSProgrammer’sGuide

72

8.4.8 no_writers_generation_countThenowritersgenerationcountisacountofthenumberoftimesaDataWriterhasstartedwritingdataontheinstanceafterbeingdeclaredNOT_ALIVE_NO_WRITERS.Inotherwords,anytimetheinstancestatechangesfromNOT_ALIVE_NO_WRITERStoALIVE.

Thiscountcanbeusedtodeterminethenumberoftimesaninstancehasnotbeenaliveduetonoactivereaders.Initially,itis0.

8.4.9 sample_rankThesamplerankisthenumberofsamplesinthisinstancethatfollowthisoneinthecurrentread(ortake)collection.

Thesamplerankcanbeusedtodeterminethe‘sampleage’ofthecurrentsample,relativetothenumbersamplesfortheinstanceinthereturnedsampleset.

8.4.10 generation_rankThegenerationrankisthenumberoftimesthisinstancehastransitionedfromnot-alivetoaliveinthetimebetweenthereceptionofthissampleandthelatestsampleforthisinstanceinthecurrentread(ortake)collection.

Thegenerationrankcanbeusedtodeterminethe‘generationage’ofthecurrentsample,relativetothenumberofsamplesforthisinstancesinthereturnedsampleset.

8.4.11 valid_dataThevaliddataflagindicatesthesampledataassociatedwiththisSampleInfoisvalid.Validvaluesarezero(FALSE)andnon-zero(TRUE).

Thevaliddataflagissettotruewhenadatasampleisreceived.Thevaliddataflagissettofalsewhenanunregisterordisposecommandisreceived.(Thereisstillasamplereturned,however,onlythekeyfields,ifany,willbevalidinthissample.)

8.5 AdditionalSubscriber/DataReaderFeatures

8.5.1 FilteringDataTherearetwobasicoptionsforfilteringreceiveddata.

73

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

1. FilterdatathatisreceivedbytheDataReader(filtereddataisneveravailabletotheapplication).

2. Filterdataasitisreadbytheapplication(filtereddataisstillavailableintheDataReaderforfuturereadsortakesbytheapplication).

AContentFilteredTopicortheTimeBasedFilterQoSpolicyisusedtoachievethefirstoption.ADataReadercreatedonaContentFilteredTopicwillnotstorethefiltereddata,andsoitisneveravailabletotheapplication.RefertotheContentFilteredTopicssectionforadditionalinformationonContentFilteredTopics.Similarly,datafilteredbyaconfiguredTimeBasedFilterQoSpolicyisnotaddedtotheDataReadercache,andsoitisneveravailabletotheapplication.

Thesecondoptionmaybeachievedbyusingtheread_w_condition()(ortake_w_condition())API,orbyusingaWaitSetwithareadconditionattached.Boththeread_w_condition()/take_w_condition()APIandWaitSetsallowfilteringusingReadConditionsorQueryConditions.

ReadConditionsallowtheapplicationtofilterbythestateandviewofthedataintheDataReadercache.ReadConditionfiltersparametersinclude:

• SampleState:hasthedatasamplebeen‘read’ornot• ViewState:isthedatasamplenewlyreceivedsincetheapplication

lastaccessedthedatacache(viaaread()ortake()operation)• InstanceState:istheinstancealive,disposed,orunregistered(see

xyzforadditionalinformationonInstances).

QueryConditionsallowtheapplicationtofilteronthedatacontentsofeachsample.TheseconditionsareprovidedasanSQL-likequerystring,andonlydatathatmatchesthespecifiedqueryisreturnedtotheapplication.RefertotheContentFilteredTopicssectionforadditionalinformationonthequerysyntax.

8.5.2 WaitforHistoricalDataDataReaderswithaDurabilityQoSpolicyconfiguredtoTransientLocal,Transient,orPersistentmayreceivehistoricaldatapublishedbeforethisDataReaderwasenabled.TheDataReaderprovidesanAPIthatwillblocktheapplicationuntilallavailablehistoricaldatahasbeenreceived:

DataReader::wait_for_historical_data( Duration_t max_wait)

Formatted: Font:Italic

Deleted: ContentFilteredTopics

Formatted: Font:Italic

Deleted: ContentFilteredTopics

CoreDXDDSProgrammer’sGuide

74

Whenthismethodisinvoked,theapplicationwillblockuntilallhistoricaldata(allpreviouslypublisheddatasamples)havebeenreceivedandareavailablefortheapplicationtoreadoruntilmax_waithasexpired,whicheveroccursfirst.

ThismethodisnotapplicablewhentheDataReader’sDurabilityQoSpolicyisconfiguredtoVolitile;inthiscase,wait_for_historical_data()willreturnimmediately.

8.6 QoSPolicies

EverycreatedDDSentityhasanassociatedQualityofService(QoS)thatcanbespecifiedwhencreatingtheentity,orlaterbycallingtheset_qos()methodonthatentity.TheQoSforeachentityisacomprehensivesetofconfigurationpoliciesthataffectthebehaviorofthatentity.ThemiddlewaredefinesadefaultQoSforeachentity,whichwasusedintheexamplesabove.

BelowisatablelistingtheavailableQoSforthesubscribingentities(DomainParticipant,Subscriber,Topic,andDataReader).Thistablelistsonlybriefdescriptions.AmorecompletelistofQoSPoliciesandtheirdescriptionscanbefoundintheQualityofServiceFeatureschapter.

Table8-1:QoSPoliciesforSubscribingEntities

QoSPolicy Description AvailableTo

USER_DATA DatanotusedbytheCoreDXDDSmiddleware,theapplicationcanusethisdataforitsownpurposes.

DomainParticipant,DataReader

TOPIC_DATA DatanotusedbytheCoreDXDDSmiddleware,theapplicationcanusethisdataforitsownpurposes.

Topic

GROUP_DATA DatanotusedbytheCoreDXDDSmiddleware,theapplicationcanusethisdataforitsownpurposes.

Subscriber

DURABILITY SpecifiesiftheDataReaderwouldliketoreceiveolderdatathatwaspublished

Topic,DataReader

Formatted: Font:Italic

Deleted: QualityofServiceFeatures

75

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

beforetheDataReadercameonline(inotherwords,thehistorydata).

DURABILITY_SERVICE NotYetImplemented

Specifiesconfigurationforthedisabilities:TRANSIENTandPERSISTENT.

Topic,DataReader

PRESENTATION Affectshowdataispresentedtothesubscribingapplication.Forexample,publisheddatacanbegroupedtogethersuchthattheDataReadersreceiveallcoherentdatatogether.

Subscriber

DEADLINE Establishesanexpectationthatthepublisherofdatawillupdatedthedataatleastonceeveryspecifiedtimeperiod.

Topic,DataReader

OWNERSHIP SpecifiesifmultipleDataWritersareallowedtowrite(orupdate)thesameinstanceofthedata,andhowthesemodificationsshouldbehandled.

Topic,DataReader

LIVELINESS IndicatesanexpectationoftheDataReaderthattheDataWriterwillsignalit’slivelinessinthespecifiedinterval.

Topic,DataReader

PARTITION AlogicalpartitionamongTopicsvisibletoPublishersandSubscribers.ApublisherwillonlycommunicatewithasubscriberiftheirPartitionsmatch.

Subscriber

RELIABILITY IndicatesthelevelofreliabilityexpectedofallmatchedDataWriters.

Topic,DataReader

DESTINATION_ORDER SpecifiestheorderinwhichchangestoaninstancewillbeorderedbytheSubscriber.

Topic,DataReader

CoreDXDDSProgrammer’sGuide

76

HISTORY Specifiesifthesubscribingmiddlewareshouldkeepany(orall)updatestoaninstance(history).

Topic,DataReader

RESOURCE_LIMITS SpecifiestheresourcesthemiddlewarecanconsumeinordertomeettherequestedQoS.

Topic,DataReader

ENTITY_FACTORY Specifiesifafactoryshouldautomaticallyenablecreatedentities.Ifthefactorydoesnotautomaticallyenablethoseentities,theapplicationmustspecificallyenablethembeforetheycanbeusedforreceivingdata.

DomainParticipantFactory,DomainParticipant,Subscriber

8.7 AvailableListeners

ListenersareonemechanismallowingtheapplicationtobemadeawareofeventsandchangesintheCoreDXDDSmiddlewarecommunicationstatus.Weillustratedanexampleofonekindoflistenerabove,theDataReaderListener,usedforreceivingdata.Thereareadditionallistenersavailabletoasubscribingapplication.TheapplicationcandefineoneormorelistenermethodsandattachthemtoanappropriateDDSentitywhentheentityiscreated,orlaterbyusingtheset_listener()methodontheentity.

Thetablebelowliststhelistenersthatcanbeattachedtoasubscribingapplication.AmorecompletelistanddescriptionoflistenerscanbefoundintheCommunicationStatuschapter.

Table8-2:ListenersforSubscribingEntities

Listener ListenerMethods Description

DataReaderListener

on_requested_deadline_missed() ThedeadlinethisDataReaderwasexpectingthroughitsQoSDEADLINEwasmissed.

Formatted: Font:Italic

Deleted: CommunicationStatus

77

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Listener ListenerMethods Description

on_requested_incompatible_qos() ADataWriterhasbeendiscoveredthathasaQoSconfigurationincompatiblewiththisDataReader’sQoS

on_liveliness_changed() OneormoreoftheDataWritersthisDataReaderwasreceivingsamplesdatafromhaschangedliveliness(eitherbecameACTIVEorINACTIVE)

on_subscription_match() ADataWriterhasbeendiscoveredthatmatchestheTopicandhasacompatibleQoSconfigurationtothisDataReader

on_sample_rejected() AreceivedsamplehasbeenrejectedbythisDataReaderbecauseaRESOURCE_LIMITSQoSsettinghasbeenexceeded.Thesampleisnotavailabletotheapplication.

on_data_available() Newinformation(datasample(s)orsampleinformation)isavailable

on_sample_lost() Asamplehasbeenlost(notreceivedbythisDataReader).Thissampleisnotavailabletotheapplication.

SubscriberListener on_data_on_readers() DatahasbeenreceivedandisavailableononeormoreDataReadersattachedtothisSubscriber.

(SubscriberListeneralsoinheritsmethodsfromtheDataReaderListener)

TopicListener on_inconsistent_topic() Another,different,TopicexistswiththesamenameasthisTopic.

CoreDXDDSProgrammer’sGuide

78

Listener ListenerMethods Description

DomainParticipantListener

(none) (DomainParticipantListenerinheritsmethodsfromtheDataReaderListener,SubscriberListenerandtheTopicListener)

79

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

80

Chapter9 Topics

9.1 Overview

Topicsconnectpublicationsandsubscriptions.Publicationsmustbeknowninsuchawaythatsubscriptionscanrefertothemunambiguously.ATopicismeanttofulfillthatpurpose:itassociatesaname,adata-type,andQoSrelatedtothedataitself.

Eachtopiccorrespondstoonedatatype.However,severaltopicsmayrefertothesamedatatype.

TopicshaveaQualityofService(QoS)thatdescribesthedatawrittentothattopic.ThetopicQoScanbespecifiedwhencreatingthetopic,orlaterbycallingtheset_qos()operationonthetopic.TheQoSdefinedforthetopicisnotusedbyCoreDXDDS,butmaybeusedbytheapplicationasahintfortheQoSofthecorrespondingDataReadersandDataWriters.AdditionalinformationonQoSpoliciescanbefoundintheQualityofServiceFeatureschapter.

Thereareseveralvariationsofatopic.ThebaseclassforalltopicsisaTopicDescription.TheTopicDescriptioncontainsthetopicnameanddata-typename.Therearethree(3)variationsofaTopicDescription.TheyarelistedinTable9-1.

Table9-1:TopicVariants

TopicVariants Description

Topic ThebasicformofaTopicDescription,itcontainsadescriptionofthedatatobepublishedandsubscribedto,includingQoSandListeners.

ContentFilteredTopic Thistopicallowsforcontent-basedsubscriptions,thatis,asubscriptionthatreceivesasubsetofthedatapublishedbasedonaSQL-likequerycondition.

Formatted: Font:Italic

Deleted: QualityofServiceFeatures

81

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

MultiTopic Thistopicallowsforcombiningandfilteringdatafromseveraltopics.

CoreDXDDScurrentlydoesnotsupportMultiTopics.

Topicsarecreatedusingoneofthecreate_topic()operationvariationsprovidedfromtheDomainParticipant.

Ingeneral,apublishingapplicationwillcreateaTopic,andassociateeachDataWritertoexactlyoneTopic.AsubscribingapplicationwillcreateaTopicandifusingacontentfilter,createaContentFilteredTopicbasedonthatTopic,andassociateeachDataReadertoexactlyoneTopicDescriptionorContentFilteredToipcDescription.

9.2 Built-InTopics

TheCoreDXDDSinfrastructuremanagesasetofbuilt-intopics.ThesetopicsarecreatedwhenaDomainParticipantisinitialized,andkeeptrackofdiscoveryinformationaboutotherDDSparticipants,Topics,DataReaders,andDataWriters.ThisinformationisnecessaryfortheDDSdiscoverytoworkproperly,andmayalsobeusefultoapplicationsthatwanttoreacttothisdiscoveryinformation.

Table9-2liststhebuilt-intopicsandtheirassociateddatatypes.

Table9-2:Built-inTopics

Built-inTopicName

DataTypeName Description

DCPSParticipant DDS::ParticipantBuiltinTopicData EachsampleisadescriptionofaDDSparticipantthathasbeendiscoveredbythisDomainParticipant

DCPSTopic DDS::TopicBuiltinTopicData EachsampleisadescriptionofaTopicdiscoveredbythisDomainParticipant

DCPSPublication DDS::PublicationBuiltinTopicData EachsamplesisadescriptionofaDataWriterdiscoveredbythisDomainParticipant

Deleted: ... [1]

CoreDXDDSProgrammer’sGuide

82

DCPSSubscription DDS::SubscriptionBuiltinTopicData EachsampleisadescriptionofaDataReaderdiscoveredbythisDomainParticipant

Ingeneral,thebuilt-indatatypesholdinformationaboutthediscoveredentity’sQoSconfiguration,alongwithotherusefulinformation.Foradetaileddescriptionofthesebuilt-indatatypes,refertothedds_builtin.hordds_builtin.hhheaderfilesintheCOREDX_TOP/target/COREDX_TARGET/include/ddsdirectory.

Eachbuilt-intopichasatype-specificDataReaderassociatedwithit(DCPSParticipantDataReader,etc.).TheapplicationcanusetheseDataReaderstoaccessthedataandstatusesfromthebuilt-intopicsinthesamewayanyuserdefinedDataReaderwoulddothis.

Togetaccesstothesebuilt-inDataReaders,theapplicationcancall

DomainParticipant::get_builtin_subscriber()

ThisSubscribercanbeusedtoaccessspecificbuilt-indatareadersbycalling

Subscriber::lookup_datareader(topic_name)

andusingtheappropriatetopicnamefrom

Table9-2(forexample:DCPSPublication).

Thebuilt-intopicsusedatatypesspecifiedintheDDSstandardforcommunicatingdiscoverydata.Thefollowingtablesillustratethedatatypeofeachofthebuilt-intopics.

Table9-3:ParticipantBuilt-inDataType

ParticipantBuiltinTopicData

struct ParticipantBuiltinTopicData { DDS_KEY BuiltinTopicKey_t key; UserDataQosPolicy user_data; };

Deleted: ... [2]

83

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Table9-4:TopicBuilt-inDataType

TopicBuiltinTopicData

struct TopicBuiltinTopicData { DDS_KEY BuiltinTopicKey_t key; string name; string type_name; DurabilityQosPolicy durability; DurabilityServiceQosPolicy durability_service; DeadlineQosPolicy deadline; LatencyBudgetQosPolicy latency_budget; LivelinessQosPolicy liveliness; ReliabilityQosPolicy reliability; TransportPriorityQosPolicy transport_priority; LifespanQosPolicy lifespan; DestinationOrderQosPolicy destination_order; HistoryQosPolicy history; ResourceLimitsQosPolicy resource_limits; OwnershipQosPolicy ownership; TopicDataQosPolicy topic_data; };

Table9-5:PublicationBuilt-inDataType

PublicationBuiltinTopicData

struct PublicationBuiltinTopicData { DDS_KEY BuiltinTopicKey_t key; BuiltinTopicKey_t participant_key; string topic_name; string type_name; DurabilityQosPolicy durability; DurabilityServiceQosPolicy durability_service; DeadlineQosPolicy deadline; LatencyBudgetQosPolicy latency_budget; LivelinessQosPolicy liveliness;

CoreDXDDSProgrammer’sGuide

84

ReliabilityQosPolicy reliability; LifespanQosPolicy lifespan; UserDataQosPolicy user_data; OwnershipQosPolicy ownership; OwnershipStrengthQosPolicy ownership_strength; DestinationOrderQosPolicy destination_order; PresentationQosPolicy presentation; PartitionQosPolicy partition; TopicDataQosPolicy topic_data; GroupDataQosPolicy group_data; };

Table9-6:SubscriptionBuilt-inDataType

SubscriptionBuiltinTopicData

struct SubscriptionBuiltinTopicData { DDS_KEY BuiltinTopicKey_t key; BuiltinTopicKey_t participant_key; string topic_name; string type_name; DurabilityQosPolicy durability; DeadlineQosPolicy deadline; LatencyBudgetQosPolicy latency_budget; LivelinessQosPolicy liveliness; ReliabilityQosPolicy reliability; OwnershipQosPolicy ownership; DestinationOrderQosPolicy destination_order; UserDataQosPolicy user_data; TimeBasedFilterQosPolicy time_based_filter; PresentationQosPolicy presentation; PartitionQosPolicy partition; TopicDataQosPolicy topic_data; GroupDataQosPolicy group_data; };

9.3 ContentFilteredTopics

85

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

AContentFilteredTopicisaspecializationofTopicDescriptionthatallowsthesubscribingapplicationtodescribeasubscriptionwhereitwillonlyseeasubsetofthedatapublished,basedonadefinedcontentfilter.ThefilterisanSQLlikestatement.TheContentFilteredTopicisassociatedwithanotherknownTopicandappliesafiltertothedataavailableonthatrelatedtopic.

ContentFilteredTopicsarecreatedbyaDomainParticipant,justlikenormalTopics.

DomainParticipant::create_contentfilteredtopic()

ThismethodcallhasadditionalparameterstospecifywhichtopictheContentFilteredTopicisassociatedwith,theSQLqueryexpression,andparameters(ifany)foruseinevaluatingthefilterexpression.

Table9-7:create_contentfilteredtopic()parameters

Parameter Description

Topic Relatedtopic.TheContentFilteredTopicpresentsafilteredsubsetofdataavailableontherelatedtopic.

filter_expression SQLlikeconditionexpression

filter_parameters Stringsequenceofparametersusedinthefilter_expression.

Thefilter_expressionmustbeavalidSQLWHEREclause(withouttheWHEREkeyword).Forexample“x<=4”.ThefilterexpressionreferstostructuremembersintheapplicationdefineddatatypeassociatedwiththerelatedTopic.Forembeddedstructures,thenamingconventionusesadot(‘.’)toseparatefieldnames.Forexample,“time.sec>10”.Table9-8listsalltheoperatorsavailablewhenconstructingthecondition.

Table9-8:ValidConditionOperatorsforContentFilters

Operator Description

= Equals

CoreDXDDSProgrammer’sGuide

86

Operator Description

<> Notequals

>= Greaterthanorequal

> Greaterthan

<= Lessthanorequal

< Lessthan

NOT,not Notoperator

() Parenthesisareusedfornestingconditions

AND,and Andoperator

OR,or Oroperator

IN,in Inoperatorformatchingavaluetosomethinginalist

BETWEEN,between Forfutureuse:thebetweenoperatorisnotyetsupportedbyCoreDXDDS.

LIKE,like Forfutureuse:thelikeoperatorisnotyetsupportedbyCoreDXDDS.

Thefilterexpressioncanalsocontainreferencestoparameters,presentinthefilter_parametersargument.Parameterreferencestaketheform“%<number>”.Thenumberisanindexintothefilter_parameterssequence,andstartsatzero.Forexample“%2”referstothethirdparameterinthefilter_parameterssequence.

OncecreatedContentFilteredTopicscanbeusedbyaDataReaderjustlikeanormalTopic.Thefilterexpressionisstatic,andcannotbechangedaftertheContentFilteredTopiciscreated;however,filterparameterscanbechangedontheflywithacallto

ContentFilteredTopic::set_expression_parameters()

87

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

ContentFilterexpressionscancontainreferencestobasicdatatypes.Forexample,datamembersoftypeint,short,long,andstringareallvalidfieldtypesforafilterexpression;but,sequences,arrays,orunionsarenot.

9.3.1 ContentFilterExampleThefullcodeforacontentfilterexamplecanbefoundintheexamplesdirectoryoftheCoreDXDDSrelease.

Table9-9:CreatingaContentFilteredTopic

CreatingaContentFilteredTopic(Clanguage)

DDS_DomainParticipant dp; DDS_Subscriber sub; DDS_Topic top; DDS_ContentFilteredTopic cftop; DDS_TopicDescription td; DDS_DataReader dr; DDS_StringSeq cf_params; dp = DDS_DomainParticipantFactory_create_participant( 1, DDS_PARTICIPANT_QOS_DEFAULT, NULL, 0); sub = DDS_DomainParticipant_create_subscriber(dp, DDS_SUBSCRIBER_QOS_DEFAULT, NULL, 0);

MyTypeTypeSupport_register_type( dp, “topic_type” ); top = DDS_DomainParticipant_create_topic(dp, “topic_name”, “topic_type”, DDS_TOPIC_QOS_DEFAULT, NULL, 0);

/* BUILD A CONTENT_FILTERED TOPIC */

cftop = DDS_DomainParticipant_create_contentfilteredtopic(dp, “cf_topic_name”, top, "x<%0", NULL);

/* parameters can be specified/modified after creation */ INIT_SEQ(cf_params); seq_set_size(&cf_params, 1); seq_set_length(&cf_params, 1); cf_params._buffer[0] = "5";

DDS_ContentFilteredTopic_set_expression_parameters(cftop, &cf_params);

td = DDS_Topic_TopicDescription((DDS_Topic)cftop);

dr = DDS_Subscriber_create_datareader(sub, td, &dr_qos, NULL, 0);

if (!dr) printf("FAILED to create DR!\n");

CoreDXDDSProgrammer’sGuide

88

9.3.2 ConfiguringContentFiltersWhenaDataReaderusesacontentfiltertofilterthereceiveddata,thefilterexpressioniscommunicatedtoanymatchingDataWriter(s).ThisallowsCoreDXDDStofilterdataeitherattheDataWriterortheDataReader.

TheDataReader’scontentfilterisalwaysenabled.Thisensuresthespecifieddataisalwaysfiltered,evenwhentheDataReaderismatchedwithaDataWriterthatdoesnotsupportwriter-side-filtering(forexample,thismayhappenwheninteroperatingwithanotherDDSimplementation).

DataWritercontentfilteringisconfigurablebytheDataWriterQoSpolicy:RTPSWriterQosPolicy.apply_filters(trueorfalsevalue).

DataWriterfilteringisenabledbydefault.ThismeanstheDataWriterwillwritedatatoaDataReaderonlywhenitpassestheDataReader’scontentfilter(oriftheDataReaderdoesnothaveacontentfilterconfigured).Thisconfigurationcanreducethe‘work’performedbytheDataReadertoapplythefilter,butalsomeanstheDataWritermustunicastallsamplesthatarefilteredbyatleast1matchedDataReader.

WhentheDataWriterisconfiguredtoNOTapplyfilters,theDataWriterwillalwaysmulticastwrittendatasamples,allowingtheDataReadertoapplythefilter.

9.3.3 CompilinganapplicationwithContentFiltersCoreDXDDSprovidesanalternatelibrarythatcontainstheContentFiltercapability.ThisallowsthebasicCoreDXDDSlibrarytostayextremelysmall.Tocompileanapplicationthatusescontentfilters,changethelibrarylineinyourMakefile,replacinglibddswithlibdds_cf.FortheC++languagebinding,youwillalsoneedtoreplacelibdds_cppwithlibdds_cpp_cf.

TheJavaandC#languagebindingcontainallCoreDXDDSfunctionalityinonelibrary,includingthecontentfilterAPIandfunctionality.

9.4 MultiTopics

AMultiTopicisaspecializationofTopicDescriptionthatallowstheapplicationtodescribeasubscriptionthatcombines,filters,andordersdatafrommultipleTopics.ThisissimilartotheJOINstatementinSQLandRelationalDatabaseSystems.

CoreDXDDScurrentlydoesnotsupportmultitopics.

CoreDXDDSProgrammer’sGuide

90

Chapter10 InstancesandSamples

Dataisthecoreofanycommunicationsmiddleware,anditisespeciallyimportanttoadata-centric,publish-subscribemiddlewarelikeCoreDXDDS.ThischapterdescribeshowtheCoreDXDDSmiddlewarehandlesandclassifiesthedata,andhowthedataispackagedandcommunicatedbetweentheapplicationandtheCoreDXDDSmiddleware.

10.1 OverviewEachTopicisattachedtoaDDSdatatype.OnlydataofthattypemaybepublishedontheTopic.TheDDSdatatypeisalwaysastructure,whichcanbemadeupofvirtuallyanyuserdefinedtype.ThefollowingisanexampleofaDDSdatatype.

struct HelloMessage { long time_sent; long sender_id; string sender_name; string msg; sequence<string> msg_history; }

ThetypenamefortheaboveDDSdatatypeis“HelloMessage”.

AdditionalinformationonthegeneratingDDSdatatypescanbefoundintheApplicationDataTypeschapter.

TheCoreDXDDSmiddlewareclassifiesdataintosamplesandinstances.AsampleisdataoftheappropriateDDSdatatypethathasbeenpublishedtoaDDSTopic.ThefollowingisapossiblesampleoftheHelloMessagedatatype:

123456789 42 “Bob The Builder” “Hello out there!” <empty sequence>

Formatted: Font:Italic

Deleted: ApplicationDataTypes

91

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Theapplicationdeveloper,whencreatingaDDSdatatype,canspecifyoneormoreattributesoftheDDSdatatypeasakey.TheCoreDXDDSmiddlewareusesthosekeyattributestoorganizethepublisheddata.GoingbacktotheHelloMessageexampleabove,anapplicationdevelopermightspecifythe“sender_id”fieldasthekeyfortheHelloMessagedatatype.

Apublishingapplicationmightwritethefollowingfour(4)samples:

IftheDataTypedefinesthe“sender_id”fieldasthekeyfortheHelloMessagedatatype,theninthe4samplespublished,thereare3uniquekeys.TheCoreDXDDSmiddlewareclassifiesallsampleswiththesamekeyvaluetobeone(1)instance.Inthisexample,3instanceshavebeenpublished,withthefollowingkeys:42,45,and12.ThisisdepictedinTable10-1.

123456789 42 “Bob The Builder” “Hello out there!” <empty sequence>

223456789 45 “Wendy” “Busy day today” <empty sequence>

323456789 42 “Bob The Builder” “Can We Build It?” <empty sequence>

423456789 12 “Scoop” “Yes we can!” <empty sequence>

CoreDXDDSProgrammer’sGuide

92

Table10-1:InstanceExample

Instance1,Key=42

2samples

Instance2,Key=45

1sample

Instance3,Key=12

1sample

123456789 42 “Bob The Builder” “Hello out there!” <empty sequence>

223456789 45 “Wendy” “Busy day today” <empty sequence>

423456789 12 “Scoop” “Yes we can!” <empty sequence>

323456789 42 “Bob The Builder” “Can We Build It?” <empty sequence>

TheCoreDXDDSmiddlewarestoresandmanagesdatasamples(anindividualstructureprovidedtowrite()andreturnedfromread())andinstances(acollectionofzeroormoresampleswiththesamekeyvalue).

10.2 PublishingDataOnthepublishingsideofDDScommunications,samplesrepresentdatathatissenttoDataReaders.Samplesarecreatedforeverywrite(),unregister(),anddispose()callmadebytheapplication.Eachsamplewrittenisassociatedwithaparticularinstance.Ingeneral,samplesandinstancesarestoredbytheDataWriteruntiltheyaredeliveredtoallappropriateDataReaders,atwhichpointthesamplesandinstancesmayberemoved.ThespecificrulesformaintainingsamplesintheDataWriteraredifferentfromtherulesformanaginginstances.Forthisreason,itispossibleforallsamplesonaninstancetoberemovedfromtheDataWriter,whiletheinstanceremains(withnoassociatedsamples).Incontrast,itisnotpossibletoremoveaninstancefromtheDataWriterwhileanysamplesassociatedwithitremain.

DatainstancesareusedtomanageseveralDataWriterQoSpolicies.InstancesallowtheapplicationtosetDeadlines,keepHistory,manageOwnership,andfollowResourceLimits.ForadditionalinformationontheseQoSpolicies,seetheQualityofServiceFeaturesChapter. Formatted: Font:Italic

Deleted: QualityofServiceFeatures

93

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

10.3 SubscribingtoDataOnthesubscribingsideofCoreDXDDScommunications,samplesrepresentthedatathathasbeenreceivedbythemiddlewareandmaybemadeavailabletothesubscribingapplication(filtersorotherQoSpolicysettingsmayprecludesamplesfromreachingtheapplication).Eachreceivedsampleisassociatedwithaparticularinstance.

Ingeneral,samplesandinstancesarestoredintheDataReaderuntiltheyareexplicitlyremovedbythesubscribingapplication(seeSection8.3.7Read(orTake)Datafordetails),ortheCoreDXDDSmiddlewareremovesthembasedonvariousQoSpolicysettings.SimilartotheDataWritermanagement,thespecificrulesformaintaininganddeletingsamplesfromtheDataReaderaredifferentfromtherulesformaintaininganddeletinginstances.Forthisreason,itispossibleforallsamplesonaninstancetoberemoved,whiletheinstanceremains(withnoassociatedsamples).Incontrast,itisnotpossibletoremoveaninstancewhileanysamplesassociatedwithitremain.

10.4 InstanceLifecyclesInstancesareusedtomanagethedatalifecycle.Instancesarecreated(registered),updated(written),anddeleted(unregisteredordisposed).Forexample,considerthethreeinstancesabove.Instancekey=12(Scoop)mayshutdownforthedaywhiletheothertwoinstances(BobandWendy)arestillworking(andupdating).Thepublishingapplicationcancalldispose()onScoop(instancekey=12)andtheremaininginstances(BobandWendy)willstillbealive.WhenScoopcomesonlineagain,thepublishingapplicationcanstartupdatingthatinstance(whichwillretainthesameinstancehandle).Thesedatalifecycleoperationsarecoveredindetailinthefollowingsections.

10.4.1 RegisteringInstancesInstancesmustberegisteredwiththeDataWriterbeforeanysamplesassociatedwiththatinstancecanbewritten(ordeleted).Asaconvenience,CoreDXDDSwillautomaticallyregisteraninstancewhentheapplicationcallsoneofthewrite(),unregister_instance(),ordispose()operationswithoutfirstregisteringtheinstance.

PublishingapplicationscanalsoexplicitlyregisteraninstancebycallingDataWriter::register_instance().Theregister_instance()operationreturns

Formatted: Font:Italic

Deleted: 8.3.7Formatted: Font:Italic

Deleted: Read(orTake)Data

CoreDXDDSProgrammer’sGuide

94

aninstancehandlewhichcanbeusedtoimprovetheperformanceofsubsequentcallstowrite().

ThebelowexampleillustratestheuseofDataWriter::register_instance()andDataWriter::write().

Example(C++)

HelloMessageDataWriter dw; HelloMessage bobData, wendyData; InstanceHandle_t bobHandle, wendyHandle; ReturnCode_t retval; bobData.sender_id = 42; bobData.sender_name = strdup(“Bob the Builder”); bobData.msg = strdup(“Hello”); wendyData.sender_id = 45; wendyData.sender_name = strdup(“Wendy”); wendyData.msg = strdup(“Good Morning, Bob!”); /* calling write() without an instance handle forces * CoreDX DDS to register this instance (key=42) */ retval = dw . write( bobData, HANDLE_NIL ); /* the instance can later be ‘looked up’ */ bobHandle = dw. lookup_instance( bobData ); /* Calling register_instance() first allows for * subsequent optimized calls to write() */ wendyHandle = dw . register_instance( wendyData ); retval = dw . write( wendyData, wendyHandle ); delete[] wendyData.msg; wendyData . msg = strdup( “Good night, everyone!” ); /* Changing the ‘msg’ in wendyData does not change the * key value, and therefore does not change the instance * or instance handle. */ retval = dw . write( wendyData, wendyHandle );

Figure10-1:RegisterInstancesExample

95

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

RegisterinstanceoperationsareapplicableonlytoDataWriters,andarenotcommunicatedtoDataReaders.Infact,DataReadersdonothaveaconceptofregisteredinstances.Instead,aDataReaderhasaconceptofanAliveinstancestate.InstanceshaveanAlivestateiftheyhaveatleastonealiveDataWriteractivelywritingdatasamplesontheinstance.RefertoSection8.4SampleStatusInformation(SampleInfo)foradditionalinformationoninstancestates.Inordertomanageinstancestates,DataReadersstorealistofalive,activelywritingDataWritersforeachinstance.

CoreDXDDScansupportmillionsofuniqueinstancesineachDataWriterandDataReader.

10.4.2 UnregisteringInstancesThepublishingapplicationcanunregisterpreviouslyregisteredinstancesbycallingtheDataWriter::unregister_instance()operation.Thisindicatestheapplicationwillnolongerbewritinganysamplesforthisinstance.Thisisnotthesameasdisposingtheinstance(whichindicatestheinstancenolongerexists).TheunregisteroperationsimplyindicatesthatthisDataWriterwillnolongerbepublishingupdatesontheinstance.CoreDXDDStreatsanunregistercommandverymuchlikeanapplicationwrittendatasample.TheunregistercommandisstoredbytheDataWritertobecommunicatedtomatchedDataReaders.Iftheinstanceforthisunregistersampleisnotalreadyregistered,CoreDXDDSwillautomaticallyregisteritbeforeprocessingtheunregisteroperation.

Afteranunregisteroperation,theinstancehandleassociatedwiththeunregisteredinstanceisinvalid.ThisisbecausetheCoreDXDDSmiddlewaremayhaveremovedallrecordsofthatinstance.Afteranunregisteroperation,theinstancehandlemaybereusedforadifferentinstance.Theapplicationmayre-registertheinstanceandthencontinuetopublishsamplesoradisposeontheinstance.UnregisteroperationsarecommunicatedtomatchedDatasReadersasasamplewiththevalid_dataflagsettofalseandindicatethattheDataWriterisnolongeractivelywritingonthisinstance.TheDataReaderwillremovethisDataWriterfromtheinstance’slistofactiveDataWriters.Whenthislistofalive,activelywritingDataWritersbecomesempty,thestateoftheinstanceintheDataReaderCachewillchangetoNOT_ALIVE_NO_WRITERS.RefertoSection8.4Sample

StatusInformation(SampleInfo)foradditionalinformationoninstancestates.

WhenaDataWriterisdeletedbythepublishingapplication,CoreDXDDSwillautomaticallysendanunregistermessagetomatchedDataReadersfor

Formatted: Font:Italic

Deleted: SampleStatusInformation(SampleInfo)

Formatted: Font:Italic

Deleted: SampleStatusInformation(SampleInfo)

CoreDXDDSProgrammer’sGuide

96

everyinstancetheDataWriterknowsabout.IfthepublishingapplicationexitswithoutdeletingitsDataWriterEntities,theDataReaderwillnotreceivetheunregistercommands.Inthiscase,theDataReaderwilleventuallydeterminetheDataWriterisnotalive(basedonLivelinessQoSconfigurations),andremovetheDataWriterfromthelistofaliveandactivelywritingDataWritersoneachinstancetheDataReaderknowsabout.

10.4.2.1 RelationshipbetweenDataWriter::unregisterandotherQoSPoliciesUnregisteringaninstanceonaDataWriterconfiguredforExclusiveOwnership(viatheOwnershipQoSPolicy)willcausetheDataWritertorelinquishownershipoftheinstance.OtherExclusiveOwnershipDataWritersmaytakeoverownershipfortheinstance.

DataWritersconfiguredwithTransientLocalDurabilitywillremovetheinstance(andallassociatedsamples)afterallcurrentlyaliveandmatchedDataReadersacknowledgereceivingallsamplesontheinstance.

DataReadersconfiguredwithauto_purge_no_writerssetintheirReaderDataLifecyclemaydeletetheinstance(andallassociatedsamples),iftheDataWriterthatsentthisunregistercommandwasthelastactiveDataWriteronthisinstance.

10.4.3 DisposingInstancesThepublishingapplicationcandisposepreviouslyregisteredinstancesbycallingtheDataWriter::dispose()operation.Thisindicatesthattheinstancenolongerexists.Thisisdifferentthantheunregisteroperation(whichindicatesthisDataWriterisnolongerwritingonthisinstance).CoreDXDDStreatsadisposeverymuchlikeanapplicationwrittendatasample.ThedisposecommandisstoredbytheDataWritertobecommunicatedtomatchedDataReaders.Iftheinstanceforthisdisposesampleisnotalreadyregistered,CoreDXDDSwillautomaticallyregisteritbeforeprocessingthedisposeoperation.

DisposeoperationsarecommunicatedtomatchedDataReadersasasamplewiththevalid_dataflagsettofalse.TheDataReaderwillchangethestateoftheassociatedinstancetoNOT_ALIVE_DISPOSED.RefertoSection8.4SampleStatusInformation(SampleInfo)foradditionalinformationoninstancestates.NotethattheDataWriterwillstillbeconsideredanalive,activelywritingDataWriteronthisinstance.

10.4.3.1 RelationshipbetweenDisposeandotherQoSPolicies

Formatted: Font:Italic

Deleted: SampleStatusInformation(SampleInfo)

97

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

DataReadersconfiguredwithauto_purge_disposedsetintheirReaderDataLifecyclewilldeletetheinstance(andallassociatedsamples)onreceiptofadisposecommand.

10.4.4 InstanceHandlesAninstancehandleisavaluethatcanbeusedtouniquelyidentifyaregisteredinstancewithinoneDataWriterorDataReader.AninstancehandleisgeneratedbyaDataWriterwhenaninstanceisregistered(returnedfromaDataWriter::register_instance()call)andforthatDataWriteritwillbeusedtoidentifytheinstanceuntilthatinstanceisunregistered.TheinstancehandleisvalidonlyfortheDataWriterthatcreatedit,andonlywhiletheinstanceisregistered.Onceaninstanceisunregistered,theinstancehandlecannolongerbeusedtoidentifythatinstance.ThisisacriticaldetailoftheCoreDXDDSmiddleware.Theseinstancehandlesarereused,andafteranunregisteroperation,theoldinstancehandlemayidentifyadifferentinstance.Iftheunregisteredinstanceisre-registered,adifferenthandlemaybeassignedforthenext‘life’ofthatinstance.

10.5 DataCacheDataReadersandDataWriterscontainaDataCacheforstoringdatasamplesandinstances.TheDataWriter’sDataCachecontainssamplesandinstancesthathavebeenwritten,andtheDataReader’sDataCachecontainssamplesandinstancesthathavebeenreceived.ThesedatacachesaresizedandmanagedaccordingtotheconfigurationoftheseveralQoSpoliciesasshowninthefigurebelow.

Table10-2:InstanceExample

QoSPolicy Configuringthispolicyonthe: WilleffectCacheManagementonthe:

RELIABILITY DataWriterandDataReader

DataReader

DataWriter

DataReader

DURABILITY DataWriter DataWriterandDataReader

HISTORY DataWriter

DataReader

DataWriter

DataReader

CoreDXDDSProgrammer’sGuide

98

QoSPolicy Configuringthispolicyonthe: WilleffectCacheManagementonthe:

RESOURCE_LIMITS DataWriter

DataReader

DataWriter

DataReader

READER_DATA_LIFECYCLE DataReader DataReader

WRITER_DATA_LIFECYCLE DataWriter DataReader

OWNERSHIP DataWriter DataReader

LIFESPAN DataWriter DataWriterandDataReader

Filters(TIME_BASED_FILTER,contentfilters)

DataReader DataReader

Ingeneral,datasamplesareaddedtotheDataCacheastheyarewritten(foraDataWriter)orreceived(foraDataReader).Ingeneral,thesesamplesareremovedwhentheyarenolongerneededbytheapplicationortheCoreDXDDSmiddleware.ThespecificmanagementofsamplesintheDataCachesisdescribedinthefollowingsections.

Ingeneral,datainstancesareaddedtotheDataCacheastheyareregistered(foraDataWriter)orreceived(foraDataReader).Ingeneral,theseinstancesareremovedwhentheyarenolongerneededbytheapplicationortheCoreDXDDSmiddleware.Themanagementandremovalofinstancesisdifferentthansamples,andinfact,itispossibleforinstancestobemanagedintheDataWriterandDataReaderDataCachesevenwhentherearenosamplesassociatedwiththeinstanceintheDataCache.ThespecificmanagementofinstancesintheDataCachesisdescribedinthefollowingsections.

10.5.1 DataWriterCacheTheDataWriter’sDataCachecontainssamplesthathavebeenwrittenbyacalltoDataWriter::write()variantandinstancesthathavebeenregistered(orwritten,sincecallingDataWriter::write()automaticallyregistersaninstance).

99

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

10.5.1.1 SamplesintheDataWriterCacheSamplesareaddedtotheDataCacheastheyarewrittenbytheapplication.SampleswillbestoredntheDataWriterCacheuntiltheyareinitiallywrittentothewire,andmaybestoredlongertomeetReliabilityandDurabilityQoSsettings.Samplescanberemovedfromthecachebytheapplication(callingDataWriter::unregister())orbytheCoreDXDDSinfrastructure,basedonQoSpolicysettings.SamplesareremovedfromtheDataWritercacheunderthefollowingconditions:

1. TheCoreDXDDSmiddlewareinthepublishingapplicationhascompletedwritingthesample.Thishappenswhen:

a. TheCoreDXDDSmiddlewarewritesthesampletoallBestEffortDataReadersAND

b. (OnlyiftheDataWriterisReliableandVolatile)TheCoreDXDDSmiddlewarehasreceivedanacknowledgementfromallmatchedReliableDataReaders

2. OR:SamplesexpirebasedontheLifespanduration3. OR:ADataWriterhasaHistoryQoSPolicykindofKEEP_LASTandthe

cachealreadyholdsHistorydepthsamplesandanewsampleiscreatedbywrite(),unregister()ordispose()

4. OR:ABestEffortDataWriterhasnon-INFINATEmax_samplesormax_samples_per_instanceResourceLimitsandthecachealreadyholdsthemaximumsamplesandanewsamplesiscreatedbywrite(),unregister()ordispose().

ItisimportanttonotethatsomecombinationsofQoSsettingswillcausetheDataWritercachetogrowinfinitely,consumingmoreandmoreruntimememory.ThiscanhappenwithaDurabilitykindofTRANSIENT_LOCALandReliabilitykindofRELIABLE,aHistorykindofKEEP_ALL,andResourceLimitssettoinfinite.WiththiscombinationofQoSsettings,theapplicationmustmanageinstancestomeetapplicationormachineresourcelimitations.

10.5.1.2 InstancesintheDataWriterCacheInstancesareaddedtotheDataWriterCachewhenthepublishingapplicationregistersaninstancethatisnotalreadyregistered.Everysamplebelongstoaninstance,andtheinstancemustberegisteredbeforeasampleonthatinstancesamplescanbecreated.TheapplicationcanexplicitlyregisteraninstancebycallingDataWriter::register_instance(),orCoreDXDDSwillautomaticallyregistertheinstancewhentheapplicationattemptstocreateasamplewithoutfirstregisteringitsassociatedinstance.

CoreDXDDSProgrammer’sGuide

100

InstancesareremovedfromtheDataWriterCachewhenthepublishingapplicationunregistersaninstance.ThismustbedoneexplicitlybycallingDataWriter::unregister_instance().

10.5.2 DataReaderCacheTheDataReader’sDataCachecontainssamplesandinstancesthathavebeenreceived(subjecttofilters).Thesesamplesandinstancesmayormaynothavebeenalreadyread(seen)bytheapplication.

10.5.2.1 SamplesintheDataReaderCacheSamplesareaddedtotheDataReaderCachewhentheyarereceivedbytheDataReaderandthesamplepassesanyfiltersconfiguredontheDataReaderandthereisroomintheDataReaderCacheforthenewsample.IfthereisnotroomintheDataReaderCache,thenewsamplewillbeaddedonlyiftheHistoryQoSpolicyisconfiguredtoKEEP_LAST.

SamplesareeligibletoberemovedfromtheDataReadercacheunderthefollowingconditions:

1. WhentheapplicationusesDataReader::take().2. IftheLifespanQoSisused,sampleswillberemovedfromthedata

cacheaftertheyareexpired.3. IftheDataCacheisfullandtheHistorykindisKEEP_LAST,theoldest

samplewillberemovedtomakeroomforanewlyreceivedsample.4. WhenaBestEffortDataReaderhasnon-INFINITEmax_samplesor

max_samples_per_instanceResourceLimitsandthecachealreadyholdsthemaximumsamplesandanewsampleisreceived.

5. WhenaDataReaderhasnon-INFINITEautopurge_nowriter_samples_delayorautopurge_disposed_samples_delayandaninstancestateisdeterminedtobeNOT_ALIVE_NO_WRITERSorNOT_ALIVE_DISPOSED;(associatedsampleswillberemovedafterthespecifieddelay)

10.5.2.2 InstancesintheDataReaderCacheInstancesareaddedtotheDataReaderCachewhenasamplebelongingtotheinstanceisreceivedbytheDataReaderandtheinstancedoesnotalreadyexistintheDataReaderCache.TheinstanceiscreatedeveniftheassociatedsampleisnotaddedtotheDataReaderCache.SamplesmaynotbeaddedtotheDataReaderCachebecauseoffiltersappliedontheDataReaderorbecauseoftheconfigurationoftheHistoryandResourceLimitsQoSpolicies.

101

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

InstancesareeligibletoberemovedfromtheDataReaderCachewhenaninstancehasastateofNOT_ALIVE_NO_WRITERSandtherearenoassociatedsamples.

CoreDXDDSProgrammer’sGuide

102

Chapter11 ApplicationDataTypes

11.1 OverviewEveryDDSTopiccontainsoneandonlyoneDataType,auserdefineddatatypethatisusedwhencommunicatingontheTopic.Inmostcases,theapplicationdeveloperdefinestheseDDSDataType(s)aheadoftimesotheymaybecompiledintotheapplicationinthealanguage-independentformat.TheInterfaceDefinitionLanguage(IDL)andeXtensibleMarkupLanguage(XML)formatsareavailableforDDSdatatypedefinition.Acompilerisusedtotranslatethesetypedefinitionsintotheappropriateprogramminglanguageforinclusionintoanapplication.

CoreDXDDSalsosupportsdynamictypes,whichareDataTypesthatarenotdefinedatcompiletype.Withdynamictypes,itispossibletodynamicallypublishandsubscribetoadiscoveredTopicwithadiscoveredDataType.Inthisscenario,theapplicationhasnoknowledgeofthedatatypeuntiltheTopicisdiscoveredatruntime.AcompletediscussionofdynamictypescanbefoundinChapter18:DynamicTypes.

11.2 WhyDefinetheDataTypes?CoreDXDDSisdata-centric.ThismeansthatthestructureandcontentsofapplicationdataisknownandusedbytheCoreDXDDSmiddleware.ThisallowstheCoreDXDDSmiddlewaretoperformadvanceddatamanagementoperationsthatarenotavailableinothermessageorientedmiddlewaretechnologies.Forexample,instanceandsamplehistoryareenabledbyidentifying‘key’fieldsinthedatatoidentifyuniquedatainstances.Thiscanbecomparedtokeyfieldsinrelationaldatabasetechnologies.Eachkeyuniquelyidentifiesacollectionofrelatedrecords.InDDS,thekeyisusedtoidentifyadata‘instance’.Updatestoadatainstancearereferredtoas‘samples’.TheCoreDXDDSmiddlewarecanmaintainhistoricalsamplesforeachinstance(seetheHISTORYQualityofService).Furthermore,theCoreDXDDSmiddlewarecanapplyaContentFiltertodatasamples.ContentfiltersarecomparabletoanSQLquerythatselectsasub-setofavailabledatabasedonconditions.Theseareafewexamplesofthepowerthatadata-centricmiddlewarecanoffer.

Furthermore,becausethedatatypesarewellknown,theDDSAPIandcompilerscanenforcetheusageofpropertypesthroughouttheapplication

103

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

code.Thiscanavoidpotentiallydifficultbugsrelatedtosubtlemismatchesofdatathroughoutthedistributedsystem.

Thebenefitsofdata-centricmiddlewarearepossiblebecausethemiddlewarehasanunderstandingofthedatastructuresusedinyourapplication.PartoftheDDSdevelopmentworkflowincludesdefiningtheapplicationdatatypesandregisteringthemwiththeCoreDXDDSmiddleware.

11.3 DataTypesandDiscoveryDataTypesplayanimportantroleintheprocessofDDSdynamicdiscovery.(AdditionalinformationonCoreDXDDSdiscoverycanbefoundinPart4:Chapter16CoreDXDDSDiscovery).ADataWriterwillmatchwithaDataReaderonlyifthedatatypepublishedbytheDataWriteriscompatiblethedatatypesubscribedtobytheDataReader.ThisprovidesadditionaltypesafetyforDDSapplicationsbecauseaDataReadercannotreceivedatainanunexpectedformat(acommonlyoccurringprogrammingerrorwhenusingothercommunicationmiddlewareproducts).

11.4 DataArchitectureTheprocessofarchitectingDDSDataTypesisverysimilartothatofdesigningaRelationalDatabaseschema.Becausethedatastructuresusedbyyourapplicationwillbeconveyedbetweenapplications,andpossiblyoveranetwork,itisimportantthattheybedesignedwithefficiencyinmind.This‘datanormalization’processisimportanttoeffectivedeploymentofDDStechnology.

Forlargeorcomplexsystems,datainterfaces,connections,andcommunicatedtypeswillbecomeverycomplex.Inthesecases,datamodelingtoolsmayprovideanecessaryframeworkformanagingthedatatypesacrossasystem.ManydatamodelingtoolssupportgeneratingDDScompatibleIDLorXMLthatcanbeprocessedbytheCoreDXDDSdatatypecompiler.

11.5 DataTypeDefinitionOncetheappropriatedatastructureshavebeendesigned,theymustbewritteninalanguagethattheCoreDXDDSmiddlewarecanunderstand.CoreDXDDSsupports2languageindependentformats:IDLandXML.

IDLisasimpleandflexiblelanguagefordefiningdatatypes.Ithasarichsetofprimitiveandcomplexdatatypes,andtherearedefinedmappingsfrom

Formatted: Font:Italic

Deleted: CoreDXDDSDiscovery

CoreDXDDSProgrammer’sGuide

104

IDLtomanycommonprogramminglanguages.ThismakesIDLagoodlanguageforDDS.

11.6 DataDefinitionSyntaxADDSDataTypeisalwaysastructure,whichmaycontainanycombinationofbasicandconstructedtypes,includingembeddedstructures.Table11-1isalistofbasictypessupportedintheCoreDXDDSIDLandXML.

Table11-1:BasicUserDefinedTypes

BasicType Description

short 2bytes

long 4bytes

longlong 8bytes

unsignedshort 2bytes

unsignedlong 4bytes

unsignedlonglong 8bytes

float 4bytes

double 8bytes

char 1byte

wchar 4bytes

boolean 1byte

octet binarydata,1byte

string boundedandunbounded

constant constanttype,alwaysanumber

typedef Aliasoralternatename

105

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Table11-2isalistofconstructedtypessupportedintheCoreDXDDSDDL.

Table11-2:ConstructedUserDefinedTypes

ConstructedType Description

struct Structuretype

union Uniontype

array Singleormultidimensional

sequence boundedandunbounded

enum Variablesizedcollectionofnameswithconstantvalues

bitset Variablesizedlistofnamedbit-sizedflags

map Key-valuepairs

CoreDXDDSIDLdoesnotsupporttheanytype.

11.7 IDLandXMLLanguageMappingsTheCoreDXdatatypecompilergeneratessourcecodeforuseinapplicationprograms.Thesefilescontain,amongotherthings,atranslationoftheIDLorXMLspecifieddatatypeintoalanguagespecificdatatype.ThemappingofIDLorXMLtoprogramminglanguagefollowsthestandardsoftheOMG.

ThefollowingsubsectionsprovideanoverviewoftheavailabledatatypesandhowtheyaremappedtoeachofthesupportedCoreDXDDSprogramminglanguages.AfulldescriptionofavailabledatatypesandconfigurationoptionsasspecifiedintheX-TypesandIDLspecificationsisprovidedintheCoreDXDDSTypeSystemProgrammer’sGuide.

CoreDXDDSProgrammer’sGuide

106

11.7.1 BasicTypesTable11-3:PrimitiveDataTypeMapping

IDLType XMLType

C C++ C# C++

char char8 char char char char

wchar char32 char32 char32 int int

octet byte unsignedchar

unsignedchar

byte byte

short int16 short short short short

unsignedshort

uint16 unsignedshort

unsignedshort

ushort short

long int32 int int int int

unsignedlong

uint32 unsignedint

unsignedint

uint int

longlong int64 int64_t int64_t long long

unsignedlonglong

uint64 unsignedint64_t

unsignedint64_t

ulong long

float float32 float float float float

double float64 double double double double

string string char* char* String String

11.7.2 ComplexTypesComplextypesaredescribedindetailintheCoreDXDDSTypeSystemProgrammer’sGuide.

107

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

11.8 CreatingDataTypes

11.8.1 UsingIDLThesyntaxofIDLisflexibleandissimilartootherlanguagessuchasC.TheIDLfilecancontainanycombinationof:

• C/C++ style comments • C compiler directives

#if, #ifdef, #else, #endif, #include, etc.

• namespace / module • constant definitions • enumerated type definitions • typedefs • structures (these become DDS data types) • unions • annotations

Figure11-1:ExampleIDLfileprovidesanexampleofaIDLfile.

ExampleIDLdatadefnitionfile

//===================================================== // CoreDX DDS IDL example //===================================================== struct SenderType { string firstname; string lastname; }; struct StringMsg { SenderType sender; long time_sent; sequence<string> old_msgs; string msg; };

Formatted: Font:Bold, Italic

Deleted: Figure11-1:ExampleIDLfile

CoreDXDDSProgrammer’sGuide

108

Figure11-1:ExampleIDLfile

ThesyntaxfortheseIDLfileelementsadherestotheOMG’sIDLsyntaxspecificationasdefinedintheIDL4specification.TheIDLtypedefinitionsaretheprimaryfocusofIDLfiles.TheCoreDXDDSIDLcompiler(coredx_ddl)canparsefullycompliantIDLfiles;itwillusetheDDStypedefinitionsandignoreanynon-DDSdefinitionswhengeneratingCoreDXDDScode.

11.8.2 USINGXMLTheXMLsyntaxallowsthesamedatadefinitionsasIDL,followingtheformatoftheTBDschema.TheXMLfilemaycontain:

• XML comments • namespace / module • constant definitions • enumerated type definitions • typedefs • structures (these become DDS data types) • unions • annotations

Figure11-1:ExampleIDLfileprovidesanexampleofaXMLfile.

ExampleXMLdattypedefinitionfile

//===================================================== // CoreDX DDS XML example //=====================================================

<dds:types xmlns:dds="http://www.omg.org/ptc/2011/01/07/XML_Type_Representation" xmlns="http://www.omg.org/ptc/2011/01/07/XML_Type_Representation" > <struct name="SenderType"> <member name="firstname" id="0" type="string"/>

Formatted: Font:Bold, Italic

Deleted: Figure11-1:ExampleIDLfile

109

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

<member name="lastname" id="1" type="string"/> </struct> <struct name="StringMsg"> <member name="sender" id="0" type="nonBasic" nonBasicTypeName="SenderType"/> <member name="time_sent" id="1" type="int32"/> <member name="old_msgs" id="2" type="string" sequenceMaxLength="(-1)"/> <member name="msg" id="3" type="string"/> </struct> </dds:types>

11.9 ConfiguringDataTypesDatatypesmaybeconfiguredusingannotations.Configurationoptionsincludespecifyingkeyfields,markingfieldsasoptionalormandatory,andspecifyingtheextensibilityofthedatatype.

Thisdocumentdescribesthesyntaxfordefiningkeys.TheCoreDXDDSTypeSystemProgrammer’sGuidedescribesdatatypeconfigurationoptionsindetail.

11.9.1 SpecifyingKeysTheapplicationdeveloper,whencreatingaDDSdatatype,canspecifyoneormoreattributesoftheDDSdatatypeasakey.TheCoreDXDDSmiddlewareusesthosekeyattributestoorganizethedataintoinstances(seetheInstancesandSampleschapterforadditionalinformation).

AkeycanbeanyfieldintheDDSDataType,exceptforsequences,unions,andenums.Theapplicationdevelopermaydefineanynumberoffieldstobeakeyfield.AllthefieldslabeledasakeyfieldareconcatenatedtogethertoformonekeyfortheDDSDataType.

Formatted: Font:Italic

Deleted: InstancesandSamples

CoreDXDDSProgrammer’sGuide

110

ThereareafewmethodstospecifyakeyfieldinIDL.

1. Annotation before the field

ThefollowingexampleshowshowtodefinekeysusingtheIDL4annoatitionbeforethekeyfield,usingIDL.

ExampleIDLfile

//===================================================== // CoreDX DDS IDL example – using keys //===================================================== // This #ifdef block allows the following IDL to be // compatible with all other IDL #ifdef DDS_IDL #define DDS_KEY __dds_key #else #define DDS_KEY #endif // the ‘sender_id’ field is defined as a key struct StringMsg1 { struct SenderType { string first_name; string last_name; } sender; DDS_KEY long sender_id; long time_sent; sequence<string> old_msgs; string msg; }; // the ‘sender’ field is defined as a key struct StringMsg1 { DDS_KEY struct SenderType { string first_name; string last_name; } sender; long sender_id; long time_sent; sequence<string> old_msgs; string msg;

111

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

}; // the key is a combination of the sender’s last name // and the sender_id struct StringMsg1 { struct SenderType { string first_name; DDS_KEY string last_name; } sender; DDS_KEY long sender_id; long time_sent; sequence<string> old_msgs; string msg; };

2. Annotation after the field

ThefollowingexampleshowshowtodefinekeysusingtheIDL4annoatitionafterthekeyfield,usingIDL.

ExampleIDLfile

//===================================================== // CoreDX DDS IDL example – using keys //===================================================== // This #ifdef block allows the following CoreDX DDS IDL to be // compatible with all other IDL #ifdef DDS_IDL #define DDS_KEY __dds_key #else #define DDS_KEY #endif // the ‘sender_id’ field is defined as a key struct StringMsg1 { struct SenderType { string first_name; string last_name; } sender; DDS_KEY long sender_id; long time_sent;

CoreDXDDSProgrammer’sGuide

112

sequence<string> old_msgs; string msg; }; // the ‘sender’ field is defined as a key struct StringMsg1 { DDS_KEY struct SenderType { string first_name; string last_name; } sender; long sender_id; long time_sent; sequence<string> old_msgs; string msg; }; // the key is a combination of the sender’s last name // and the sender_id struct StringMsg1 { struct SenderType { string first_name; DDS_KEY string last_name; } sender; DDS_KEY long sender_id; long time_sent; sequence<string> old_msgs; string msg; };

3. Oringial CoreDX DDS syntax

BeforetheformalizationoftheIDL4specification,thedefinitionofDDSkeyswasnotspecifiedinanyoftheDDSstandards.NewCoreDXDDSversionsacceptboththeIDL4keydefinitionsyntax,andtheoriginalCoreDXDDSkeydefinitionsyntax.

ThissectiondescribestheoriginalCoreDXDDSsyntax.Tospecifyafieldtobeakey,addthestring“__dds_key”infrontofthefielddefinition.TheCoreDXDDSdatatypecompilerdefinesacompilerflag:“DDS_IDL”,anditiscommontousethistoprovidecompatibleIDLsyntaxintheIDLfiles.ThefollowingIDLprovidesseveralexamplesofusingkeysintheIDL.

113

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

ExampleIDLfile

//===================================================== // CoreDX DDS IDL example – using keys //===================================================== // This #ifdef block allows the following CoreDX DDS IDL to be // compatible with all other IDL #ifdef DDS_IDL #define DDS_KEY __dds_key #else #define DDS_KEY #endif // the ‘sender_id’ field is defined as a key struct StringMsg1 { struct SenderType { string first_name; string last_name; } sender; DDS_KEY long sender_id; long time_sent; sequence<string> old_msgs; string msg; }; // the ‘sender’ field is defined as a key struct StringMsg1 { DDS_KEY struct SenderType { string first_name; string last_name; } sender; long sender_id; long time_sent; sequence<string> old_msgs; string msg; }; // the key is a combination of the sender’s last name // and the sender_id struct StringMsg1 { struct SenderType { string first_name; DDS_KEY string last_name; } sender;

CoreDXDDSProgrammer’sGuide

114

DDS_KEY long sender_id; long time_sent; sequence<string> old_msgs; string msg; };

Figure11-2:IDLkeysexample

Moreinformationondatatypeconfiguration,keys,andannotationsyntaxisavailableintheCoreDXDDSTypeSystemProgrammer’sGuide.

11.10 UsingtheCoreDXDDSDataTypeCompiler

TheCoreDXDDSdatatypecompiler(coredx_ddlorcoredx_ddl.exe)compilestheDDStypesdefinedinIDLorXMLandgeneratestype-specificsourcecodetobecompiledandlinkedwithaCoreDXDDSapplication.TheCoreDXDDSdatatypecompilerprovidessomecommandlineargumentstotailorthebehavior.

Table11-4:coredx_ddlcommandlineoptions

coredx_ddloption Default Description

-h n/a Help:printcoredx_ddlusageinformation

-aalignmentflag 0 0==don’tcountCDRENCAPHDRinalignment.ThisisthedefaultinCoreDXDDSversions3.5.3andnewer,andisinteroperablewithotherDDSimplementations.

1==countCDR_ENCAP_HDRisalignment.ThisvalueisinteroperablewitholderCoreDXDDSversions(beforev3.5.3).

115

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

coredx_ddloption Default Description

-bname IDLorXMLfilename

Basename:provideanalternatefilenameprefixtouseforthegeneratedfiles.ThedefaultisthebasenameoftheIDLorXMLfilename.Forexample,aIDLfilenamed“hello.ddl”will,bydefault,producegeneratedfilesnamedlike“hello.h”,“helloTypeSupport.h”,etc.Theusercanprovidethisargumenttochangethegeneratedfilenameprefixtoastringspecifiedbyname.

-boptiononlyvalidforCandC++languages

-ddirectoryname Currentdirectory OutputDirectory:provideanalternatedirectorytoputtheresultinggeneratedcode.Thedefaultisthecurrentworkingdirectory.

-Dpreprocessorsymbol

n/a Thisoptionisusedtospecifypre-processordefines.PredefinedbyCoreDXDDS:DDS_IDL,COREDX_DDS

-eendian HOSTCPUarchitecture

Endian:oneof“b”or“l”,providethebyteorder(bigendianorlittleendian)tousewhenmarshallingpublisheddatatotransmitoverthewire.ThedefaultistheendianoftheHOSTplatform(theplatformwherethecoredx_ddlcompilerisrunning).ThisshouldbeusedwhentheTARGETplatformhasadifferentendiannessthantheHOSTplatform.

IftheendiannessoftheTARGETplatformisnotsetcorrectly,DDSapplicationsthatperformareadortakeoperationwillhaveundefinedbehaviorandmaysegfault.

-ffilename Nodefault,mustbespecified

File:providetheIDLorXMLfiletoprocess

-F EnabesupportforthefullX-Typestypesystem.Withoutthisflag,typesarefullybackwardscompatible,anderrorsaregeneratedwithtypesandannotationsthatarenotbackwardscompatible.

CoreDXDDSProgrammer’sGuide

116

coredx_ddloption Default Description

-g Constructpreprocessorguardfromfrullinputfilename(defaultisbaseinputfilename)

-Gguard_variable Specifypreprocessorguardvariableusedinc/c++headers(defaultisbaseinputfilename).

-Iinclude_flags Enableordisablegenerationofcertaincodecomponents.Ifaflagisprefixedwith‘^’,thendisablegenerationofthatcomponent.Otherwise,enablegenerationofthatcomponent.Flagsinclude:

g:generate‘get_field()’routineforstruct/uniontypes(defaultisenabled)

O:generateTypeObjectinTypeSupport(defaultisenabled)

p:generate‘print’routineforstructtypes(defaultisdisabled)

s:generateunmarshalcodewithextradatachecks(defaultisdisabled)

T:generateTypeCodeinTypeSupportsource(defaultisenabled).Note‘–i^T’isequivalentto‘-T’

x:generateextraTypetypedefsAPI’s(defaultisenabled)

X:generateextraX-TypesdefinedTypeSupportAPI’s(defaultisdisabled)

-Iincludepath empty Thisoptionprovidesapaththatwillbesearchedtosatisfy‘#include’directivesfoundintheIDLfile(s).

-Ipath Specifytheincludepath,willbepassedtothepreprocessor.

-jjava_version 7 ControlssomeaspectsofJavacodegeneration(5or7).

117

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

coredx_ddloption Default Description

-llanguage c Language:oneof“c”,“cpp”,“csharp”,“java”providethelanguagetouseforthegeneratedsourcecode.

-Llicense_file SpecifythefullpathtotheCoreDXDDSlicensefile.

-ppreprocessor cpp(linux)

cl.exe/E(win)

Preprocessor:providethepreprocessortouse.ThelocationofthespecifiedpreprocessormustbeinthePATH.

-s Thisoptionsuppressesthegenerationofcodefor‘included’IDLfiles.

-S Thisoptionstripsthepathfromgenerated#includestatements.Itisonlyrelevantif‘-s’isineffect.

-T Thisoptionsuppressesthegenerationof‘typecode’datainlineinTypeSupport.

-X SpecifythattheinputisinXMLformat(asopposedtoIDLorDDL).

-Wno-<warning> Disablethewarning<warning>.Forexample:-Wno-1091

TheCoreDXDDSdatatypecompilergeneratesseveralsourcecodefiles.Allgeneratedfilesarewrittentothecurrentworkingdirectory(thedirectoryfromwhichcoredx_ddlwasrun),unlessthe–d<output_directory>optionisused.

ForadditionalCoreDXdatatypecompileroptionsforusewithDynamicTypes,refertoPart4:Chapter18:DynamicTypes.

11.11 GeneratedCode

TheCoreDXDDSdatatypecompilerwillgenerateseveralsourcefiles,listedinTable11-5.Detaileddescriptionsofthegeneratedfilesarelistedbelow.[IfRPCinterfacesaredefinedinthedatatypefile,additionalsourcefilesaregenerated.ThosearedescribedintheCoreDXDDSRPCProgrammer’sGuide.

CoreDXDDSProgrammer’sGuide

118

Table11-5:Generatedsourcecodefilenames

Cfilenames C++filenames C#filenames Javafilenames

name.h

name.c

name.hh

name.cc

name.cs name.java

nameTypeSupport.h

nameTypeSupport.c

nameTypeSupport.hh

nameTypeSupport.cc

nameTypeSupport.cs nameTypeSupport.java

nameDataReader.h

nameDataReader.c

nameDataReader.hh

nameDataReader.cc

nameDataReader.cs nameDataReader.java

nameDataWriter.h

nameDataWriter.c

nameDataWriter.hh

nameDataWriter.cc

nameDataWriter.cs nameDataWriter.java

11.11.1 TypeDefinitionThetypedefinitionfiles(name.h,name.cinC)containthelanguagespecificdatatypedeclarationsfortheDDSdatatypesdefinedintheIDLorXMLfile.Theyalsoincludebasicinitialization,copy,anddeleteoperationsforthedatatypes.

11.11.2 TypedTypeSupportDefinitionThetypesupportfiles(nameTypeSupport.h,nameTypeSupport.cinC)containthelanguageandtypespecificTypeSupportstructures.Forlanguagesthatsupportheredity,theseareclassesthatderivefromthebaseTypeSupportclass.

11.11.3 TypedDataReaderandDataWriterDefinitionsThedatareader(nameDataReader.h,nameDataReader.c)anddatawriterfiles(nameDataWriter.h,nameDataWriter.c)containthelanguageandtypespecificDataReaderandDataWriterstructures.Forlanguagesthatsupportheredity,theseareclassesthatderivefromthebaseDataReaderandDataWriterclasses.

119

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TheapplicationshouldusethetypespecificoperationsforDataReaderandDataWritercalls.

CoreDXDDSProgrammer’sGuide

120

Chapter12 QualityofServiceFeatures

OneofthepowerfulfeaturesofDDSisthesupportforvariousQualityofService(QoS)settings.QoSsettingsallowtheapplicationdevelopertotailorthebehaviorofpublishers,subscribers,andthecommunicationsbetweenthem.

MostDDSEntities,fromaDomainParticipantFactorydowntotheDataReaderandDataWriter,haveasetofQoSsettingsthatapply.TheQoSsettingsarecontainedinastructure.Forexample,aDomainParticipantFactoryhasaDomainParticipantFactoryQosstructurecontainingalltheapplicableQoSsettings.

TheQoSsettingsforanentitycanbeestablishedwhentheentityiscreated,orbyusingtheget_qos()andset_qos()methodsoneachentity,asthefollowingCexampleillustrates.

SampleCApplicationCode

DDS_Subscriber subscriber; DDS_DataReader dr; DDS_DataReaderQos drqos; DDS_DataReaderListener dr_listener; /* … code deleted … */ /* Setup a non-default DataReader QoS structure */ DDS_Subscriber_get_default_datareader_qos(subscriber, &drqos); drqos.history.kind = DDS_KEEP_LAST_HISTORY_QOS; drqos.history.depth = 5; /* EXAMPLE 1: Define the DataReader QoS at creation */ dr = DDS_Subscriber_create_datareader(subscriber, topic_descr, &drqos, &dr_listener, DDS_DATA_AVAILABLE_STATUS); /* EXAMPLE 2: Set the QoS after creating the DataReader */ DDS_DataReader_set_qos(dr, &drqos);

Figure12-1:ConfiguringQoS-SampleCCode

121

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

12.1 QoSCompatibilityManyQoSsettingsareapplicabletomorethanoneentity.Andinorderforeffectivecommunications,insomecasestheQoSsettingmustbecompatiblebetweenpublishingentitiesandsubscribingentities.PublishersandDataWritersofferaQoSconfiguration.SubscribersandDataReadersrequestaQoSconfiguration.IfthePublisherandDataWriterofferaconfigurationsettingthatisatleastwhattheSubscriberandDataReaderrequested,thisisconsideredamatch,eveniftheQoSconfigurationsarenotthesame.

Forexample,theDURABILITYQoSsettingindicatesweatherapublishingapplicationwillsavepreviouslypublisheddataandwhetherasubscribingapplicationexpectstoreceivedatathatwaspublishedbeforeitwascreated.ConsiderasubscribingapplicationrequestingaDURABILITYQoStobeabletoreceivehistory(datapublishedbeforetheDataReaderexisted),andapublishingapplicationofferingaDURABILITYQoSindicatingitwillnotsaveanydataafterithasbeenpublished.Itisimpossibleforthispublishingapplicationtomeettherequestofthissubscribingapplication,andeffectivecommunicationwillnotoccur.However,ifthesubscribingapplicationrequestsaDURABILITYQoStonotreceiveanyhistory,andapublishingapplicationoffersaDURABILITYQoStomakehistoryavailable,theQoSsettingsmatch.Inthiscase,thepublishingapplicationisofferingmorethanthesubscribingapplicationisrequesting.

Whenattemptingtomatchuppublishingapplicationswithsubscribingapplications,theCoreDXDDSmiddlewarewillconsidertheQoSsettingsonbothsides(aswellasontheTopic).IfallQoSsettingsarecompatible,thepublishingapplicationandsubscribingapplicationwillbe“matched”.IfanyQoSsettingsareincompatibleboththepublishingandsubscribingapplicationsarenotified.TheOfferedIncompatibleQosstatusisupdatedonthepublishingapplicationandtheRequestedIncompatibleQosstatusisupdatedonthesubscribingapplication.Forinformationonhowtoretrievecommunicationstatuses,seetheCommunicationStatuschapter.

Table12-1liststhecompatibilityofeachQoSsetting(whetherornottheQoSsettingmustbecompatiblebetweenpublishingentities,subscribingentities,andtopics).

Formatted: Font:Italic

Deleted: CommunicationStatus

CoreDXDDSProgrammer’sGuide

122

12.2 QoSMutabilityManyQoSsettingscanbechangedonlybeforetheDDSEntityisenabled.However,therearesomeQoSsettingsthatcanbechangeddynamicallyatanytime.TheseQoSsettingsareconsideredmutableorchangeable.Table12-1liststhemutabilityofeachQoSsetting(whetherornottheQoSsettingcanbedynamicallychangedatanytime).AttemptingtochangeaQoSsettingthatisnotmutableusingaset_qos()operationwillreturnDDS::RETCODE_IMMUTABLE_POLICY.

12.3 QualityofServiceDetailsTable12-1listsallthestandardDDSQoSpolicies,alongwithcompatibilityandmutabilitycharacteristics.FollowingthetableisadetailedlistofallsupportedQoSfeaturesfromtheOMGDDSspecificationsanddescriptionoftheiruse.CoreDXDDSsupportsadditionalpoliciesbeyondthosedefinedintheOMGDDSspecifications.TheseadditionalQoSpoliciesaredescribedinPart4:CoreDXDDSExtensions.

Table12-1:QoSSummary

QoSSetting Mustbecompatible DynamicallyChangeable

DEADLINE YES YES

DESTINATION_ORDER YES no

DURABILITY YES no

DURABILITY_SERVICE no no

ENTITY_FACTORY no YES

GROUP_DATA no YES

HISTORY no no

LATENCY_BUDGET YES YES

LIFESPAN (n/a) YES

123

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

QoSSetting Mustbecompatible DynamicallyChangeable

LIVELINESS YES no

OWNERSHIP YES no

OWNERSHIP_STRENGTH (n/a) YES

PARTITION no YES

PRESENTATION YES no

PROPERTY no Dependsonuse

READER_DATA_LIFECYCLE (n/a) YES

RELIABILITY YES no

RESOURCE_LIMITS no no

TIME_BASED_FILTER (n/a) YES

TOPIC_DATA no YES

TRANSPORT_PRIORITY (n/a) YES

USER_DATA no YES

WRITER_DATA_LIFECYCLE (n/a) YES

12.3.1 DEADLINETheDeadlineQoSpolicyisusedwhenaTopicisexpectedtohaveeachinstanceupdatedperiodically.TheDataWriteroffersaDeadlinecontractwheretheapplicationguaranteestoupdateeachinstanceeveryntimeperiod.TheDataReaderrequestsaDeadlinecontractwheretheapplicationexpectseachinstancetobeupdatedeveryntimeperiod.

WhenawritingapplicationdoesnotsatisfytheDataWriter’sDeadlineperiod(configuredinitsQoSpolicy),theoffered_deadline_missedstatusisupdated.Thewritingapplicationmaychoosetobenotifiedofthisevent

CoreDXDDSProgrammer’sGuide

124

throughanyoftheofferednotificationmethods(refertoCommunication

Statusformoreinformation).

WhenawritingapplicationdoesnotsatisfyamatchedDataReader’sDeadlineperiod(configuredinit’sQoSpolicy),therequested_deadline_missedstatusisupdated.Thereadingapplicationmaychoosetobenotifiedofthiseventthroughanyoftheavailablenotificationmethods(refertoCommunicationStatusformoreinformation).

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.TheDataWritermusthaveaDeadline<=theDataReader’sDeadlinebeforetheDataWriterandDataReaderwillcommunicate.IftheDeadlinesarenotcompatible,CoreDXDDSwillgenerateanIncompatibleQosstatus(seetheCommunicationStatuschapterforadditionalinformation).

12.3.2 DESTINATION_ORDERTheDestinationOrderpolicydeterminesthelogicalorderatreceptiontimeofdatasamplesforaninstance.ThisisimportantwhentheinfrastructuremustdeterminewhichsamplestokeepattheDataReader,basedonotherQoSpolicieslikeHISTORYandRESOURCE_LIMITS.ThepossiblevaluesforDestinationOrderarebyreceptiontimestampandbysourcetimestamp.Whensettobyreceptiontimestamp,CoreDXDDSwillusethereceptiontimetodeterminetheorderofsamples.Whensettobysourcetimestamp,

CoreDXDDSwillusethetimestampsetbythepublishertodeterminetheorderofsamples,regardlessofwhenthedatasamplewasreceived.

12.3.3 DURABILITYTheDurabilitypolicycontrolswhetherornotCoreDXDDSwillmakealreadypublisheddataavailabletolatejoiningDataReaders.Thepublish-subscribeparadigmofferedbyCoreDXDDSallowsapplicationstowritedataevenwhentherearenocurrentreadersonthenetwork.Further,aDataReaderhastheoptiontoreceivehistoricaldata(datapublishedbeforethisDataReadercameonline)inadditiontocurrentlypublisheddata.TheDurabilitypolicyallowsthisconfiguration.

ThepossiblevaluesforDurabilityareVolatile,TransientLocal,Transient,andPersistent.WhensettoVolatile,CoreDXDDSwillnotsavepreviouslypublisheddataforlatejoiningreaders.WhensettoTransientLocal,CoreDXDDSwillsavepreviouslypublisheddataforthelifespanoftheDataWriterforlatejoiningreaders.WithaTransientLocalsetting,oncetheDataWriter

Formatted: Font:Italic

Deleted: CommunicationStatus

Formatted: Font:Italic

Deleted: CommunicationStatus

Formatted: Font:Italic

Deleted: CommunicationStatus

125

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

isdestroyed,itspublishedhistorydataisnolongeravailable.WhensettoTransient,CoreDXDDSwillsavepreviouslypublisheddataforthelifespanofthepublishingapplicationforlatejoiningreaders.WithaTransientsetting,oncethepublishingapplicationexits,itspublishedhistorydataisnolongeravailable.WhensettoPersistent,CoreDXDDSwillsavepreviouslypublisheddatainpermanentstorage,whereitcanoutlivethepublishingapplicationandasystemreset.Thishistorydataisavailabletolatejoiningreaders.

The‘wait_for_historical_data’maybeusedonDataReaderswithaDurabilitysettingofTransientLocalorstrongertoblocktheapplicationuntilallhistoricaldatahasbeenreceivedbytheDataReader.Refertosection8.5.2WaitforHistoricalDataforadditionalinformation.

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.TheDataWritermusthaveaDurability<=theDataReader’sDurabilitybeforetheDataWriterandDataReaderwillcommunicate,wheretheDurabilityvaluesareorderedsothatVolatile<TransientLocal<Transient<Persistent.IftheDurabilitiesarenotcompatible,CoreDXDDSwillgenerateanIncompatibleQosstatus(seetheCommunicationStatuschapterforadditionalinformation).

ThenumberofdatasamplesandinstancesstoredforanyDurabilitysettingisdeterminedinpartbytheconfigurationoftheHistoryandResourcesLimitsQoSpolicies.

CoreDXDDScurrentlysupportsonlythevolatileandtransientlocalvaluesforDurability.

12.3.4 DURABILITY_SERVICETheDurabilityServiceQoSpolicyisapplicableonlywhentheDurabilityQoSpolicyissettoTransientorPersistent.Thispolicyconfiguresthedurationandamountofdatastored.

CoreDXDDScurrentlydoesnotsupporttheDurabilityServiceQoSpolicy.

12.3.5 ENTITY_FACTORYTheEntityFactoryQoSpolicycontrolsthebehaviorofcreate_xxx()anddelete_xxx()operationsonafactoryentity.Factoryentitiesinclude:DomainParticipantFactory,DomainPartition,Publisher,andSubscriber.

Formatted: Font:Italic

Deleted: WaitforHistoricalData

Formatted: Font:Italic

Deleted: CommunicationStatus

CoreDXDDSProgrammer’sGuide

126

TheEntityFactoryQoSpolicycontainsoneconfigurationitem:autoenable_created_entities.WhensettoTRUE,allEntitiesreturnedbycreate_xxx()operationsarealreadyenabled.WhensettoFALSE,theapplicationmustexplicitlycallenable()onallcreatedEntities.

Theautoenabled_created_entities=FALSEsettingiscommonlyusedwhenconfiguringoneormoreTransporrtsforaDomainParticipant.SincethetransportmustbeconfiguredandinstalledbeforetheDomainParticipantisenbled,itisnecessarytodisabletheautomaticenableoftheDomainParticipant.

ThedefaultsettingfortheEntityFactoryQoSpolicyisTRUE.

12.3.6 GROUP_DATATheGroupDataQoSpolicyallowstheapplicationtoattachadditionalinformationtocreatedEntityobjects.ThisdataisnotusedbyCoreDXDDS,andismadeavailabletotheapplicationbytheBuilt-inTopics,alongwithotherdiscoveryinformation.Formoreinformation,seethe9.2Built-InTopicssection.

12.3.7 HISTORYTheHistoryQoSpolicy(alongwiththeResourceLimitsQoSpolicy)controlsthesizeandbehavioroftheDataReaderandDataWriterdatacaches.ThedatacachesmaybeusedtobufferwrittendataontheDataWriter,andreceiveddataontheDataReader.TheHistoryQoSpolicydetermineshowCoreDXDDSwillsavedatasamples,andthenumberofsamplesthatmaybesaved,foreachInstance.TheHistoryQoSpolicycanprovidesomeamountofbufferingonboththepublishingandsubscribingsides.WhencombinedwiththeDurabilityQoSpolicyonaDataWriter,thisQoSpolicywilldeterminetheamountofdatahistorysavedforlatejoiningreaders.OnaDataReader,thispolicywilldeterminethenumberofsamplesavailabletoreturnonaread()ortake()operation.

ThepossiblevaluesfortheHistorykindareKEEPALLandKEEPLAST.WhentheHistorykindisconfiguredtoKEEP_LAST,CoreDXDDSmaydeletestoreddatasamplestomakeroomfornewlywritten(orreceived)samples.WhentheHistorykindisconfiguredtoKEEP_LAST,CoreDXDDSwillnever‘bump’astoreddatasampletomakeroomforanewlywritten(orreceived)sample.WhensettoKEEPLAST,theapplicationcandefineadepth(numberofsamplestokeep).[DepthisnotusedbyCoreDXDDSwhentheHistory.kindissettoKEEP_ALL.]

Formatted: Font:Italic

Deleted: Built-InTopics

127

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

AHistorykindofKEEP_ALLmaybeusedincombinationwiththeResourceLimitsQoSpolicyinordertoboundthenumberofsamplesand/orinstancesstoredbyCoreDXDDS.

HereisanexampleofhowtheHistorykindscanbehave.LetusconsiderascenariowhereaReliableDataWriteriswritingsamplesfasterthanatleastoneifit’smatchedReliableDataReaderscanreadorprocessthem.Inthiscase,CoreDXDDSwillattempttobuffertheunreadsamples.SampleswillbebufferedfirstattheDataReader.WithaHistorykindofKEEP_LAST,samplesarebuffereduptotheHistorydepth,andthentheymaybeoverwritten.WithaHistorykindofKEEP_ALL,samplesarebuffereduptotheconfiguredResourceLimits.IfResourceLimitsareconfiguredtobeinfinite,sampleswillbebufferedinfinitely.IfResourceLimitsareconfiguredtobefinitevalue(s)andtheDataReaderhasbufferedthatconfigurednumberofsamples,theDataReaderwilldrop(andnotacknowledge)anymorereceivedsamples.Atthispoint,sampleswillbebufferedattheDataWriter.

NotethatusingaHistorysettoKEEP_ALLincombinationwithaDurabilitysettoTRANSIENT_LOCAL(orhigher)canbeadangerouscombination.TheCoreDXDDSinfrastructuremaykeepeverysampleeverwrittenbytheDataWriter,untilthepublishingapplicationspecificallydisposesorunregisterstheInstance,oruntilLifespanlimitsareexpired(seetheInstancesandSampleschapter).Thiscanquicklyutilizeallavailableresourcesforthepublishingapplication,orthehostmachineifResourceLimitsarenotspecified.

12.3.8 LATENCY_BUDGETTheLatencyBudgetQoSpolicyspecifiesadelayisacceptableinthetimebetweenwhenapublishingapplicationwritesdataandwhenasubscribingapplicationisnotifiedthedataisavailable.CoreDXDDSusesthispolicyasahint–notacontractthatmustbemonitoredorenforced.Bydefault,theLatencyBudgetissettozero(0),indicatingthedelayshouldbeminimized.

ItmaynotbeobviouswhyanapplicationwouldwanttoconfigureaLatencyBudgetgreaterthanzero.HerearetwoexamplesofwhenitmaybeappropriatetoconfigureaLatencyBudget.First,considerapublishingapplicationthatispublishingaveryhighrateofdatasamples.IftheLatencyBudgetissettozero,CoreDXDDSwillattempttowriteeverydatasampleontothenetworkassoonasitisavailablefromtheapplication,whichmaynotbeveryefficient.Inthiscase,settingaLatencyBudgetgreaterthanzeroallowsCoreDXDDStoqueuemultipledatasamplesto

Formatted: Font:Italic

Deleted: InstancesandSamples

CoreDXDDSProgrammer’sGuide

128

writeinabatch,whichwillreducetheamountoveroverheadrequired,andmayimproveperformance.Foranotherexample,considerasubscribingapplicationthatisreceivingaveryhighrateofdatasamples.IftheLatencyBudgetissettozero,CoreDXDDSwillnotifytheapplicationforeverydatasamplethatarrivesattheDataReader.However,iftheLatencyBudgetissettoavaluegreaterthanzero,CoreDXDDScanqueuereceiveddatasamples,andsend1notificationformultipleavailablesamples.Inthiscase,thesubscribingapplicationisissuingfewercallstoread()ortake()butreceivingallthesamedatasamples.

12.3.9 LIFESPANTheLifespanQoSpolicyallowsCoreDXDDStoexpireolddatasamples.TheapplicationconfiguresanexpirationdurationtimeonaDataWriter.

ADataReaderreceivingdatafromthisDataWriterwillperiodicallycheckallthesamplesthathavebeenreceived,andifanysampleshaveexpired,theywillberemovedfromtheDataReadercache.

ADataWriterwillalsoperiodicallycheckallthesamplesinitsDataWriterCacheandmayremoveanysamplesthathaveexpired(actualremovalmaybedelayedduetoReliabilityQoSpolicysettings).

Bydefault,theexpirationdurationis0(meaninganinfiniteduration,ornoexpiration).

12.3.10 LIVELINESSTheLivelinessQoSpolicycontrolsthemechanismusedtoensureDataWritersonthenetworkremain“alive”totheirmatchedDataReaders.ThepossiblevaluesfortheLivelinessQoSpolicyareAutomatic,Manualby

Participant,andManualbyTopic.

TheAutomaticsettingconfiguresCoreDXDDSensureallDataWriterswithinaDomainParticipantstayalive,withoutrequiringanyspecificactionfromthepublishingapplication.

Themanualsettings:ManualbyParticipantandManualbyTopicrequirethepublishingapplicationtoperiodicallyassertthelivelinesstoindicatethecorrespondingEntityisstillalive.Thiscanbeexplicitbycallingtheassert_liveliness()operationorimplicitbywritingdata.TheManualby

ParticipantconfigurationallowsanyoneDataWritertoassertlivelinessfor

129

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

allDataWriterswithinthatDomainParticipant.TheManualbyTopic

configurationrequireseachDataWritertoassertitsownliveliness.

TheLivelinessQoSpolicyincludesaleaseduration.ForaDataWriter,theleasedurationisanofferedcontractthatthewriterwillassertlivelinessatleastonceeveryspecifiedduration.ForaDataReader,theleasedurationisarequestthatthewriterassertlivelinessatleastonceeveryspecifieddurationinterval.

WhenawritingapplicationdoesnotsatisfytheDataWriter’sLivelinessleaseduration,theliveliness_loststatusisupdated.Thewritingapplicationmaychoosetobenotifiedofthiseventthroughanyoftheofferednotificationmethods(refertoCommunicationStatusformoreinformation).

WhenawritingapplicationdoesnotsatisfyamatchedDataReader’slivelinessperiod,theliveliness_changedstatusisupdated.Thereadingapplicationmaychoosetobenotifiedofthiseventthroughanyoftheavailablenotificationmethods(refertoCommunicationStatusformoreinformation).

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.WhenconfiguredtooneoftheManualkinds,theDataWritermusthaveaLivelinessleaseduration>=theDataReader’sLivelinessleasedurationbeforetheDataWriterandDataReaderwillcommunicate.IftheLivelinessisnotcompatible,CoreDXDDSwillgenerateanIncompatibleQosstatus(seetheCommunicationStatuschapterforadditionalinformation).

12.3.11 OWNERSHIPTheOwnershipQoSpolicycontrolswhetherCoreDXDDSwillallowmultipleDataWriterstoupdatethesameinstance.ThepossiblevaluesforOwnershipareSharedandExclusive.WhensettoShared,CoreDXDDSdoesnotenforceuniqueownershipforeachinstance,andmultipleDataWriterscanupdatethesameinstance(DataReaderswillreceivethedatawrittenbyallmachedDataWriters).WhensettoExclusive,eachinstancecanbemodifiedonlybyoneDataWriter.Inthiscase,oneDataWriter“owns”eachinstance,andwhilethatDataWriteris“alive”,matchedDataReaderswillonlyacceptsamplesonaninstancewrittenbytheinstanceowner.

ADataReadermayautomaticallychangetheownerofaninstancetoadifferentDataWriter.Thiswillhappenifthecurrentownermissesadeadlineorisotherwiseconsideredtobenotactivelywritingonthe

Formatted: Font:Italic

Deleted: CommunicationStatus

Formatted: Font:Italic

Deleted: CommunicationStatus

Formatted: Font:Italic

Deleted: CommunicationStatus

CoreDXDDSProgrammer’sGuide

130

instance.TheDataReaderwillthenassignownershiptotheactiveDataWriterwiththenexthigheststrength.

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.TheDataReaderandDataWriterOwnershipsmustmatchbeforetheDataWriterandDataReaderwillcommunicate.IftheOwnershipisnotcompatible,CoreDXDDSwillgenerateanIncompatibleQosstatus(seetheCommunicationStatuschapterforadditionalinformation).

12.3.12 OWNERSHIP_STRENGTHTheOwnershipStrengthQoSpolicyisapplicableonlywhentheOwnershipQoSpolicyissettoExclusive.EachDataWritercansetitsStrengthwiththisQoSsetting.ThisstrengthisusedtodeterminewhichDataWriter’supdateswillbereceivedusedthesubscribingapplicationwhenmorethanoneDataWriteriswritingonthatinstance.

12.3.13 PARTITIONThePartitionQoSpolicyallowstheapplicationtodefinelogicalpartitionsinaDDSdomain.InorderforaDataReadertoseedatapublishedbyaDataWriter,theirPartitionsmustmatch.APartitionisastringthatmaycontaina‘*’wildcard.Entitiesmaydefine(andbepartof)multiplepartitions.Theemptystring(“”)isavalidpartition,andwillmatchonlyanotheremptystringor‘*’wildcardpartition.

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.IfthePartitionsdonotmatch,CoreDXDDSwillgenerateanIncompatibleQosstatus(seetheCommunicationStatuschapterforadditionalinformation).

12.3.14 PRESENTATIONThePresentationQoSpolicycontrolstheextenttowhichpublisheddatachangesaredependentoneachother.ThepossiblevaluesforPresentationarecoherentaccessandorderedaccess.Inaddition,thereisanadditionalconfigurationitem:AccessScope.

WhenPresentationisconfiguredascoherentaccess,CoreDXDDSwillpreservegroupingsofchangesmadebythepublishingapplicationbetweencallstothebegin_coherent_change()andend_coherent_change()operations.WhenAccessScopeissettoINSTANCE,thescopeforgroupingchangesiswithineachindividualinstance.Inthiscase,callsto

Formatted: Font:Italic

Deleted: CommunicationStatus

Formatted: Font:Italic

Deleted: CommunicationStatus

131

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

begin_coherent_change()andend_coherent_change()havenoeffect.WhenAccessScopeissettoTOPIC,thencoherentchangesmadebyaDataWriterwillbepreservedandmadeavailableasasettoeachDataReader.WhenAccessScopeissettoGROUP,coherentchangesmadebyallDataWritersattachedtoaPublisherwillbepreservedandmadeavailabletoeachSubscriber.

WhenPresentationisconfiguredasorderedaccess,CoreDXDDSwillpreservetheorderofchangesmadebythepublishingapplication,inaccordancewiththesettingofAccessScope.WhenAccessScopeissettoINSTANCE,changestoaninstanceareunorderedrelativetootherinstances.WhenAccessScopeissettoTOPIC,changesmadebyasingleDataWriteraremadeavailabletoDataReadersinthesameorderinwhichtheyoccurred.WhenAccessScopeissettoGROUP,changesmadebyallDataWritersattachedtoaPublisheraremadeavailabletoSubscribersinthesameorderinwhichtheyoccurred.

NotethatwhilechangesarepreservedbyCoreDXDDSandmadeavailabletotheDataReadersorSubscribersinorder,theapplicationmustmaketheappropriatecallstotheDataReaderorSubscriberinordertoseethedatainthedesiredorder.

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.

12.3.15 PROPERTYThePropertyQoSpolicyispartoftheParticipantQoSPolicystructureandallowstheapplicationtoflexiblydefinename/valuepairs.Currently,CoreDXDDSusesthePropertyQoSpolicyonlyforconfigurationoftheCoreDXDDSSecurityPlug-ins.

ThePropertyQoSpolicycontainsasequenceofproperities,eachonecontaininganame,value,andpropogate_flag.Thepropogate_flagdeterminesiftheinformationissharedduringparticipantdiscovery.

12.3.16 READER_DATA_LIFECYCLETheReaderDataLifecycleQoSpolicycontrolsthebehavioroftheDataReaderwithregardtothedataithasreceivedandismaintaining.ADataReaderinternallymaintainsdatasamplesithasreceiveduntiltheyhavebeen‘taken’bytheapplicationaccordingtoHistoryandResourceLimitsQoSpolicysettings.ADataReaderwillmaintaininformationforaninstance,

CoreDXDDSProgrammer’sGuide

132

evenwhentheassociatedDataWriterisnolongeralive,untiltheapplicationhas“taken”allsamplesforthatinstance.

TheReaderDataLifecycleQoSpolicyofferssomememoryusageprotectiontotheapplication,byallowingCoreDXDDStoreleaseresourcesforinstances,eveniftheapplicationneglectsto“take”allsamplesfortheseinstances.ThisQoSpolicyofferstwoconfigurationitems.TheautopurgenowritersamplesdelayconfigurationitemdefinestheamountoftimetheDataReaderwillmaintaininformationforaninstanceonceitbecomesNOT_ALIVE_NO_WRITERS(therearenolivewriterswritingthisinstance).TheautopurgedisposedsamplesdelayconfigurationitemdefinestheamountoftimetheDataReaderwillmaintaininformationforaninstanceonceitbecomesNOT_ALIVE_DISPOSED(awriterhasdisposedthisinstance).CoreDXDDSmayreclaimaninstanceonaDataReaderwhentheinstancestateisNOT_ALIVE_NO_WRITERSandtherearenosamplesassociatedwiththeinstance.

12.3.17 RELIABILITYTheReliabilityQoSpolicyconfiguresthelevelofreliabilityCoreDXDDSwillguaranteeforcommunicationsbetweenaDataReaderandDataWriter.ThepossiblevaluesforReliabilityareBestEffortandReliable.

WithaBestEffortconfiguration,CoreDXDDSwilloperateina“fireandforget”mode,makinganefforttodeliverallpublisheddata,withnoguaranteealldatawillbereceivedbyallDataReaders.Itisimportanttonotethatonreliablephysicalnetworks,withenoughbandwidthtosupportpublisheddata,itisraretohavedroppedormissedsamples.DDSapplicationspublishingperiodicdatawithhighdataratescanseebetterperformancewithminimaltonodatalossusingaBestEffortconfiguration.

WithaReliableconfiguration,CoreDXDDSwilluseanadditionalreliabilityprotocoltocheckifwrittensamplesarereceived,andpossiblyresendthemifnecessary.TheReliableconfigurationmaybeusedincombinationwiththeHistoryandResourceLimitsQoSpoliciestoguaranteeallpublisheddatawillbereceivedbyallmatchedDataReaders.Thisconfigurationrequiresmoreresourcesandoverheadtofulfill.TheHistoryandResourceLimitsQoSpolicieswilldeterminetheamountofresourcesCoreDXDDSwillmaintaininordertomeetReliablerequirements.Ifconfiguredresourcelimitsaremet,thepublishingapplicationmayblockonawrite()operation.

ThisisaQoSpolicythatmustbecompatiblebeforeDataReadersandDataWriterswillmatch.AReliableDataWriterwillmatchanyDataReader,

133

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

BestEffortorReliable.ABestEffortDataWriterwillmatchonlyBestEffortDataReaders.

12.3.18 RESOURCE_LIMITSTheResourceLimitsQoSpolicyconfigurestheresourcesCoreDXDDScanuseinordertomeettherequirementsimposedbytheapplicationandotherQoSsettings(includingHistory,Durability,andReliability).TheResourcesLimitsthatcanbeconfiguredinclude:thetotalnumberofsamples(max_samples),thetotalnumberofinstances(max_instances),andthenumberofsamplesineachinstance(max_samples_per_instance).

CoreDXDDSDataReadersandDataWriterswillnotstoremoresamplesorinstancethanisspecifiedbytheirResourceLimitsQoSpolicies.ThisprovidesaconvenientmechanismtoconstraintheamountofmemoryaCoreDXDDSapplicationwilluseforapplicationdata.ItalsoallowsCoreDXDDStopre-allocatememoryresources,whichcanresultinbetterperformance.

TheResourceLimitsQoSpolicyprovidesahardlimitforthenumberofsamplesorinstancesthatcanbestoredbyaDataReaderorDataWriter.TheconfigurationofotherQoSPolicies:Reliability,Durability,andHistorydeterminethebehaviorofDataReadersandDataWriterswhentheirResourceLimitsaremet.

Foradditionalinformation,refertothe10.5DataCachesection,aswellasthesectionsforthesespecificQoSpolicies:12.3.17RELIABILITY,12.3.3DURABILITY,and12.3.7HISTORY.

ItispossibleforaDataWritertopublishdatasamples(andinstances)fasterthanaDataReaderisconsumingthem,causingtheDataReadertofillupitsDataCachetoitsconfiguredResourceLimits.Thiscouldbewithrespecttosamples(max_samplesormax_samples_per_instance)orinstances(max_instances).WiththerightcombinationofQoSpolicies(specifically,ReliableReliabilityandKeepAllHistory),publishedsampleswillbestoredbytheDataWriteruntilallDataReaderscanacceptthem.TheDataWriter’sCacheofdatasampleswillcontinuetogrowuntilitmeetstheconfiguredResourcesLimits.Whenthisoccurs,CoreDXDDSwillreturnanerroronthenextcalltowrite()(ordispose()orregister_instance()).Theapplicationmayblockfirst,dependingontheconfigurationoftheReliabilityblockingtime.Thisisaconfigurationwhereone‘slow’DataReadercaneffectivelypreventtheDataWriterfrompublishinganynewdata,affectingallotherDataReadersmatchedtothatDataWriter.

Formatted: Font:Italic

Deleted: RELIABILITY

Formatted: Font:Italic

Deleted: DURABILITY

Formatted: Font:Italic

Deleted: HISTORY

CoreDXDDSProgrammer’sGuide

134

TheCoreDXDDSconstantDDS::LENGTH_UNLIMITEDisusedtoindicatetheabsenceofaparticularlimit.

Themax_samplesandmax_samples_per_instancesettingsmustbeconsistentsuchthatmax_samples>=max_samples_per_instance.Inaddition,themax_samples_per_instancesettingmustbeconsistentwiththeHistorydepth,suchthatdepth<=max_samples_per_instance.Ifthereisanerrorinthesesettings,acreate_datareader()operationwillfail.Aset_qos()operationwillreturntheerrorDDS::RETCODE_INCONSISTENT_POLICY.

12.3.19 TIME_BASED_FILTERTheTimeBasedFilterQoSpolicyallowstheapplicationtoindicateaparticularDataReaderdoesnotnecessarilywanttoseealldatasamplespublishedforaTopic.Infact,theDataReaderwouldtosee,foreachinstance,atmostonedatasampleeveryntimeperiod.Thistimeperiodistheminimum_separationfortheTimeBasedFilter.

UsingtheTimeBasedFilterQoSpolicycanreducetheamountofdatawrittenbyaDataWriter.ThisisparticularlyusefulinsituationswhereaDataReadercannotkeepupwiththeamountofdatapublished,orwheresomeDataReaderssimplydonotneedalltheintermediatedatasamplespublishedonaTopic.

TheTimeBasedFilterminimum_separationmustbeconsistentwiththeDeadlineperiod.Settingaperiod<minimum_separationisanerror.Acreate_datareader()operationwillfail.Aset_qos()operationwillreturntheerrorDDS::RETCODE_INCONSISTENT_POLICY.

12.3.20 TOPIC_DATATheTopicDataQoSpolicyallowstheapplicationtoattachadditionalinformationtocreatedEntityobjects.ThisdataisnotusedbyCoreDXDDS,andismadeavailabletotheapplicationbytheBuilt-inTopics,alongwithotherdiscoveryinformation.Formoreinformation,seethe9.2Built-InTopicssection.

12.3.21 TRANSPORT_PRIORITYCoreDXDDSdoesnotcurrentlysupportthisQoSpolicy.

Formatted: Font:Italic

Deleted: Built-InTopics

135

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

12.3.22 USER_DATATheUserDataQoSpolicyallowstheapplicationtoattachadditionalinformationtocreatedEntityobjects.ThisdataisnotusedbyCoreDXDDS,andismadeavailabletotheapplicationbytheBuilt-inTopics,alongwithotherdiscoveryinformation.Formoreinformation,seethe9.2Built-InTopicssection.

12.3.23 WRITER_DATA_LIFECYCLETheWriterDataLifecycleQoSpolicycontrolsthebehavioroftheDataWriterwithregardtothedataithaspublishedandismaintaining.ThisQoSpolicyallowstheapplicationtoconfigureCoreDXDDStoautomaticallydisposeinstanceswhentheyareunregistered(seethe10.4InstanceLifecyclesforadditionalinformation).

TheWriterDataLifecycleQoSpolicycontainsoneconfigurationitems:auto-disposeunregisteredinstances(autodispose_unregistered_instances).SettingthisconfigurationitemtoTRUEcausestheDataWritertodisposetheinstanceeachtimeitisunregistered.SettingthisconfigurationitemtoFALSEwillnotautomaticallydisposeinstanceswhentheyareunregistered.

WhenaDataWriterisdeleted,allinstancesmanagedbytheDataWriterareautomaticallyunregistered.Therefore,onlysettingtheauto-disposeunregisteredinstancesconfigurationitemwillensuretheinstancesmanagedbyaDataWriteraredisposed.

Formatted: Font:Italic

Deleted: Built-InTopics

Formatted: Font:Italic

Deleted: InstanceLifecycles

CoreDXDDSProgrammer’sGuide

136

Chapter13 CommunicationStatus

TheDDSinfrastructurekeepstrackofanumberofstatusesandstatisticsrelatedtodatacommunications.Theapplicationmaychoosetobemadeawareofsome,all,ornoneofthesestatusesandstatistics.

EachDDSentityhasitsrelevantstatuses,aslistedinTable13-1.

Table13-1:CommunicationStatuses

Entity StatusName Description

Topic INCONSISTENT_TOPIC Another,different,TopicexistswiththesamenameasthisTopic,butadifferentdatatype(iftypeinformationissharedfordiscovery),ordifferentdatatypename.

Subscriber DATA_ON_READERS NewdatahasbeenreceivedononeormoreDataReadersassociatedwiththisSubscriber,andisavailablefortheapplicationtoread()ortake().

DataReader SAMPLE_REJECTED AreceivedsamplehasbeenrejectedbecauseofRESOURCE_LIMITSQoSsettinghasbeenreachedorexceeded.Thesamplehasbeen‘seen’bytheDDSmiddlewareatthesubscribingapplication,butcouldnotbestored.TheDataWriterwillnotre-transmitthissample.Thesampleisnotavailabletothesubscribingapplication.

LIVELINESS_CHANGED OneormoreDataWritersthatwerewritingdatathisDataReaderwasreadinghaschangeditsliveliness(becomingactiveorinactive).

137

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Entity StatusName Description

REQUESTED_DEADLINE_MISSED Adataupdateforaninstancewasnotreceivedintheexpectedtimeinterval(configuredintheDeadlineQoSPolicy).Becausetheoffereddeadline(DataWriter)mustbe<=therequesteddeadline(DataReader),itispossibleforaDataWriter’sOFFERED_DEADLINE_MISSEDstatusmaybetriggered,whentheDataReader’sOFFERED_DEADLINE_MISSEDstatusisNOTtriggered.

REQUESTED_INCOMPATIBLE_QOS ADataWriterwasdiscoveredwhoseTopicmatchesthisDataReader,butwhoseQoSisincompatiblewiththisDataReader.

DATA_AVAILABLE Newdataisnowavailabletoberead.

SAMPLE_LOST Asamplewaslost(neverreceived).Thismaybebecausethesamplewasdroppedbythenetwork(withBEST_EFFORTreliability)orbecausetheDataWriternolongerhasthissampletore-transmit(withRELIABLEreliability).

SUBSCRIPTION_MATCHED ADataWriterhasbeendiscoveredthatmatchestheTopicofthisDataReaderandhasacompatibleQoS(oraDataWriterthatwaspreviouslymatchedisnolongermatched).

DataWriter LIVELINESS_LOST ThelivelinessspecifiedintheLIVELINESSQoSwasnotrespected,andDataReaderswillconsiderthisDataWriternolongeractive.

CoreDXDDSProgrammer’sGuide

138

Entity StatusName Description

OFFERED_DEADLINE_MISSED Adataupdatewasnotreceivedintheexpectedtimeinterval(configuredintheDeadlineQoSPolicy).Becausetheoffereddeadline(DataWriter)mustbe<=therequesteddeadline(DataReader),itispossibleforaDataWriter’sOFFERED_DEADLINE_MISSEDstatusmaybetriggered,whentheDataReader’sOFFERED_DEADLINE_MISSEDstatusisNOTtriggered.

OFFERED_INCOMPATIBLE_QOS ADataReaderwasdiscoveredforthesameTopicasthisDataWriter,buttheQoSrequestedbythatDataReaderwasincompatiblewiththisDataWriter’sQoS.

PUBLICATION_MATCHED ADataReaderhasbeenfoundthatmatchestheTopicandQosofthisDataWriter(oraDataReaderthatwaspreviouslymatchedisnolongermatched).

Somecommunicationstatusesareassociatedwithdatabeingavailableforthesubscribingapplication.Thesearereferredtoasreadcommunicationstatuses,andinclude:DATA_ON_READERSandDATA_AVAILABLE.Sincethesetwostatusesindicatethereceptionofdata(therealpurposeforaDataDistributionService)theytreatedalittledifferentlyfromtheothercommunicationstatuses,referredtoasplaincommunicationstatuses.

13.1 CommunicationStatusDetailsEachcommunicationstatusisdescribedindetailbelow.

139

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

13.1.1 InconsistentTopicStatusTheInconsistentTopicStatusisusedtoinformtheapplicationthatanotherTopichasbeenregisteredintheDomain(andPartition,ifdefined)thathasthesamenameasthisTopic,butadifferentdatatype(ifdatatypesareusedformatching)oradifferentdatatypename.TheCoreDXDDSmiddlewarewillallowanapplicationtocreatemultipleTopicsofthesamenameanddifferenttypes.TheInconsistentTopicStatusallowsapplicationstobemadeawareoftheseinconsistencies.

Type: Plain Communication Status Associated Entity: Topic Mask Name: INCONSISTENT_TOPIC_STATUS Struct Type Name: InconsistentTopicStatus

Figure13-1:InconsistentTopicStatusStructure

13.1.2 DataOnReadersStatusTheDataOnReadersStatusisoneofthereadcommunicationstatuses,andisusedtoinformtheapplicationthatoneormoreoftheDataReadersattachedtoaSubscriberhasnewdatasamplesorsampleinformation.

TheDataAvailableStatusandDataOnReadersStatusarecommunicatedtotheapplicationtogether.Inotherwords,ifthereisDataAvailableforaDataReader,thenthereisaDataReaderwithnewdata.

Type: Read Communication Status Associated Entity: Subscriber Mask Name: DATA_ON_READERS_STATUS Struct Type Name: N/A

CoreDXDDSProgrammer’sGuide

140

13.1.3 SampleRejectedStatusTheSampleRejectedStatusisusedtoinformtheapplicationthatadatasamplewasnotacceptedbytheDataReaderbecauseofresourceslimitsandhistoryconfiguredintheassociatedQoS(ontheeffectedDataReader).TheHISTORYQoSallowstheapplicationtoconfigurethebehaviorofDDSwhentheDataReadercacheisfull.WithaconfigurationofKEEP_ALL,themiddlewaremaynotremoveexistingsamplestomakeroomforthenewsample,andthishasthepotentialtotriggeraSampleRejectedStatus.TheRESOURCE_LIMITSQoSallowstheapplicationtosetalimitonthetotalnumberofsamples,thetotalnumberofinstances,andthenumberofsamplespereachinstancekeptbytheCoreDXDDSmiddleware.IfaDataReaderreceivesasamplethatwouldputanyofthesenumbersovertheirsetlimit,andHistoryisconfiguredtoKEEP_ALL,thesampleisrejected(notaddedtothereadercache),andtheappropriatecountontheSampleRejectStatusisupdated.

Becausethesamplewas‘seen’bytheDataReader,thesendingDataWriterwillnotretransmitit(evenwhenReliability=RELIABLE).Theapplicationwillnotbeabletoaccessthissample.

Type: Plain Communication Status Associated Entity: DataReader Mask Name: SAMPLE_REJECTED_STATUS Struct Type Name: SampleRejectedStatus

141

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure13-2:SampleRejectedStatusStructure

13.1.4 LivelinessChangedStatusTheLivelinessChangedStatusisusedtoinformtheapplicationofchangestoDataWritersknownbythisDataReader.DataReaderskeeptrackofallDataWriterstheyare‘matched’with.ThesematchedDataWritersmaybeACTIVE(theyareeitheractivelywritingdataorotherwiseassertingtheirliveliness)orINACTIVE(theyarenotactivelywritingorassertingtheirliveliness).AnytimeoneoftheDataWritersthisDataReaderismatchedwithchangesbetweenthesestates,theLivelinessChangedStatusisupdated.

Type: Plain Communication Status Associated Entity: DataReader Mask Name: LIVELINESS_CHANGED_STATUS Struct Type Name: LivelinessChangedStatus

CoreDXDDSProgrammer’sGuide

142

Figure13-3:LivelinessChangedStatusStructure

13.1.5 RequestedDeadlineMissedStatusTheRequestedDeadlineMissedStatusisusedtoinformtheapplicationwhenadeadlineperiodspecifiedinanassociatedDeadlineQoS(eitherTopicorDataReader)wasmissed.TheREQUESTED_DEADLINEQosallowstheapplicationtorequestthataninstancebeupdatedatleastonceeverytimeintervalspecifiedbytheQoS.WhenaDataWriterfailstoupdateaninstancewithinthetimeintervalspecifiedbytheDataReader’sDeadlineQoSpolicy,theRequestedDeadlineMissedStatusisupdated.

Type: Plain Communication Status Associated Entity: DataReader Mask Name: REQUESTED_DEADLINE_MISSED_STATUS Struct Type Name: RequestedDeadlineMissedStatus

143

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure13-4:RequestedDeadlineMissedStatusStructure

13.1.6 RequestedIncompatibleQoSStatusTheRequestedIncompatibleQoSStatusisusedtoinformtheapplicationthataDataWriterwasdiscoveredwithamatchingTopicandmatchingdatatype,butwithQoSincompatibletothisDataReader’srequestedQoS.ForadditionalinformationaboutcompatibleandincompatibleQoS,seetheQualityofServiceFeatureschapter.

Type: Plain Communication Status Associated Entity: DataReader Mask Name: REQUESTED_INCOMPATIBLE_QOS_STATUS Struct Type Name: RequestedIncompatibleQosStatus

Formatted: Font:Italic

Deleted: QualityofServiceFeatures

CoreDXDDSProgrammer’sGuide

144

Figure13-5:RequestedIncompatibleQoSStatusStructure

13.1.7 DataAvailableStatusTheDataAvailableStatusisoneofthereadcommunicationstatuses(alongwiththeDataOnReadersStatus),andisusedtoinformtheapplicationofnewdataavailabletobereadontheassociatedDataReader.

Thesetworeadcommunicationstatusesarecommunicatedtotheapplicationtogether.Inotherwords,ifthereisDataAvailableforaDataReader,thenthereisaDataReaderwithnewdata.

Type: Read Communication Status Associated Entity: DataReader Mask Name: DATA_AVAILABLE_STATUS Struct Type Name: N/A

145

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

13.1.8 SampleLostStatusTheSampleLostStatusisusedtoinformtheapplicationthatoneormoredatasampleswerenotreceivedbyaReader.Asamplecanbe‘lost’formanyreasons.

Forexample,thetransportmightdropthesampleduetocongestionorsomeotherreason.IftheReaderisusingBEST_EFFORTreliability,thensamplesdroppedbytheunderlyingtransportwillnotberetransmitted,andtheyareLOST.

EvenifreliabilityissettoRELIABLE,itisstillpossibletoexperiencelostsamplesduetootherQoSsettings.Forexample,iftheWriterisconfiguredtokeepverylittlehistoricaldatainitscache(eitherthroughHISTORYorRESOURCE_LIMITSQoS),thenitispossiblethataReaderwillfailtogetasamplesimplybecausethesampleispurgedfromtheWriter’scachebeforeitcouldbesuccessfullytransmittedtotheReader.

LostSamplesarenotavailabletothesubscribingapplication.

Type: Plain Communication Status Associated Entity: DataReader Mask Name: SAMPLE_LOST_STATUS Struct Type Name: SampleLostStatus

Figure13-6:SampleLostStatusStructure

CoreDXDDSProgrammer’sGuide

146

13.1.9 SubscriptionMatchedStatusTheSubscriptionMatchedStatusisusedtoinformtheapplicationthatanewDataWriterhasbeendiscoveredthatmatchesthisDataReader’sQoSsettingsanditisproducingdatathisDataReaderisinterestedin.Thatis,theDataWriteriswritingdataonthesameTopicthisDataReaderisreadingonanditsQoSsettingsarecompatiblewiththisDataReader.

Type: Plain Communication Status Associated Entity: DataReader Mask Name: SUBSCRIPTION_MATCHED_STATUS Struct Type Name: SubscriptionMatchedStatus

Figure13-7:SubscriptionMatchedStatusStructure

13.1.10 LivelinessLostStatusTheLivelinessLostStatusisusedtoinformtheapplicationthatthisDataWriterhasmissedassertingitslivelinessinthetimeperiodspecifiedbyitsLIVELINESSQoSpolicy.TheDataWriter’sLIVELINESSQoSpolicyallowsthepublishingapplicationtospecifytheintervalinwhichthisDataWriter

147

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

willeitherwriteasampleorassertitslivelinesstoallmatchedDataReaders.IfaDataWritermissesthisspecifiedwindow,theLivelinessLostStatusisupdated.

Type: Plain Communication Status Associated Entity: DataWriter Mask Name: LIVELINESS_LOST_STATUS Struct Type Name: LivelinessLostStatus

Figure13-8:LivelinessLostStatusStructure

13.1.11 OfferedDeadlineMissedStatusTheOfferedDeadlineMissedStatusisusedtoinformtheapplicationwhenadeadlineperiodspecifiedinanassociatedDeadlineQoS(eitherTopicorDataWriter)wasmissed.TheOFFERED_DEADLINEQosallowstheapplicationtocommittoupdatingeachinstanceatleastonceeverytimeintervalspecifiedbytheQoSsetting.WhentheDataWriterfailstoupdateaninstancewithinthespecifiedtimeinterval,theOfferedDeadlineMissedStatusisupdated.

Type: Plain Communication Status Associated Entity: DataWriter Mask Name: OFFERED_DEADLINE_MISSED_STATUS Struct Type Name: OfferedDeadlineMissedStatus

CoreDXDDSProgrammer’sGuide

148

Figure13-9:OfferedDeadlineMissedStatusStructure

13.1.12 OfferedIncompatibleQoSStatusTheOfferedIncompatibleQoSStatusisusedtoinformtheapplicationthataDataReaderwasdiscoveredwithamatchingTopicandmatchingdatatype,butwithQoSincompatibletothisDataWriter’sofferedQoS.ForadditionalinformationaboutcompatibleandincompatibleQoS,seetheQualityofServiceFeatureschapter.

Type: Plain Communication Status Associated Entity: DataWriter Mask Name: OFFERED_INCOMPATIBLE_QOS_STATUS Struct Type Name: OfferedIncompatibleQosStatus

Formatted: Font:Italic

Deleted: QualityofServiceFeatures

149

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure13-10:OfferedIncompatibleQoSStatusStructure

13.1.13 PublicationMatchedStatusThePublicationMatchedStatusisusedtoinformtheapplicationthatanewDataReaderhasbeendiscoveredthatmatchesthisDataWriter’sQoSsettings.

Type: Plain Communication Status Associated Entity: DataWriter Mask Name: PUBLICATION_MATCHED_STATUS Struct Type Name: PublicationMatchedStatus

CoreDXDDSProgrammer’sGuide

150

Figure13-11:PublicationMatchedStatusStructure

13.2 ApplicationAccesstoCommunicationStatusAnapplicationcanaccessplaincommunicationstatusesassociatedwithanentitybycallingthatentity’sget_<status_name>()method.Forexample,aDataReaderwillhaveaget_sample_lost_status()methodtoobtainasnapshotofitsSampleLostStatus,andaTopicwillhaveaget_inconsistent_topic_status()methodtoobtainasnapshotofitsInconsistentTopicStatus.

Readcommunicationstatusareusedtoindicatetheavailabilityofdata.ThedatamaythenaccessedbycallingtheDataReaderread()ortake()methods.Theapplicationmaycallread()ortake()directlyatanytime,evenifthereisnodataavailable.

Whiletheapplicationcanchoosetocallget_xxx_status(),read(),ortake()atanytime,typicallytheapplicationwillwaitfornotificationfromtheinfrastructurethatastatushaschanged(ordataisavailable)beforeaccessingthestatusinformationordata.

151

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Therearetwomechanismsanapplicationmayusetolearnaboutchangesincommunicationstatusesandstatistics.Thefirstislisteners,whereanapplicationcanasynchronouslyhandleachangeincommunicationstatuses.Thesecondisconditions(usingwaitsets),whereanapplicationcanblockwaitingforastatuschange.

13.2.1 ListenersListenersprovideanasynchronousmethodfortheapplicationtobenotifiedofchangesinstatuses.TheapplicationprovidesahookfortheCoreDXDDSmiddlewaretoinvokeuponaparticularstatuschange.Forexample,anapplicationinterestedintheDataAvailableStatusforitsDataReaderwillprovideanon_data_available()methodtotheCoreDXDDSmiddleware,andtheCoreDXDDSmiddlewarewillcalltheprovidedmethodwhennewdataisavailableonthatDataReader.

AllDDSentitiessupportalistener,andalllistenershaveatypespecifictotheirassociatedentity.Forexample,theDataReaderListenerisassociatedwithaDataReader.

Listenersareinterfaces.Eachlistenerprovidesasetofmethodsthatcorrespondtotherelevantcommunicationstatusesforthatentity.

Listenersarehierarchical.Figure13-12:ListenerHierarchydepictsthehierarchyofallthelisteners.

Formatted: Font:Italic

Deleted: Figure13-12:ListenerHierarchy

CoreDXDDSProgrammer’sGuide

152

Figure13-12:ListenerHierarchy

Theapplicationmustimplementanappropriatelistenerinterfaceinordertoreceivecommunicationstatuschanges.ThefollowingTable13-2depictsthelistenermethodsforeachentity.

Deleted: Table13-2

153

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Table13-2:ListenerMethodSignatures

Entity ListenerMethodSignature

DataReaderListener voidon_requested_deadline_missed(DataReader,RequestedDeadlineMissedStatus);

voidon_requested_incompatible_qos(DataReader,RequestedIncompatibleQosStatus);

voidon_sample_rejected(DataReader,SampleRejectedStatus);

voidon_liveliness_changed(DataReader,SampleRejectedStatus);

voidon_data_available(DataReader);

voidon_subscription_matched(DataReader,SubscriptionMatchedStatus);

voidon_sample_lost(DataReader,SampleLostStatus);

SubscriberListener voidon_data_on_readers(Subscriber);

(inheritsallDataReaderListenermethods)

TopicListener voidon_inconsistent_topic(Topic,InconsistentTopicStatus);

DataWriterListener voidon_liveliness_lost(DataWriter,LivelinessLostStatus);

voidon_offered_deadline_missed(DataWriter,OfferedDeadlineMissedStatus);

voidon_offered_incompatible_qos(DataWriter,OfferedIncompatibleQosStatus);

voidon_publication_matched(DataWriter,PublicationMatchedStatus);

PublisherListener (inheritsallDataWriterListenermethods)

DomainParticipantListener (inheritsallSubscriberListener,PublisherListener,andTopicListenermethods)

CoreDXDDSProgrammer’sGuide

154

Noticethatthelistenermethodsforplaincommunicationstatusesfollowthesameformat:theyreturnavoidandtaketheentityandappropriatestatusasarguments.Thelistenermethodsforreadcommunicationstatusesarealittledifferent.Readcommunicationstatusesdonothaveassociatedstatusstructures.TheonlyargumentistheconcernedDataReader(fortheon_data_available()method)andSubscriber(fortheon_data_on_readres()method).Itisassumedthatinhandlingthereadcommunicationstatus,theapplicationintendstoeventuallyreadtheavailabledata,andprovidingtheappropriateDataReaderorSubscriberallowstheapplicationtodothis.

Theapplicationmayuseall,some,ornoneofthelistenermethodsforanEntity.Forexample,anapplicationmayonlybeinterestedintheDataReader’sdata_availablestatus,andimplementonlytheon_data_availablel()listenermethod.Whentheapplicationattachesalistenertoanentity,itmustalsosetamaskthatindicateswhichlistenermethodsareenabledwithinthislistener.

13.2.1.1 ListenerAccesstoPlainCommunicationStatusesNoticeinFigure13-12thatthelistenersformahierarchy.Whenaplaincommunicationstatuschanges,themiddlewarewillinvokethemostspecificrelevantlistenermethodthatisenabled.

Forexample,considerthePublicationMatchedStatus.Thecorrespondingon_publication_matched()listenermethodcomesfromtheDataWriterListener,andisinheritedbythePublisherListenerandtheDomainParticipantListener.WhenthereisachangetothePublicationMatchedStatus,theDDSinfrastructurewilllookforanenabledon_publication_matched()listenermethodtoinvoke.ItwilllookattheDataWriterListenerfirst.Ifthereisnotanenabledon_publication_matched()listenermethod,itwillthenlookatthePublisherListener.Ifthereisnotanenabledon_publication_matched()listenermethod,itwilllookattheDomainParticipantListener.Thefirstenabledlistenermethodwillbeinvoked.Iftherearenolistenersenabled,nolistenermethodswillbeinvoked.ThestatusisstillavailableandmaytriggeraconfiguredCondition,orbeaccessedbycallingtheassociatedget_xxx_status().

13.2.1.2 ListenerAccesstoReadCommunicationStatusesThereadcommunicationstatuslistenersareinvokeddifferentlythanplaincommunicationstatuslisteners.Thetworeadcommunicationstatuses

Formatted: Font:Italic

Deleted: Figure13-12

155

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

constitutetherealpurposeoftheDataDistributionService,andrequirespecialconsideration.

EachtimeareadcommunicationstatuschangestheDDSperformthefollowingactions.

1. Theinfrastructurewillattempttoinvoketheon_data_on_readers()methodontheSusbscriberListenerwithaparameteroftherelatedSubscriber

2. Ifthisdoesn’twork(eithertherewasnolistenerinstalledorthemethodwasnotenabledviathelistenermask),theDDSmiddlewarewillattempttotriggertheon_data_available()methodontherelatedDataReaderListenerwithaparameteroftherelatedDataReader.

13.2.1.3 NilListenersTheapplicationcanchoosetoinstallanillistenerinplaceofanylistenermethod.Whentheinfrastructurefindsanillistener,itwillperformaNO-OPoperationandstoplookingforenabledlistenermethods.

13.2.1.4 ImplementingListenersinCListenersinCareimplementedasastructureoffunctionpointers.Inordertoimplementalistenermethod,theapplicationmustwriteafunction,andthenassignittotheappropriatelistenerfunctionpointer.

Forexample,aDataReaderinterestedinonlytheDATA_AVAILABLEstatusmightdothefollowing:

on_data_availableListener

void my_on_data_available( DDS_DataReader dr ) { Printf(“Data is available!\n”); /* process data by calling DDS_DataReader_read() * or DDS_DataReader_take() */ } DDS_DataReaderListener drListener = { NULL, NULL, NULL, NULL, my_on_data_available, NULL, NULL }

CoreDXDDSProgrammer’sGuide

156

/* when we create the DataReader */ Dr = DDS_Subscriber_create_datareader( sub,

DDS_Topic_TopicDescription(topic), &drListener, DDS_DATA_AVAILABLE_STATUS);

Figure13-13:ListenerExampleCCode

Thelastargumenttothecreate_datareader()methodisthelistenerstatusmask,tellingtheDDSmiddlewarewhichlistenermethodsareenabled.

InC,anillistenerisinstalledsimplybysettingtheappropriatefunctionpointertoNULL,andthensettingthatstatusinthelistenermask.Supposeintheaboveexample,thelistenermaskusedinthecreate_datareader()callwas:

DDS_DATA_AVAILABLE_STATUS | DDS_LIVELINESS_CHANGED_STATUS

Thentherewouldbeanillistenerinstalledfortheon_liveliness_changed()method,andanactuallistenerinstalledfortheon_data_available()method.Allotherlistenermethodswoulddefault“down”thelistenerhierarchy,lookingforenabledcorrespondinglistenermethodsontheSubscriber,andthentheDomainParticipant.

ThedefinitionofalltheClistenerscanbefoundintheCoreDXDDSheaderfile(DDS_HOME/include/dds/core/dds.hordds.hh).

13.2.1.5 ImplementingListenersinC++ListenersinC++areclassescontainingvirtualon_<communication_status>()methods.Inordertoimplementalistenermethod,theapplicationmustcreatealistenerclassthatderivesfromtheappropriatevirtuallistenerclass,andthenimplementthedesiredlistenermethod.

ForexampleaDataReaderwhoisonlyinterestedintheDATA_AVAILABLEstatusmightdothefollowing:

on_data_availableListener

class MyDRListener : public DataReaderListener { public:

157

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

void on_data_available( DataReader * dr ); }; void MyDRListener::on_data_available(DataReader * dr) { printf(“Data Available!\n”); /* process data by calling read() or take() */ } /* when we create the DataReader */ MyDRListener drListener; Dr = sub->create_datareader( (TopicDescription*)topic, DATAREADER_QOS_DEFAULT, &drListener, DATA_AVAILABLE_STATUS );

Figure13-14:ListenerExampeC++Code

ToinstallanillistenerinC++,usethenil_listenersmemberontheappropriatelistenerobject.Forexample,toaddanillistenerfortheon_liveliness_changed()listenermethod:

drListener . nil_listeners = LIVELINESS_CHANGED_STATUS;

ThisindicatestotheDDSmiddlewarethattheon_liveliness_changed()listenermethodshouldbetreatedasanillistenermethod.

13.2.1.6 ImplementingListenersinC#ListenersinC#areclassesthatmaybeusedasabaseclassforapplicationdataspecificListeners.Inordertoimplementalistenermethod,theapplicationmustcreatealistenerclassthatderivesfromtheappropriatelistenerbaseclass,andthenimplementthedesiredlistenermethod.

ForexampleaDataReaderwhoisonlyinterestedintheDATA_AVAILABLEstatusmightdothefollowing:

on_data_availableListener

class MyDRListener : DataReaderListener { Public MyDRListener() { this.on_requested_deadline_missed = null; this.on_requested_incompatible_qos = null; this.on_sample_rejected = null; this.on_liveliness_changed = null; this.on_data_available = data_available;

CoreDXDDSProgrammer’sGuide

158

this.on_subscription_matched = null; this.on_sample_lost = null; } public void data_available( DataReader dr ) { System.Console.WriteLine (“Data Available!\n”); /* process data by calling read() or take() */ } /* when we create the DataReader */ MyDRListener drListener = new MyDRListener(); Dr = sub->create_datareader( topic, DDS.DATAREADER_QOS_DEFAULT, drListener, DDS.DATA_AVAILABLE_STATUS );

Thelastargumenttothecreate_datareader()methodisthelistenerstatusmask,tellingtheDDSmiddlewarewhichlistenermethodsareenabled.

InC#,anillistenerisinstalledsimplybysettingtheappropriatefunctionpointertoNULL,andthensettingthatstatusinthelistenermask.Supposeintheaboveexample,thelistenermaskusedinthecreate_datareader()callwas:

DDS.DATA_AVAILABLE_STATUS | DDS.LIVELINESS_CHANGED_STATUS

Thentherewouldbeanillistenerinstalledfortheon_liveliness_changed()method,andanactuallistenerinstalledfortheon_data_available()method.Allotherlistenermethodswoulddefault“down”thelistenerhierarchy,lookingforenabledcorrespondinglistenermethodsontheSubscriber,andthentheDomainParticipant.

13.2.1.7 ImplementingListenersinJavaListenersinJavaareinterfacescontainingemptyon_<communication_status>()methods.Inordertoimplementalistenermethod,theapplicationmustcreatealistenerclassthatimplementstheappropriatelistenerinterface,andthencreatepublicversionsofalllistenermethods.Listenermethodsmaybeempty.

ForexampleaDataReaderwhoisonlyinterestedintheDATA_AVAILABLEstatusmightdothefollowing:

159

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

on_data_availableListener

class MyDRListener implements DataReaderListener { public long get_nil_mask() { return 0; } public void on_data_available(DataReader dr) { System.out.println(" DATA AVAILABLE "); /* process data by calling read() or take() */ } public void on_requested_deadline_missed(DataReader dr, RequestedDeadlineMissedStatus status) { }; public void on_requested_incompatible_qos(DataReader dr, RequestedIncompatibleQosStatus status) { }; public void on_sample_rejected (DataReader dr, SampleRejectedStatus status) { }; public void on_liveliness_changed (DataReader dr, LivelinessChangedStatus status) { }; public void on_subscription_matched (DataReader dr, SubscriptionMatchedStatusstatus) { }; public void on_sample_lost(DataReader dr, SampleLostStatus status) { }; /* when we create the DataReader */ DataReaderListener dr_listener = new MyDRListener(); dr = sub.create_datareader( topic, DDS.DATAREADER_QOS_DEFAULT, drListener, DDS.DATA_AVAILABLE_STATUS );

ToinstallanillistenerinJava,implementtheget_nil_maks()methodontheappropriatelistenerobjecttoreturnthecorrespondingstatus.Forexample,toaddanillistenerfortheon_liveliness_changed()listenermethod:

public long get_nil_mask() { return DDS.LIVELINESS_CHANGED_STATUS; }

ThisindicatestotheDDSmiddlewarethattheon_liveliness_changed()listenermethodshouldbetreatedasanillistenermethod.

13.2.2 ConditionsandWaitSetsThelistenernotificationmethodisasynchronous.ConditionsandWaitSetsprovideawait-basedmechanismtobenotifiedofchangesintheCoreDX

CoreDXDDSProgrammer’sGuide

160

DDSinfrastructure.Ingeneral,theapplicationusingConditionsandWaitSetswillusethefollowingpattern.

1. TheapplicationindicateswhichstatusesitisinterestedinbyobtainingorcreatingoneormoreConditionobjectsandattachingthemtoaWaitSet.

2. TheapplicationwaitsontheWaitSetuntilthetriggervalueofoneormoreoftheattachedConditionobjectsbecomesTRUE.

3. Theapplicationcallsget_status_changes()todeterminethewhatchanged.

4. Theapplicationcallstheappropriateget_<communication_status>(),read(),ortake()method(s).

ConditionsarealwaysusedincombinationwithaWaitSet.TheConditioncontainsatriggervaluethatissetwhenthereisachange(changeincommunicationstatus,changeinreadstatus,forexample).TheWaitSetblockstheapplicationuntiltheCondition’striggervalueisset(oruntilanapplication-definedtimeoutisreached).TherearedifferentkindsofConditionsavailablefortheapplicationtouse.Thesearedescribedinthesectionsbelow.

13.2.2.1 StatusConditionsStatusConditionsallowtheapplicationtoaccessplaincommunicationstatuses.AConditioncanbeobtainedfromeachentitythatcontainsacommunicationstatus,byusingtheget_status_condition()operation.

AStatusConditioncontainsamaskofenabledstatuses.Similartothelistenermask,thismaskallowstheapplicationtotailortheConditiontotriggeronlyforspecificstatuschanges.Forexample,aDataWritercontainsfourstatuses:liveliness_lost,offered_deadline_missed,offered_incompatible_qos,andpublication_matched.TheStatusConditionreturnedfromDataWriter::get_statuscondition()willhaveallfourstatusesenabledbydefault.IfanyoneofthesestatuseschangesfortheDataWriter,theConditionwillbeset,andtheapplicationwaitingonthecorrespondingWaitSetwillbesignaled.Theapplicationcanusetheenabledstatusesmasktoenableonlythecommunicationsstatusesthatareofinteresttotheapplication.

13.2.2.2 ReadConditionsandQueryConditionsReadConditionsandQueryConditionsallowtheapplicationtobenotifiedwhendataisavailable.Specifically,theseConditionsallowtheapplicationtobenotifiedwhenaspecifickindofdataisavailable.TheReadCondition

161

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

allowstheapplicationtoconfiguretheview_states,instance_states,andsample_statesthattheReadConditionshouldtriggeron.TheQueryConditionallowstheapplicationtodefinethecontentofthedatasamplesthatshouldtriggertheQueryCondition.Thisisdoneusingansql-likequerystring.

13.2.2.3 GuardConditionsGuardConditionsallowtheapplicationtocontroltriggeringthecondition.GuardConditionsarenotattachedtoaCoreDXDDSentity(DataReader,Topic,etc),rathertheycanbeusedbytheapplicationforsynchronizationeffortsoutsidetheDDSmiddleware.BecausetheseconditionsarenotattachedtoaCoreDXDDSentity,theyarecreatedbyusingtheGuardCondition__alloc()operation(Cinterface),ortheGuardConditionconstructor(C++,C#,Javainterfaces).TheapplicationisresponsibleforreleasingtheGuardConditionmemory.

13.2.2.4 ImplementingConditionsinCConditionExamples

/* Variabled used in sample code */ DDS_DataReader dr; DDS_StatusMask sm; DDS_StatusCondition sc; DDS_ReadCondition rc; DDS_WaitSet ws; DDS_ConditionSeq active_conditions; DDS_Duration_t timed; DDS_ReturnCode_t retval; /* Create DomainParticipant, register data type,

* create Topic, Subscriber – code not shown here. */ /* Create DataReader with no Listeners */ dr = DDS_Subscriber_create_datareader( sub, DDS_TopicDescription(topic), DDS_DATAREADER_QOS_DEFAULT, NULL, 0); /* Get the StatusCondition, configure to only trigger on

* subscription matched status changes

CoreDXDDSProgrammer’sGuide

162

*/ sc = DDS_DataReader_get_statuscondition( dr ); sm = DDS_SUBSCRIPTION_MATCHED_STATUS; retval = DDS_StatusCondition_set_enabled_statuses( sc, sm ); /* Create the ReadCondition, configure to trigger * only on samples not yet read */ rc = DDS_DataReader_create_readcondition( dr, DDS_NOT_READ_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE );

/* Create a WaitSet and attach all my conditions */ ws = DDS_WaitSet__init( DDS_WaitSet__alloc() ); retval = DDS_WaitSet_attach_condition( ws, sc ); retval = DDS_WaitSet_attach_condition( ws, rc ); /* Wait for something to happen (no timeout) */ INIT_SEQ(active_conditions); timed.sec = 0; /* infinite */ timed.nanosec = 0; retval = DDS_WaitSet_wait( ws, &active_conditions, &timed ); /* Something woke us up -- check */ for (i=0 ; i<seq_get_length(&active_conditions) ; i++) { if ( active_conditions._buffer[i] == (DDS_Condition)sc ) { /* If you don’t already know what entity this * StatusCondition is attached to, here’s how * to find out. */ DDS_Entity e = DDS_StatusCondition_get_entity(sc); DDS_DataReader r = (DDS_DataReader)e; DDS_StatusMask s = DDS_DataReader_get_status_changes(r); if ( s & DDS_SUBSCRIPTION_MATCHED_STATUS ) /* Handle subscription match */ }

else if ( active_conditions._buffer[i] == (DDS_Condition)rc ) { /* handle data available on our DataReader ‘dr’ */ }

} /* Cleanup */ retval = DDS_DataReader_delete_readcondition( dr, rc );

163

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure13-15:ConditionExampleCcode

13.2.2.5 ImplementingConditionsinC++ConditionExamples

using namespace DDS; /* Variabled used in sample code */ DataReader * dr; StatusMask sm; StatusCondition * sc; ReadCondition * rc; WaitSet ws; ConditionSeq active_conditions; Duration_t timed; ReturnCode_t retval; /* Create DomainParticipant, register data type,

* create Topic, Subscriber – code not shown here. */ /* Create DataReader with no Listeners */ dr = sub->create_datareader( (TopicDescription)topic, DATAREADER_QOS_DEFAULT, NULL, 0); /* Get the StatusCondition, configure to only trigger on

* subscription matched status changes */

sc = dr -> get_statuscondition(); sm = SUBSCRIPTION_MATCHED_STATUS; retval = sc -> set_enabled_statuses( sm ); /* Create the ReadCondition, configure to trigger * only on samples not yet read */ rc = dr -> create_readcondition( NOT_READ_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE );

/* Create a WaitSet and attach all my conditions */ retval = ws . attach_condition( sc ); retval = ws . attach_condition( rc ); /* Wait for something to happen (no timeout) */ timed.sec = 0; /* infinite */ timed.nanosec = 0; retval = ws . wait( &active_conditions, &timed );

CoreDXDDSProgrammer’sGuide

164

/* Something woke us up -- check */ for (i=0 ; i<active_conditions . size() ; i++) { if ( active_conditions[i] == (Condition)sc ) { /* If you don’t already know what entity this * StatusCondition is attached to, here’s how * to find out. */ Entity e = sc -> get_entity(); DataReader r = (DataReader)e; StatusMask s = r -> get_status_changes(); if ( s & SUBSCRIPTION_MATCHED_STATUS ) /* Handle subscription match */ }

else if ( active_conditions[i] == (Condition)rc ) { /* handle data available on our DataReader ‘dr’ */ }

} /* Cleanup */ retval = dr -> delete_readcondition( dr, rc );

Figure13-16:ConditionExampleC++code

13.2.3 UsingListenersandConditionsinCombinationTheapplicationmaychoosetousebothlistenersandconditionsincombination.Onewaytodothisisusinglistenersforsomecommunicationstatusesandusingconditionsforothercommunicationstatus.However,ifbothlistenersandconditionsareusedforanindividualcommunicationstatus,thelistenermethodisinvokedfirstandthentheconditionobjectsaresignaled.Sincecallingalistenerhastheeffectof“resetting”thestatus,whentheConditionissignaledthecorrespondingstatuswillnotbeset.

165

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

166

Part4: CoreDXDDSExtensions

ThissectionintroducessomeCoreDXDDSspecificextensionstotheDDSAPI.Theseincludefacilitiesforlogging,transports,licensing,adjustingthediscoverymechanisms,namingDDSentities,andotherconceptsthatmakeusingDDSeasier.

167

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

168

Chapter14 CoreDXDDSLogging

ThischapterdescribestheloggingfacilitiesprovidedbyCoreDXDDSandhowtoconfigurethem.

First,itshouldbenotedthattherearetwoversionsofCoreDXDDSlibrariesprovided.Thefirstistheoptimized,performancefocusedlibrarywhichdoesnotcontaintheextralogginginstrumentationcode.Thislibraryisfasterandsmallerthantheinstrumentedlibrary.Thislibrarycontainsverylittlelogging,primarilylimitedtoindicatingerrororanomalousconditions.

Thesecondversionoflibrariesincludesarichsetoflogginginstrumentation.Duringapplicationdevelopmentanddebugging,itmaybeusefultolinkagainsttheloggingversionoftheCoreDXDDSlibraries.Then,deployedapplicationscanbelinkedwiththestreamlinedlibrariesforenhancedperformanceandresourceutilization.

ForC#andJavausers:Thecoredx_csharp.dll(C#)andcoredx_dds.jar(java)packagesrefertothenon-loggingnativelibraryname(dds_csharp.dll/libforC#anddds_java.so/dll/libforjava).Inordertousetheloggingversionsoftheselibraries,theselibrariesmustberenamed(orlinkedto).Forexample,tousetheJavalogginglibraryunderLInux:

% cd ${COREDX_TOP}/target/${TARGET_ARCH} % ls –l libdds_java*

-rw-r--r-- 1 user grp libdds_java_log.so -rw-r--r—- 1 user grp libdds_java.so

% mv libdds_java.so libdds_nolog.so % ln –s libdds_java_log.so libdds_java.so % ls –l libdds_java*

-rw-r--r-- 1 user grp libdds_java_log.so -rw-r--r-- 1 user grp libdds_java_nolog.so -rw-r--r—- 1 user grp libdds_java.so -> libdds_java_log.so

Oncetheapplicationhasbeenlinkedwiththeinstrumentedlibrary,theloggingoutputcanbecontrolledeitherbyenvironmentvariableorbyadjustingtheCoreDX_LoggingQosPolicy.

Controllingloggingwithanenvironmentvariableisquickandeasy,butdoesnotofferfine-grainedcontrol.TheLoggingQoSpolicyoffersgreatercontrol.

169

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Whichevermechanismisused,thelevelofloggingoutputiscontrolledbyaseriesofbitmappedflags.Eachclassoflogmessageisenabledbysettingaflagto1,andisdisabledby0.

Thefollowingtablelistssomeoftheloggingflagsavailable.Thefulllistofloggingflagscanbefoundin$COREDX_TOP/target/include/dds/coredx_logging.h

Table14-1:CoreDXDDSLoggingFlags

CoreDXDDSDebugCategoriesandFlags

COREDX_ERROR_LOGGING_QOS 0x0001 COREDX_DATA_LOGGING_QOS 0x0002 COREDX_DISCOVERY_LOGGING_QOS 0x0004 COREDX_FACTORY_LOGGING_QOS 0x0008 COREDX_LIVELINESS_LOGGING_QOS 0x0010 COREDX_STATUS_LOGGING_QOS 0x0020 COREDX_TRANSPORT_LOGGING_QOS 0x0040 COREDX_SCHEDULE_LOGGING_QOS 0x0080 COREDX_HANDSHAKE_LOGGING_QOS 0x0100 COREDX_CACHE_LOGGING_QOS 0x0200 COREDX_SECURITY_LOGGING_QOS 0x0400 COREDX_TRACE_LOGGING_QOS 0x0800 COREDX_RPC_FACTORY_LOGGING_QOS 0x1000 COREDX_RPC_REQUEST_LOGGING_QOS 0x2000 COREDX_RPC_REPLY_LOGGING_QOS 0x4000

Currently,allloggingoutputisdirectedtostderr.ThereisanadditionalfieldintheCoreDX_LoggingQosPolicy(uri)thatwillbeusedtodirectloggingoutputtootherlocations,sockets,ddstopics,etcinafutureCoreDXDDSrelease.Currently,thisfieldisunused.

Table14-2:LoggingQoSConfigurationExample

SettingCoreDXDDSLoggingFlags

DDS_Subscriber sub; DDS_DataReader dr;

DDS_DataReaderQos dr_qos;

CoreDXDDSProgrammer’sGuide

170

DDS_Subscriber_get_default_datareader_qos(sub, &dr_qos); dr_qos.logging.flags |= (COREDX_FACTORY_LOGGING_QOS |

COREDX_DATA_LOGGING_QOS | COREDX_STATUS_LOGGING_QOS);

dr = DDS_Subscriber_create_datareader(sub, td, &dr_qos, NULL, 0);

171

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter15 CoreDXDDSTransport

TheCoreDXDDStransportconformstotheReal-TimePublish-Subscribe(RTPS)WireProtocol.Thistransportdoesnotuseastand-alonetransportdaemon,anddoesnotrequireconfigurationofanyoperatingsystemservices.

15.1 OverviewCoreDXDDSincludesamodulartransportinfrastructurethatsupportsconfigurationandcustomization.CoreDXDDSshipswithsupportforUDP(onIPv4andIPv6),TCP(IPv4,IPv6planned),LMT(LocalMachineTransport),andSERIAL.[Someplatformsdonotsupportallkindsoftransports–checkwithTwinOakstodeterminetheavailabilityforyourplatform.]

Eachtransportimplementationincludesthecapabilitytoconfigureaspectsofthetransport.Thesetofconfigurationoptionsavailableforeachtransportaredescribedindetailinsubsequentsections.

Bydefault,CoreDXDDSwillinstallandusetheUDPtransport.Alternatively,thedevelopercanconfigureandinstallalternateoradditionaltransportsduringtheinitializationofaDomainParticipant.

15.1.1 TransportCommonAPIEachtransportimplementationprovidesasetofmethodstofacilitateaccesstoconfigurationparametersandcreationofthetransport;thesearereferredtoastheTransportInitializationAPI.InadditiontothisAPI,thissectionalsodescribestheDomainParticipantmethodtoaddtheconfiguredtransport(s).

UsingtheCoreDXDDSTransportInitializationAPI,thedevelopercanconfigureandcreateaninstanceofatransport.TheAPIprovidesamechanismtoretrievethedefaultconfigurationsettings.Thesesettingscanbemodifiedbythedeveloperasrequiredbeforepassingthemto‘create’.The‘create’operationacceptsastructurethatcontainsalloftheconfigurationparameters.

CoreDXDDSProgrammer’sGuide

172

Forexample,the‘C’TransportInitializationAPIfortheUDPtransportconsistsofthefollowingmethods:

DDS_ReturnCode_t CoreDX_UdpTransport_get_default_config( CoreDX_UdpTransportConfig * config );

DDS_ReturnCode_t CoreDX_UdpTransport_get_env_config( CoreDX_UdpTransportConfig * config );

DDS_ReturnCode_t CoreDX_UdpTransport_clear_config( CoreDX_UdpTransportConfig * config );

CoreDX_Transport *CoreDX_UdpTransport_create_transport( CoreDX_UdpTransportConfig * config );

EachtransportimplementationwillprovidethissetofTransportInitializationAPImethods.Thesemethodsarefurtherdescribedbelow.

15.1.1.1 Transport::get_default_config()Theget_default_config()methodwillinitializeallfieldsintheprovidedTransportConfigstructurewithdefaultvalues.Thisprovidesagoodstartingpointforcustomconfigurationmodifications.Iftheuserdoesnotcallget_default_config(),thentheuserisresponsibleformanuallyinitializingallfieldsintheTransportConfigstructure.

OncetheTransportConfigstructurehasbeeninitializedwiththedesiredconfigurationvalues,theconfigurationcanbepassedtothecreate_transport()method.Thetransportwillutilizetheprovideconfigurationvaluestoinitializethecharacteristicsofthetransport.Oncecreate_transport()returns,thecallercandestroyorreusetheTransportConfigstructure–thetransportimplementationdoesnotholdanyreferencestotheprovidedstructure.

ThecallerisresponsibleforclearinganyallocatedmemorywithintheTransportConfigstructure.Themethodclear_config()willaccomplishthis.

15.1.1.2 Transport::get_env_config()

173

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

ThismethodwilloverridevaluesintheprovidedTransportConfigstructurewithvaluestakenfromtheenvironment.Sometransportsallowtheusertoadjustconfigurationparametersbysettingenvironmentvariables.Thisroutinewillquerytheenvironmentandsetconfigurationparametersbasedondiscoveredvalues.[Notalltransportsuseenvironmentvariablesforconfiguration.]Inallcases,theenvironmentvariablebasedconfigurationparametersareprovidedasaconvenience–thesameresultcanbeobtainedbydirectlyadjustingvalueswithintheTransportConfigstructure.

TheprovidedTransportConfigstructureshouldbeinitializedtodefaultvalues(eithermanuallyorbycallingget_default_config())priortocallingthisroutine.

15.1.1.3 Transport::clear_config()ThisroutinewillclearanyallocatedmemorywithintheprovidedTransportConfigstructure.Insomecases,aTransportConfigstructuremaycontaindynamicallyallocatedvalues.Thismemorymayhavebeenallocatedbytheget_default_config()orget_env_config()methods,orbytheuser.EachtransporthasadifferentTransportConfigstructurewhichmayormaynotincludeparametersthathavedynamicmemoryallocations.Clear_config()providesamechanismtoreleaseanydynamicallyallocatedmemorywithintheTransportConfigstructure.

15.1.1.4 Transport::create_transport()Thisroutinewillcreateaninstanceofthetransport.ThereturnedtransportinstancecanthenberegisteredwithaDomainParticipant.TheprovidedTransportConfigstructurewillbeusedtoconfigurethetransportduringcreation.TheusermaintainsownershipoftheTransportConfigstructure,andcanclearorreuseitafterthecreate_transport()callreturns.

Onsuccess,thecreate_transport()methodwillreturnapointertoaninitializedtransportinstance.Ifthereisanerrorduringcreation,NULLwillbereturned.Normally,theresultingtransportwillbepassedtoDomainParticipant::add_transport().Inthiscase,theDomainParticipanttakesownershipofthetransport,andtheusershouldnolongeraccessthetransportinstance.IftheuserdoesnotregisterthetransportwithaDomainParticipant,thentheusermaintainsownershipofthetransportinstanceandisresponsiblefordestroyingit.ThiscanbeaccomplishedbyinvokingtheTransport::destroymethod.

15.1.1.5 DomainParticipant::add_transport()

CoreDXDDSProgrammer’sGuide

174

Thisroutine,whilenotstrictlypartoftheTransportAPI,isusedtoaddaconfiguredtransporttotheDomainParticipant.

DDS_ReturnCode_t DDS_DomainParticipant_add_transport(

DDS_DomainParticipant dp, CoreDX_Transport * transport);

Iftheapplicationdoesnotinstallanytransportsusingtheadd_transport()method,theDomainParticipantwillautomaticallycreateandregisteradefaultUDPtransport.

15.1.2 TransportConfigurationThissectiondocumentsthedetailsofeachtransport.Thisincludesadiscussionofthetransportspecificconfigurationparameters.

15.1.2.1 UDPTransportAPITheUDPtransportisthedefaultCoreDXDDStransport.ItprovidesthefullyRTPScompliant,interoperable,DDStransport.TherearemanyconfigurationoptionstotheUDPtransport.

ItprovidessupportforUNICASTandMULTICASTtransmissionandreception.Bydefault,MULTICASTisenabledforboth‘built-in’(discovery)dataand‘user’data.FordiscoveryconfigurationoptionsoverUDP,refertoChapter16CoreDXDDSDiscovery.

ThespecificconfigurationparametersavailablewiththeUDPtransportaredescribedinthefollowingsections.

15.1.2.1.1 ParticipantIndex

ParticipantIndexisanintegernumberthatbydefaultiscomputedautomaticallybytheRTPSimplementation.ItisusedtodistinguishDomainParticipantsonthesamehostandinthesameDomainfromoneanother.Insomecases,itishelpfultodirectlyconfigurethisvalueasitisusedtocomputeunicastportnumbers.Itisanerrortoconfigure2ormoreDomainParticipantsonthesamehost,withinthesameDomain,suchthattheyhavethesameParticipantIndexvalue.

175

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

15.1.2.1.2 IPv4andIPv6

ThetransportisconfiguredtooperateoverIPv4bydefault;andcanbeconfiguredtosupportIPv6.The‘use_ipv4’and‘use_ipv6’configurationparametersprovidecontroloverwhichversion(s)ofIPwillbeused.

15.1.2.1.3 Interfaces

Thetransport,bydefault,willmakeuseofallavailableactivenetworkinterfaces.Ifyourmachinehasmultiplenetworkinterfaces,thismaygenerateunnecessarynetworktrafficonsomeofthosenetworks.Thetransportcanbeconfiguredtouseasubsetofavailableinterfaces.The‘interfaces’configurationparametercanbeconfiguredwithalistofinterfaceaddresses.Ifthelistisempty,thenCoreDXDDSwillquerytheoperatingsystemtoobtainalistofallavailableactiveinterfaces.

NOTE:WhenconfiguringastaticlistofinterfacesforCoreDXDDStouse,youmayalsowanttodisabledynamicinterfacedetection(below).

15.1.2.1.4 DynamicInterfaceDetection

OnOperatingSystemsthatsupportit,theCoreDXDDSUDPtransportcandetectchangestothenetworkinterfacesandadjustitsconfigurationinresponse.Forexample,iftheuserbringsupanewinterface,CoreDXDDSwilldiscoverandutilizethenewinterfaceonthefly.Thisdynamicinterfacedetectionisconfigurable.The‘dynamic_interfaces’configurationparameterisusedtoenableordisablethiscapability.

15.1.2.1.5 RXBufferSizes

TheUDPtransportmaintainsbufferstohandleincomingdatapackets.Inordertopreservememory,thesizeandbehaviorofthereceivebufferisconfigurable.Bydefault,thereceivebufferbeginssmallandcangrowdynamicallyasrequiredtohandletheincomingdata.Theinitialsizeofthebufferisdeterminedbythe‘rx_init_buffer_size’parameter.Themaximumsizeofthebufferislimitedbythe‘rx_max_buffer_size’configurationparameter.Ifthesetwovaluesareidentical,thenthebufferwillnotdynamicallyresize,andallmemoryallocationisperformedduringinitialization.

NOTE:IfthemaximumsizeoftheRXBufferislimitedtosomevaluesmallerthanthatallowedbytheunderlyingtransport(inthiscase,UDPmaximumdatagramsizeis64KB),thenitispossiblethatthetransportwillbeforcedtodropsomeincomingdata.ThesizeofincomingUDPdatagramsisdeterminedbytheremotewritingapplication.Iftheremotewriterisfrom

CoreDXDDSProgrammer’sGuide

176

aCoreDXDDSDomainParticipant,thentheremotepeercanbeconfiguredtolimitthesizeoftransmittedpackets.ThisconfigurationwillenabletransmissionoflargedatabetweentwopeerswithoutrequiringthetransporttoestablishalargeRXbuffer.

15.1.2.1.6 TXPacketSizeLimit

TheCoreDXDDSUDPTransporttransmitsinformationinUDPdatagrams.TheunderlyingUDPtransportmechanismsupportdatagramsizesupto64KB.Insomecases,itisbeneficialtolimitthesizeofdatagramputontothenetwork.Forexample,somenetworkdevicesfailtohandlelargedatagrams.The‘tx_max_packet_size’configurationparameterisusedtolimitthesizeofUDPdatagramproducedbytheCoreDXDDSUDPTransport.CoreDXDDSwillfragmentthedatamessageifitwillnotfitwithinthespecifiedmaximumsize.

15.1.2.1.7 SNDBUFandRCVBUF

TheUDPsocketsusedbytheCoreDXDDSUDPTransporthaveanOSconfiguredsendandreceivebuffer.ThisisconfigurablethroughanOperatingSystemprovidedAPI.Ingeneral,theOSprovideddefaultbuffersizesareappropriate;however,itispossibletooverridethesedefaultswiththe‘so_rcvbuf’and‘so_sndbuf’configurationparameters.Forfurtherinformationonthesebuffers,refertothedocumentationforyourOperatingSystemunderthetopicof‘setsockopt’andSO_RCVBUForSO_SNDBUF.

15.1.2.1.8 MulticastandUnicast

TheCoreDXDDSUDPTransportsupportstheuseofUnicastandMulticastdatagrams.CoreDXDDSwilluseMulticastwhenavailabletominimizethenumberofpacketswrittenonthenetwork.Ingeneral,thisisforallcommunicationsexceptfor:

• HeartbeatandACK/NACKmessages(RELIABILEReliability)• Retransmissionofdatapackets(RELIABLEReliability)• ContentfiltereddatawithWriter-sidefilteringenabled

IfMulticastisnotavailableordesirable,thenCoreDXDDScanbeconfiguredtouseonlyUnicasttransmissions.ThereareseveralconfigurationparametersavailabletotailortheuseofUnicastandMulticast.Insomecases,itmaybeusefultouseMulticastfor‘meta’(discovery)topics,butnotforusertopics.Insomecases,itisusefultotransmitmulticast,butnotreceiveit.

177

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Inordertoprovidefullflexibility,theCoreDXDDSUDPTransportprovidesthefollowingconfigurationparametersrelatedtoUnicastandMulticast:

Table15-1:UDPTransportConfigurationParameters

Parameter Description

multicast_address_v4 SpecifytheMULTICASTGROUPaddressusedforallmulticastcommunicationsoverIPv4.

multicast_address_v6 SpecifytheMULTICASTGROUPaddressusedforallmulticastcommunicationsoverIPv6.

multicast_ttl SpecifytheMULTICASTTTLvalue.Thisdefinesthenumberofhops(routers)thatmulticastpacketsshouldtraverse.

tx_meta_multicast EnablesthetransmissionofMETA(discovery)dataovermulticast.

tx_meta_unicast EnablesthetransmissionofMETA(discovery)dataoverunicast.

rx_user_multicast EnablesthereceptionofUSERdataovermulticast.

rx_user_unicast EnablesthereceptionofUSERdataoverunicast.

advertise_meta_multicast EnablestheadvertisementofourabilitytoreceiveMETAdataviamulticast.

advertise_user_multicast EnablestheadvertisementofourabilitytoreceiveUSERdataviamulticast.

15.1.2.1.9 Broadcast

Insomenetworkenvironments,Multicastisnotavailableordesirable.Inthesecases,itmaybeacceptabletouseBroadcastasanalternativetofacilitatedynamicdiscovery.TheCoreDXDDSUDPTransportcansupportthebroadcastofDomainParticipantdiscoveryinformation.Bysetting

CoreDXDDSProgrammer’sGuide

178

‘do_meta_broadcast’,theDomainParticipantDatamessagewillbebroadcastontothelocalnetworksegment.

Ifoperatingonahostornetworkthatdoesnotsupportmulticast,butdoessupportbroadcast,thenthefollowingconfigurationmaybeuseful:

advertise_meta_multicast = 0; advertise_user_multicast = 0; do_meta_broadcast = 1;

Thiswillprohibitremotepeersfromattemptingmulticastcommunication,butwillsupportdynamicdiscoveryviabroadcast.

15.1.2.1.10 Debug

The‘debug_flags’parameterenablesdebugoutputfromtheUDPtransport.Usefulvaluesare2(DATA_LOGGING)and64(TRANSPORT_LOGGING).Theflagscanbecombined.See<dds/dds.h>forthefullsetofLOGGINGflags.

15.1.2.2 UDPTransportEnvironmentVariablesCoreDXDDSprovidestheabilitytosetmanyoftheUDPtransportconfigurationitemsthroughenvironmentvariables.AllsettingsavailablethroughenvironmentvariablesisalsoavailablethroughtheTransportAPI.

IfanytransportenvironmentvariablesareusedtoconfiguretheUDPtransport,theTransport::get_env_config()APImustbecalledinordertoapplythoseenvironmentsettingstoatransport.

Table15-2:UDPTransportEnvironmentVariables

EnvironmentVariable Meaning Example

COREDX_IP_ADDR Setsthe‘interfeaces’parameter

ThisconfiguresthedefaultIPaddressusedbytheUDPtransport.Ifthisvalueisdefinedintheenvironment,thenthetransportwilluseonlytheinterfaceassociatedwiththespecifiedaddress.

Legacybehaviorpreserved:Settingthisenvironmentvariablewilldisabledynamicinterface

COREDX_IP_ADDR=192.168.1.5

179

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

EnvironmentVariable Meaning Example

detection(whichcanbere-enabledviatheTransportAPIifdesired).

COREDX_UDP_DEBUG Setsthedebug_flagsparameter. COREDX_UDP_DEBUG=64

COREDX_UDP_RX_BUFFER_SIZE Setstherx_init_buffer_sizeparameter.

COREDX_UDP_MAX_TX_SIZE Setsthetx_max_packet_sizeparameter.

COREDX_UDP_RCVBUF Setstheso_rcvbufparameter. COREDX_UDP_RCVBUF=1024

COREDX_UDP_SNDBUF Setstheso_sndbufparameter. COREDX_UDP_SNDBUF=1024

COREDX_USE_MULTICAST Setsthe‘advertise_user_multicast’and‘advertise_meta_multicast’parameters.

COREDX_USE_MULTICAST=1

COREDX_MULTICAST_TTL Setsthemulticast_ttlparameter. COREDX_MULTICAST_TTL=2

COREDX_UDP_IPV4 Setsthe‘use_ipv4’parameter. COREDX_UDP_IPV4=1

COREDX_UDP_IPV6 Setsthe‘use_ipv6’parameter COREDX_UDP_IPV6=1

15.1.2.3 TCPTransportAPITheTCPtransportprovidessupportforCoreDXDDStocommunicateusingTCPconnections.BecauseTCPisaconnectionorientedtransport,thereisnofacilityforMulticastorBroadcast.WithoutMulticastorBroadcast,theTCPtransportdoesnotprovideanyfacilitiesforfullyDynamicDiscovery.

ThecurrentversionoftheTCPtransportsupportsonlyIPv4.SupportforIPv6isplannedforasubsequentrelease.

ThespecificconfigurationparametersavailablewiththeTCPtransportaredescribedinthefollowingsections.

CoreDXDDSProgrammer’sGuide

180

15.1.2.3.1 ParticipantIndex

ParticipantIndexisanintegernumberthatbydefaultiscomputedautomaticallybytheRTPSimplementation.ItisusedtodistinguishDomainParticipantsonthesamehostandinthesameDomainfromoneanother.Insomecases,itishelpfultodirectlyconfigurethisvalueasitis*usedtocomputeunicastportnumbers.Itisanerrortoconfigure2ormoreDomainParticipantsonthesamehost,withinthesameDomain,suchthattheyhavethesameParticipantIndexvalue.

15.1.2.3.2 Interfaces

Thetransport,bydefault,willmakeuseofallavailableactivenetworkinterfaces.Ifyourmachinehasmultiplenetworkinterfaces,thismaygenerateunnecessarynetworktrafficonsomeofthosenetworks.Thetransportcanbeconfiguredtouseasubsetofavailableinterfaces.The‘interfaces’configurationparametercanbeconfiguredwithalistofinterfaceaddresses.Ifthelistisempty,thenCoreDXDDSwillquerytheoperatingsystemtoobtainalistofallavailableactiveinterfaces.

NOTE:WhenconfiguringastaticlistofinterfacesforCoreDXDDStouse,youmayalsowanttodisabledynamicinterfacedetection(below).

15.1.2.3.3 DynamicInterfaceDetection

OnOperatingSystemsthatsupportit,theCoreDXDDSTCPtransportcandetectchangestothenetworkinterfacesandadjustitsconfigurationinresponse.Forexample,iftheuserbringsupanewinterface,CoreDXDDSwilldiscoverandutilizethenewinterfaceonthefly.Thisdynamicinterfacedetectionisconfigurable.The‘dynamic_interfaces’configurationparameterisusedtoenableordisablethiscapability.

15.1.2.3.4 TXPacketSizeLimit

TheCoreDXDDSTCPTransporttransmitsinformationinRTPSMessages.Insomecases,itisbeneficialtolimitthesizeofRTPSMessagesputontothenetwork.Forexample,somenetworkdevicesfailtohandlelargepackets.The‘tx_max_packet_size’configurationparameterisusedtolimitthesizeofRTPSMessagesproducedbytheCoreDXDDSTCPTransport.CoreDXDDSwillfragmentthedatamessageintomultiplesmallermessages,ifitwillnotfitwithinthespecifiedmaximumsize.

181

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

15.1.2.3.5 Debug

The‘debug_flags’parameterenablesdebugoutputfromtheUDPtransport.Usefulvaluesare2(DATA_LOGGING)and64(TRANSPORT_LOGGING).Theflagscanbecombined.See<dds/dds.h>forthefullsetofLOGGINGflags.

15.1.2.4 TCPTransportEnvironmentVariablesCoreDXDDSprovidestheabilitytosettheTCPtransportconfigurationitemsthroughenvironmentvariables.TheTransport::get_env_config()APImustbecalledinordertoapplythoseenvironmentsettingstoatransport.

Table15-3:TCPTransportEnvironmentVariables

EnvironmentVariable Meaning Example

COREDX_IP_ADDR ThisconfiguresthedefaultIPaddressusedbytheTCPtransport.Ifthisvalueisdefinedintheenvironment,thenthetransportwilluseonlytheinterfaceassociatedwiththespecifiedaddress.

Legacybehaviorpreserved:Settingthisenvironmentvariablewilldisabledynamicinterfacedetection

COREDX_IP_ADDR=192.168.1.5

COREDX_TCP_DEBUG EnablesdebugoutputfromtheTCPtransport.Usefulvaluesare2(DATA_LOGGING)and64(TRANSPORT_LOGGING).Theflagscanbecombined.See<dds/dds.h>forthefullsetofLOGGINGflags.

COREDX_TCP_DEBUG=64

15.1.2.5 LMTTransportAPITheLMT(LocalMachineTransport)providessupportforoptimized‘onhost’communication.ThetransportenablesDomainParticipantsthatareco-locatedonthesamehosttocommunicatewithloweroverheadandlatenciesthanprovidedbythedefaultUDPtransport.

CoreDXDDSProgrammer’sGuide

182

TheLMTtransportiscurrentlyprovidedonasubsetofCoreDXDDSsupportedoperatingsystems.Foracurrentlistofsupportedoperatingsystems,pleasecontactTwinOaksComputingatsupport@twinoakscomputing.com.

NOTE:LMTisnotimplementedusingsharedmemory.Asaresult,thesafetyprovidedbyseparateprogramaddressspacesismaintained.

ThespecificconfigurationparametersavailablewiththeUDPtransportaredescribedinthefollowingsections.

15.1.2.5.1 SNDBUFandRCVBUFTheUDPsocketsusedbytheCoreDXDDSUDPTransporthaveanOSconfiguredsendandreceivebuffer.ThisisconfigurablethroughanOperatingSystemprovidedAPI.Ingeneral,theOSprovideddefaultbuffersizesareappropriate;however,itispossibletooverridethesedefaultswiththe‘so_rcvbuf’and‘so_sndbuf’configurationparameters.Forfurtherinformationonthesebuffers,refertothedocumentationforyourOperatingSystemunderthetopicof‘setsockopt’andSO_RCVBUForSO_SNDBUF.

15.1.2.5.2 TXPacketSizeLimit

Insomecases,itisbeneficialtolimitthesizeofpacketwrittenbythetransport.The‘max_tx_size’configurationparameterisusedtolimitthesizeofpacketproducedbytheCoreDXDDSLMTTransport.CoreDXDDSwillfragmentthedatamessageifitwillnotfitwithinthespecifiedmaximumsize.Refertotheblahsectionforadditionalinformationonbuffersizingandfragmentation.

15.1.2.5.3 RXBufferSize

TheLMTtransportmaintainsbufferstohandleincomingdatapackets.Inordertopreservememory,thesizeandbehaviorofthereceivebufferisconfigurable.Bydefault,thereceivebufferbeginssmallandcangrowdynamicallyasrequiredtohandletheincomingdata.TheinitialsizeofthebufferissetatinitializationtobejustlargeenoughtohandleanRTPSMessageHeader.Themaximumsizeofthebufferislimitedbythe‘max_rx_buf_size’configurationparameter.

183

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

15.1.2.5.4 Debug

The‘debug_flags’parameterenablesdebugoutputfromtheLMTtransport.Usefulvaluesare2(DATA_LOGGING)and64(TRANSPORT_LOGGING).Theflagscanbecombined.See<dds/dds.h>forthefullsetofLOGGINGflags.

15.1.2.6 LMTTransportEnvironmentVariablesCoreDXDDSprovidestheabilitytosetmanyoftheLMTtransportconfigurationitemsthroughenvironmentvariables.AllsettingsavailablethroughenvironmentvariablesisalsoavailablethroughtheTransportAPI.

IfanytransportenvironmentvariablesareusedtoconfiguretheLMTtransport,theTransport::get_env_config()APImustbecalledinordertoapplythoseenvironmentsettingstoatransport.

Table15-4:LMTTransportEnvironmentVariables

EnvironmentVariable Meaning Example

COREDX_LMT_DEBUG Setsthe‘debug_flags’parameter.

COREDX_LMT_DEBUG=64

COREDX_LMT_RCVBUF Setsthe‘rcvbuf’parameter.

COREDX_LMT_SNDBUF Setsthe‘sndbuf’parameter.

COREDX_LMT_MAX_TX_SIZE Setsthe‘max_tx_size’parameter.

COREDX_LMT_MAX_RX_BUF_SIZE Setsthe‘max_rx_buf_size’parameter.

15.1.2.7 UDSTransportTheUDStransportprovidesthefacilityforserialorotherstreambasedtransports.UDSissupportedbyahelperprogramthatinitializestheserialport,andprovidesamulti-participantaccesstothesinglesharedresource.Becauseofthediversenatureofserialandotherrelatedhardwaredevices,pleasecontactTwinOaksComputingforassistanceinadaptingthistransporttechnologytoyourplatform.

CoreDXDDSProgrammer’sGuide

184

185

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter16 CoreDXDDSDiscovery

16.1 OverviewofCoreDXDDSDiscoveryTheautomaticdiscoveryprocessisoneofthemorepowerfulandusefulfeaturesofCoreDXDDS.AutomaticdiscoveryofentitiesallowsCoreDXDDSapplicationstopublishandsubscribetodatawithoutneedingtoconfiguretheendpoint(s)theytalkto.Whethertheseendpointsareonthesamemachine,oracrosstheroom,CoreDXDDSapplicationsdonotneedanyknowledgeoftheotherapplicationstheywillbecommunicatingwith.

TheStandard(peer-to-peer,dynamic)DiscoveryprocessinCoreDXDDSisencapsulatedineveryCoreDXDDSapplication,anddoesnotrequireanyadditionaldaemonsorservices.EachCoreDXDDSapplicationperformsthediscoveryprocess,includingannouncingthepresenceofitsDDSEntities,listeningforotherDDSEntities,andlookingformatchesbetweenitsownDDSEntitiesandthosediscovered.ThestandarddiscoverymechanismisinteroperablebetweenDDSimplementations.

Theautomaticdiscoveryprocessincludesthefollowingsteps:

1. Discovering DomainParticipants 2. Discovering DataReaders and DataWriters within

those discovered Participants 3. Matching those discovered DataReaders and

DataWriters with local DataReaders and DataWriters

UsingtheCoreDXDDSSecureextensionsenhancesthisautomaticdiscoveryprocess.Formoreinformation,refertotheCoreDXDDSSecureProgrammer’sGuide.

DespitethemanybenefitsoftheStandardDiscoverymechanism,itdoeshavesomedrawbacksforcertainsystemarchitectures.Forexample,wheresecurityrequirementspreventdynamicdiscovery,orwherescalabilityrequirementsneedanalternativesolutiontothestandardpeer-to-peerdiscovery.CoreDXDDSprovidesseveralalternativesforconfiguringthediscoveryprocess.

CoreDXDDSProgrammer’sGuide

186

16.2 DiscoveringDomainParticipantsThefirststepintheautomaticdiscoveryprocessistodiscoverremoteDomainParticipants.EachDomainParticipantwillperiodicallyannounceitsexistence(includinghowitcanbereacheddirectlytolearnaboutcontainingDataReaderandDataWriterEntities)bywritingaSPDPdiscoveredParticipantDatamessagetothemulticastaddressspecifiedbytheDDSstandards.EachDomainParticipantwillalsolistenonthatsamemulticastaddresstolearnaboutotherDomainParticipants.

AfteraDomainParticipanthasbeendiscovered,itwillbeconsidered‘alive’aslongasitsSPDPdiscoveredParticipantDatamessagescontinuetobereceived.IfenoughtimeexpireswithoutreceivingaSPDPdiscoveredParticipantDatamessagefromaDomainParticipant,thatDomainParticipantisnolongerconsidered‘alive’.

16.2.1 ConfiguringParticipantDiscoveryTheDDSstandardsspecifydefaultdurationsforhowoftenSPDPdiscoveredParticipantDatamessagesshouldbesent,andhowmuchtimeshouldexpirebeforeaDomainParticipantshouldbeconsidered‘notalive’.

Whilethesedefaultdurationsworkwellformostnetworkenvironments,theymaynotworkforallenvironments.Forexample,networkswithverylonglatencies,orextremelybandwidthconstrainednetworksmayneedtotailorthetimingofdiscoverymessages.

CoreDXDDSallowstheapplicationtoconfiguretimingofDomainParticipantdiscoverybyusingtheCoreDX_DiscoveryQosPolicy,asdescribedbelow.

QoSPolicy DefaultValue Description

CoreDX_DiscoveryQosPolicy

dpd_push_period(duration_t) 5seconds ConfiguretheamountoftimebetweensendingofSPDPdiscoveredParticipantDatamessages.

dpd_lease_duration(duration_t)

120seconds ConfiguretheamountoftimethecanexpirewithoutreceivingaSPDPdiscoveredParticipantData

187

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

QoSPolicy DefaultValue Description

messagebeforeweconsideraremoteParticipantbe‘notalive’.

16.3 MatchingDataReadersandDataWritersThematchingofDataReadersandDataWritersisasophisticatedprocessthatensuresthesubscribersofdataarematchedappropriatelywithproducersofdata.Thiscarefulmatchinghelpstoreduceprogrammingerrors,inadditiontoreducingunnecessarystorageandnetworkcommunicationsusage.

ThefollowingthreeconditionsarecheckedbetweenDataReadersandDataWriters,andallmustbemetinordertocreateamatch:

1. The Topic Names must match

ThenameusedwhencreatingaToipcwithDomainParticipant::create_topic()iscommunicatedtopeerDomainParticipantsduringdiscovery.ThenameoftheTopicusedbyaDataReadermustmatchthenameoftheTopicusedbyaDataWriter.

2. The Type Names (and type definition, if available) must match

ThenameusedwhenregisteringadatatypewithTypeSupport::register_type()iscommunicatedtopeerDomainParticipantsduringdiscovery.ThenameoftheregisteredtypeassociatedwiththeTopicusedbyaDataReadermustmatchthenameoftheregisteredtypeassociatedwiththeTopicusedbyaDataWriter.

Furthertypecheckingisperformedwhenthetypedefinitionisavailable.Thetypedefinitionisencodedforuseduringdiscoveryinoneoftwoways:typecodeortypeobject.ThesetypedefinitionsprovidemoreaccurateinformationaboutthedatatypeactuallybeingpublishedbyDataWritersandexpectedtobereceivedbyDataReaders.UsingtypecodesortypeopjectsinEntitymatchingprovidesanadditionalleveloftypesafety.

CoreDXDDSProgrammer’sGuide

188

Bydefault,CoreDXDDSv4applicationsexchangetypeobjectinformationduringdiscovery.[CoreDXDDSv3applicationsexchangetypecodeinformationduringdiscovery.]MoreinformationontypecodeandtypeobjectandtheirconfigurationcanbefoundintheCoreDXDDSTypeSystemProgrammer’sGuide.

3. The QoS policies must be compatible

TheQoSpolicydefinedwithDataReadersandDataWritersiscommunicatedtopeerDomainParticipantsduringdiscovery.OncetheTopicsandTypeshavebeenverifiedasmatchingbetweenaDataReaderandDataWriter,theQoSpoliciesarecheckedforcompatibility.RefertosectionPart3:12.1QoSCompatibilityforadditionalinformationonQoScompatibilitymatching.

16.3.1 ConfiguringEntityMatchingTypecodeandtypeobjectarenotrequiredforDDSdiscovery.Bydefault,CoreDXDDSwillsendandusetypeobjectforEntitymatching,buttheapplicationcanconfigurethisbehavior.TheRTPSReaderandRTPSWriterQoSpolicieswillcontrolweathertypecodeand/ortypeobject(iftheyareavailable)willbeusedforentitymatching.Optionstothedatatypecompiler(-i)defineiftypecode,typeobject,ornotypeencodingswillbegenerated,andavailable.

Further,whenmatchingtypesthatarecompatible,butnotequivalent,CoreDXDDSwill,bydefult,coerseamatch.ThisbehaviorisconfigurableusingtheDataReaderQoSpolicy.

QoSPolicy DefaultValue Description

CoreDX_RTPSReaderQosPolicy

send_typecode(unsignedchar)

1(true) ConfigurethisDataReadertosend(ornotsend)thetypecodefortheTopicitissubscribingto.

CoreDX_RTPSWriterQosPolicy

send_typecode(unsignedchar)

1(true) ConfigurethisDataWritertosend(ornotsend)thetypecodefortheTopicitispublishing.

Formatted: Font:Italic

Deleted: QoSCompatibility

189

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

QoSPolicy DefaultValue Description

DataReaderQoSPolicy

type_consistency.kind

ALLOW_TYPE_COERCION

Possiblevalues:DISALLOW_TYPE_COERCION, ALLOW_TYPE_ COERCION.

Thereareseveralpossiblereasonsanapplicationmayneedtodisablethesendingoftypecodes(andtherefore,removingthecapabilitytousethemforEntitymatchingduringdiscovery).

BecausetypeencodingwasnotwellspecifiedintheearlierDDSstandards,itispossiblethatDDSimplementationsarenotinteroperableinmatchingallpossibletypecodes.

Inaddition,typecodesandtypeobjectsrequiresystemresources:generatedcodeusesadditionalstaticorFLASHmemory,sendingandreceivingtypecodesusesadditionaldynamicorRAMmemoryandnetworkresources.Thisisespeciallytrueoflargetypedefinitions.Inextremecases,thetypecodemaybetoolargetosendovertheavailabletransport(thisisespeciallytrueforlowbandwidthtransports).

16.4 StaticDiscoveryTheCoreDXDDSmiddlewaresupportsdynamicdiscoverybydefault.ThisallowsDomainParticipantstodiscoverotherParticipantsinthesamedomain.OnceDomainParticipantsdiscovereachother,thenthecontainedDataReadersandWritersaredynamicallymatched.

ThestandarddynamicdiscoveryprotocolisbasedonUDPMULTICAST,andworkseffectivelyinalocalareanetwork,andcanbeconfiguredtoworkthroughroutersandothernetworkingdevices.However,therearesome

CoreDXDDSProgrammer’sGuide

190

situationsinwhichUDPMULTICASTisnotdesirableorpossible,orwhereDynamicDiscoveryisnotsuitablefortheapplication.

Inordertoaddressthesesituations,CoreDXDDSprovidesQoSsupportfordefiningremotepeerDomainParticipants.AnextensionQoSpolicyisaddedtotheDomainParticipantQoSpolicies.Thispolicy,peer_participants,identifiesalistofremoteDomainParticipantswithwhichthisparticipantshouldcommunicate.Thisavoidstheinitialparticipantdiscoveryprocess,andinitiatesdirectcommunicationbetweentheidentifiedparticipants.

ThisQoSpolicycanbeupdatedonthefly,aftertheDomainParticipantisenabled,andcansupportanapplicationcontrolleddiscoverymechanism.Table16-1showsaClanguageexampleofsettingthe‘peer_participant’QoSpolicy.

Table16-1:CodeExampleofpeer_participantsQoS

Examplecodetopre-definePeerParticipants

DDS_DomainParticipant dp; DDS_ReturnCode_t retval; DDS_DomainParticipantQos dp_qos; CoreDX_ParticipantLocator pl; DDS_DomainParticipantFactory_get_default_participant_qos(&dp_qos); /* add two 'a-priori' configured peer locators */ /* two different participant id's and two different IP addrs */ pl.participant_id = 0; pl.participant_locator.kind = COREDX_UDPV4_LOCATOR_KIND_QOS; memset(pl.participant_locator.addr, 0, 16); pl.participant_locator.addr[12] = 192; pl.participant_locator.addr[13] = 168; pl.participant_locator.addr[14] = 1; pl.participant_locator.addr[15] = 12; seq_add(&dp_qos.peer_participants.value, &pl); pl.participant_id = 1; pl.participant_locator.kind = COREDX_UDPV4_LOCATOR_KIND_QOS; memset(pl.participant_locator.addr, 0, 16); pl.participant_locator.addr[12] = 192; pl.participant_locator.addr[13] = 168; pl.participant_locator.addr[14] = 1; pl.participant_locator.addr[15] = 22; seq_add(&dp_qos.peer_participants.value, &pl); dp = DDS_DomainParticipantFactory_create_participant( 0,

191

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

&dp_qos, NULL, 0);

16.5 CentralizedDiscovery

16.5.1 OverviewTheStandard(peer-to-peer)DiscoveryprocessinCoreDXDDSisencapsulatedineveryCoreDXDDSapplication,anddoesnotrequireanyadditionaldaemonsorservices.EachCoreDXDDSapplicationperformsthediscoveryprocess,includingannouncingthepresenceofitsDDSEntities,listeningforotherDDSEntities,andlookingformatchesbetweenitsownDDSEntitiesandthosediscovered.ThestandarddiscoverymechanismisinteroperablebetweenDDSimplementations.

ThisStandardDiscoveryisdepictedinthebelowdiagram.

Figure17:StandardDiscovery(peer-to-peer)architecture

DespitethemanybenefitsoftheStandardDiscoverymechanism,itdoeshavesomedrawbacksforcertainsystemarchitectures.Inparticular,StandardDiscoverymaynotscalewelltolargeDDSdomains.InDDSdomainswithlargenumbersofDDSentities(Participants,ReadersorWriters),theStandardDiscoverymechanismcanrequirelargeamountsofmemoryaseveryParticipantdiscoversallotherentitiesinthesystem.In

CoreDXDDSProgrammer’sGuide

192

manycase,this‘worldview’oftheDDSdomainiswasteful.Often,aParticipantisrequiredtocommunicatewithonlyasmallsub-setoftheentireDDSnetwork.

ToaddressthescalabilityissuesofStandardDiscovery,CoreDXDDSsupportsaspecializeddiscoverymechanismcalledCentralizedDiscovery.CoreDXCentralizedDiscoveryperformstheworkofdiscoveringallDDSEntitiesandappropriatelycommunicatingthoseentitiestoparticipantsbasedon‘needtoknow’.TheCentralizedDiscoverymechanismcanscaletoverylargeDDSdomains,withouttheexplosionofmemoryallocationfoundinStandardDiscovery.

Further,CentralizedDiscoveryisdesignedtobeinteroperablewithStandardDiscovery.ThismeansthataDDSdomainmaycombinebothdiscoverymechanismsasnecessary:someDomainParticipantscanuseStandardDiscoverywhileothersuseCentralizedDiscovery.

ThisCentralizedDiscoveryisdepictedinthebelowdiagram.

Figure18:CentralizedDiscoveryarchitecture

16.5.2 MemoryUtilizationandScalabilityWithStandardDiscovery,eachDomainParticipantlearnsandrememberseveryactiveDomainParticipant,DataReader,andDataWriterintheDDSDomain.AsthenumberofDDSEntitiesintheDomaingrows,sodoestheamountofdiscoveryinformationstoredineachDomainParticipant.

193

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

ForsystemsthatcontainmanyDDSEntities,itmaybedesirabletoreducethenumberofcopiesofthismaintaineddiscoveryinformation.ThisisonebenefitofCentralizedDiscovery.ThediscoveryinformationaboutallDDSEntitiesinaDDSDomainisstoredinacentralizedlocation,reducingtheoverallmemoryutilizationinthesystem.

TheCentralizedDiscoveryDaemondeterminesthepotentialReader/WritermatchesforallitsconnectedDomainParticipants.DomainParticipantslearnonlyaboutpotentialmatchesfromtheCentralizedDiscoveryDaemon.

ACoreDXCentralizedDiscoveryDaemonmustresideonthesamemachineasDomainParticipantsthatareconfiguredtouseCentralizedDiscovery.Therefore,thegreatestbenefitsformemoryreductionareseenwhen:

1. TherearemanyDDSEntitiesononemachinethatcanuseCentralizedDiscovery,and

2. ForeachDomainParticipant,asmallpercentageoftheDDSEntitiesintheDDSdomainmatchwithitsownDDSEntities.

Notethattheselectionof‘discovery’mechanismaffectsonlytheexchangeofdiscoveryinformation–applicationdataisnotaffected.Applicationdataisalwaysexchangedpeer-to-peer,evenwhenusingCentralizedDiscovery.

16.5.3 NetworkUtilizationandDiscoveryWithStandardDiscovery,eachDomainParticipantcommunicateswitheveryactiveDomainParticipantintheDDSDomain.AsthenumberofDDSDomainParticipantsintheDomaingrows,sodoestheamountofnetworktrafficgeneratedtocommunicatewitheachpeerDomainParticipant.

ForsystemsthatcontainmanyDomainParticipants,andatleastsomeoftheseDomainParticipantsareco-locatedonthesamecomputer,itmaybedesirabletoreducethenumbermessagesgeneratedonthenetwork.ThisisanadditionalbenefitofCentralizedDiscovery.TheDomainParticipantsco-locatedonacomputerwillcommunicatewiththeirlocationCentralizedDiscoveryDaemon,andonlytheCentralizedDiscoveryDaemonwillcommunicateoff-box,reducingtheamountofdiscoverynetworktraffic.

16.5.4 ConfiguringCentralizedDiscoveryConfiguringCoreDXDDSdiscoveryhappensattheDomainParticipantusingaQoSpolicy.ADomainParticipantcanbeconfiguredtouseacertaindiscoverymechanismatcreationtimethroughaQoSpolicy.

CoreDXDDSProgrammer’sGuide

194

Bydefault,CoreDXDDSusesStandardDiscovery(PEER).TouseCentralizedDiscovery,changetheDomainParticipantCoreDX_Discovery_Qos_Policytospecifycentralizeddiscovery.TheDomainParticipantQoSpolicyforconfiguringdiscovery(andbuilt-inentities)isdescribedbelow.

CoreDXCentralizedDiscoveryiscompliantwiththeOMG’sRTPSWireProtocolstandard,andisthereforeinteroperablewithotherDDSimplementations.SinceDomainParticipantsusingCentralizedDiscoverycancommunicationwithDomainParticipantsusingstandarddiscovery,amixofdiscoverytypescanbeconfiguredinthesameDDSnetwork.

QoSPolicy DefaultValue Description

CoreDX_DiscoveryQosPolicy

discovery_kind(DiscoveryQosPolicyDiscoveryKind)

DDS_PEER_DISCOVERY_QOS

ConfigurethisDomainParticipanttousestandard(PEER)discoveryorcentralizeddiscovery.

Possiblevaluesare:DDS_PEER_DISCOVERY_QOSandDDS_CENTRAL_DISCOVERY_QOS

16.5.5 DeployingCentralizedDiscoveryACoreDXCentralizedDiscoveryDaemonmustbedeployedoneachcomputerthatishostingaDomainParticipantconfiguredtouseCentralizedDiscovery.ThereshouldbeonlyoneCoreDXCentralizedDiscoveryDaemonrunningonacomputer.ComputersthatarenothostingDomainParticipantsconfiguredtouseCentralizedDiscoverydonotneedaCoreDXCentralizedDiscoveryDaemon.

AnexampledeploymentusingCentralizedDiscoveryisshownbelow.

195

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Figure19:ExampleCentralizedDiscoverydeployment

16.6 WaitforDiscoveryTheautomaticanddynamicdiscoveryprocessisdefinedbytheDDSstandardsandemployedbyCoreDXDDS.Whilethediscoveryalgorithmsareefficient,thedynamicnatureofdiscoverymeansitisimpossibletodeterminetheamountoftimerequiredfordiscoverytocomplete,evenwhenallentitiesarelocatedwithinoneDomainParticipant.

Forexample,consideranapplicationwiththefollowingexecutionflow(andnopausesorgapsbetweensteps):

1. Create DomainParticipant 2. Register data types and create Topics 3. Create Subscribers and DataReaders 4. Create Publishers and DataWriters 5. Write data

DiscoveryandmatchingoftheselocalDataReadersandDataWritersmaynotcompletebeforetheapplicationwritesdata.Ifthediscoveryandmatchingisnotyetcomplete,datawillnotbereceivedbytheDataReaders(sincetheyarenotyetknowntoexistbytheDataWriter).

Toaddressthisproblem,CoreDXDDSprovidesanAPIonDomainParticipantstowaitforbuilt-inacknowledgements:

DomainParticipant::builtin_wait_for_acknowledgments( Duration_t *max_wait)

CoreDXDDSProgrammer’sGuide

196

WhileaDomainParticipantconfiguredtousedynamicdiscoveryhasnowaytoknowhowmany,ifanyremoteDDSEntitiesmaybediscovered,thisAPIwillblocktheapplicationuntilallDataReadersandDataWriterswithinknownDomainParticipantshavebeendiscoveredandmatchedasappropriate(oruntilthemax_waitdurationhasexpired).

16.7 DiscoveryandDeterministicMachines

CoreDXDDSdiscoveryadherestotheDDSstandardsandisinteroperablewithotherDDSimplementations.PartofthisinteroperablediscoveryprocessistheassignmentofGloballyUniqueIdentifiers(GUIDs)toRTPSEntitiesthatareadvertisedandmaybediscoveredbyotherRTPSEntities,includingParticipants,Readers,andWriters.

TheParticipantGUIDisimportantfordynamicdiscovery.EachParticipantwillgenerateauniqueGUIDandincludeitinthediscoverymessagesitpublishes.Whenanewdiscoveryadvertisementmessageisreceived,aParticipantcanusetheGUIDtodetermineifthisisnewParticipant,oronethatithasalreadydiscovered.NewlydiscoveredparticipantswillparticipateinadditionaldataexchangetoshareQoSpolicysettingsandinformationaboutexistingDataReadersandDataWriters.

Thediscoveryprocessallowsanapplication’sParticipanttogoaway(bynormalorabnormalexit,ormachinerestart),restart,andseamlesslyre-jointheexistingDDSnetworkasanewParticipant.Thisworksonlyiftherestartingapplication’sParticipantsareassignedauniqueGUID.

Accordingtothestandard,theParticipantGUIDiscreatedusingthefollowingdata:

• IPv4addressofthecomputerhostingtheParticipant • ProcessIDofthisParticipant’sapplication • One-upcounterforeachParticipantwithinthisapplication • EntityKind(fixedidentifierforParticipant)

Formanycomputersystems,thisalgorithmdoesgenerateuniqueGUID’sforParticipants,evenaftermachinerestarts.However,applicationsrunningondeterministicOperatingSystems,suchasVxWorks,mayalwaysstartwiththesameprocessID,resultinginaParticipantalwayshavingthesameGUID.ThiscancauseaproblemwhenaParticipantattemptstore-joinDDScommunicationsusingthesameGUIDithadpreviously.RemoteParticipantsontheDDSnetworkwillconsiderthisParticipantanalready-

197

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

discoveredParticipant,andwillnotparticipateinthenecessarydataexchangetoshareQoSpolicysettingsandexistingDataReadersandDataWriters.

Toaddressthisproblemwithdeterministicsystems,CoreDXDDSprovidesanadditionaldiscoveryQoSpolicysettingforapplicationstousetheirownalgorithmtosettheProcessIDportionoftheGUID.Whenused,thisshouldbeanumberthatuniquelyidentifiesanapplicationonacomputer,andwillnotbethesameafteramachinerestart.Thismightbeaone-upcounterthatiswrittentopersistentstorage(disk,writableFLASHmemory)oranotherapplicationdefinedalgorithm.

QoSPolicy DefaultValue Description

CoreDX_DiscoveryQosPolicy

guid_pid(DDS_BUILTIN_TOPIC_KEY_TYPE_NATIVE)

0 Avalueof‘0’willusethedefault:theapplicationprocessID(PID).Valuesotherthan‘0’willbeusedinplaceofthePIDinconstructingtheGUID.

199

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

200

Chapter17 ConfiguringReliabilityProtocol

17.1 ReliabilityProtocolTheCoreDXDDSReliabilityprotocoladdressesdroppedpackets,outofordersamples,communicationdisconnects,andapplicationre-startstoensuredeliveryofpublisheddatatotheintendedrecipients.ThisprotocolissupportedbythestandardizedRTPSprotocolandtheDataReaderandDataWriterDataCaches(seeChapter10.5forafulldiscussionontheDataCaches).

Thisreliabilityprotocolislight-weightandminimizeslatency.Droppedpacketsarequicklydetectedandrepaired.CoreDXDDSprovidestunableparametersforconfiguringthereliabilityprotocoltoallowtheapplicationdevelopertoachieveanoptimalbalanceofoverheadandtimelydataretransmission.

17.1.1 CacheManagementThereliableprotocoleffectsmorethanthehandshakingbetweenDataWritersandDataReaders.TheDataCachealsoplaysanimportantroleinreliablecommunications.

OntheDataWriter,theDataCachecontainssamplesthathavenotbeenacknowledgedbyallreliablesubscriptions.[DatamaybekeptlongerbasedontheDurabilityQoSconfiguration.]ThedatacachesizeiscontrolledbytheHistoryandtheResourceLimitsQoSpolicies.Ifthedatacachebecomesfull,theHistoryQoSpolicykindcomesintoplay.WithaHistorykindofKEEP_ALL,thewrite()callwillblockuntilthereisspace,oruntilthemax_blocking_timehaselapsed.WithaHistorykindofKEEP_LAST,theoldestsamplewillberemovedfromthecachetomakeroomforanewsample.

OntheDataReader,theDataCachecontainssamplesinorder,withrespecttothesourceDataWriter.Ifsamplesarelost,thedatacachemaycontainoutofordersamples(thosesamplesthatarereceivedaresavedwhilewaitingforthelostsample(s)toberetransmittedandreceived).Thesesamplesarestoredina“forwardcache”andarenotavailabletotheapplicationuntilallmissingsamplesarereceived.Thisdesignminimizesretransmissionsofdatasamples,whileensuringtheapplicationreceivesonlyinorderdatasamples.TheDataReaderdatacachesizeiscontrolledby

201

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

theHistoryandtheResourceLimitsQoSpolicies.Ifthedatacachebecomesfull,theHistoryQoSpolicykindcomesintoplay.WithaHistorykindofKEEP_ALL,theDataReaderwilldropnewincomingsamples,sendingaNACKtotheDataWriter,andforcingtheDataWritertosaveandre-transmitthesamples.WithaHistorykindofKEEP_LAST,theoldestsamplewillberemovedfromthecachetomakeroomforanewsample.

17.1.2 Heartbeats,ACKs,andNACKsThereliabilityprotocolreliesonHeartbeatsfromtheDataWriterandACK/NACKresponsesfromtheDataReader.HeartbeatmessagestelltheDataReadersthedatathatiscurrentlyavailable(thathasbeensent)attheDataWriter.PositiveACKandnegativeNACKResponsesaresentinresponsetoaHeartbeatandconfirmtheDataReaderhasreceivedoneormoresamples,andpossiblyrequestsoneormoresamplestoberetransmitted.

Figure17-1showsasimpleexampleofthenetworktraffic(includingHeartbeatandACKResponses)whentherearenodroppedsamples.NoticethatHeartbeatscanbesentincombinationwithdatasamples,reducingnetworkoverhead.

Figure17-1:ExampleDDSUsage

Inthisexample,theDataReadersendsanACKinresponsetoeachofthe2HeartbeatsreceivedfromtheDataWriter.InthefirstACKresponse,theDataReaderconfirmsreceiptofallavailablesamplesuptosample#3.Inthe

CoreDXDDSProgrammer’sGuide

202

secondACKresponse,theDataReaderconfirmsreceiptofallavailablesamplesuptosample#6.

Figure17-2showsasimilarexample,exceptonedatasamplehasbeenlost,andmustberetransmitted.

Figure17-2:ExampleDDSUsage

Inthisexample,theDataReadersendsanACK/NACKinresponsetothefirstHeartbeatfromtheDataWriter.TheDataReadercanacknowledgesamples#1and#3,butnotsample#2.WhentheDataWriterreceivestheNACK,itwillretransmitsample#2,sendingitdirectlytothisDataReaderwhoneedsit.InresponsetothenextHeartbeatfromtheDataWriter,theDataReadercannowacknowledgealldatasamplesthrough#6.

17.1.3 PeriodicData,ReliabilityProtocol,andDataCacheConfiguration

Forapplicationsthatpublishperiodicdata(dataiswrittenataknownfrequency)withReliablity.kind=RELIABLE,considerationshouldbegiventotheDataWritercachesizewithrespecttothefrequencyofwrites,frequencyofHeartbeats,andACK/NACKresonsedelay.ThedurationbetweenHeartbeats,alongwiththeACK/NACKresponsedelayprovidetheminimumamountoftimethatwillelapsebeforesentsamplesmaybeacknowledgedbyamatchedDataReader,allowingtheDataWritertopotentiallyremovethosesamplesfromit’scache.

Considetheexample,withaDataWriterconfiguredwiththeQoS:

203

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

• Reliability.kind = DDS_RELIABLE_RELIABILITY_QOS

• History.kind = DDS_KEEP_ALL_HISTORY_QOS • Resource_Limits.max_samples = 2

ThefollowingdiagramdepictsatimelineandtheDataWritercache:

Notethetimebetweenwhenthefirstsampesarewrittenbythewritingapplicationandthetimethosesamplesarepotentiallyacknowledgedbythereadingapplication.TheDataWritercacheshouldbesizedtoallowforthenumberofwrites()thatwilloccurduringthattimeperiod,ataminimum.

17.1.4 UnresponsiveDataReadersDataReadersthatdonotrespondtoHeartbeatswithACK/NACKmessagesinatimelymannerposeauniquechallengetothestandardizedDDSReliabilityprotocol.ADataWriterwithcertainQoSpolicysettingswillkeepeachpublishedsampleinitsdatacacheuntilitisacknowledgedbyallmatchedReliableDataReaders.IfaDataReaderbecomesunresponsive(thatis,theDataWriterisnolongerreceivingACK/NACKmessagesfromthisDataReader),theDataWriterisunabletopurgesamplesfromitscache.Aftersomeperiodoftime,thedatacachemaybecomefull,oravailablememorywillbeusedtostoretheseun-acknowledgedsamples.Atthistimetheapplicationmaybeunabletowriteadditionaldata(exactbehaviorwilldependonotherQoSpolicyconfiguration),andtheother,responsive

CoreDXDDSProgrammer’sGuide

204

DataReaderswillnotreceiveanyadditionaldata,allbecauseof1unresponsiveDataReader.

Toaddressthischallenge,CoreDXDDSwilldegradeunresponsiveDataReaderstoaReliabilityconfigurationthatnotquiteReliable.TheDataWriterwillcontinuetosendHeartbeatstothisDataReader(inthehopethatitwilleventuallyrespondwithACK/NACKmessages),butwillnolongerexpect(orwaitfor)samplestobeacknowledgedbythisDataReader.Intheaboveexample,theDataWriterwillremovesamplesfromitsdatacacheoncetheyareacknowledgedbyallresponsiveDataReaders,allowingdatacommunicationstocontinuewithoutinterruption.[NotethattheunresponsiveDataReadermaymisssamples.]

WhenaDataReaderismarkedunresponsiveisconfigurablebytheapplicationthroughtheack_deadlineparameter(describedbelow).

17.2 ReliabilityQoSConfigurationSomeapplicationsneedtheabilitytotailorthereliabilityprotocoltoachieveanoptimalbalanceofoverheadandtimelydataretransmission.

CoreDXDDSprovidesadditionalQoSpoliciestoallowtailoringoftheRELIABLEhandshakingprotocol:theDataWriter_RTPS_WriterQoSPolicyandtheDataReader_RTPS_ReaderQoSPolicy.TheseQoSpoliciesallowtheapplicationtotailorwhenandhowfrequentlyCoreDXDDSsendsheartbeats,NACKs,andrelatedresponses.ConfiguringtheseitemscanbalancelatencyandoverheadinRELIABLEcommunications,andhelpavoidpacketstorms.

TheseadditionalQoSpoliciesaredescribedbelow.

Table17-1:CoreDXDDSRTPS_ProtocolQoSPolicy

QoSPolicy DefaultValue

Description

DataWriter_RTPSWriterQoSPolicy

heartbeat_period(Duration_t) 2ms ThedurationbetweenHeartbeatssentbytheDataWriter.

205

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

QoSPolicy DefaultValue

Description

nack_response_delay(Duration_t) 1us ThedelaybetweenthereceiptofaNACKResponseandtheDataWriter’sretransmissionofdata.

nack_suppress_delay(Duration_t) 0ns NotyetusedbyCoreDXDDS

ack_deadline(Duration_t) INFINITE TheamountoftimetheDataWritershouldwaitforanACK/NACKmessagefromaDataReaderbeforeitisconsideredunresponsive.

DataReader_RTPSReaderQoSPolicy

heartbeat_response_delay(Duration_t)

500us ThedelaybetweenthereceiptofaHeartbeatandtheDataReader’sACK/NACKResponse.

send_initial_nack 1(true) ThissettingisapplicableonlytoReliableDataReaders.Whensettonon-zero(true),theDataReaderwillsenda“NACK”messagetoeachnewlydiscoveredDataWriter,jumpstartingthehandshakingprocesstoreceiveanydatatheDataWriterhastopublish.Onepossiblereasontodisablethis‘jumpstart’,isperformance:withlotsofDataReadersmatchingwithoneDataWriteratthesametime.

CoreDX_DiscoveryQosPolicy

heartbeat_period(Duration_t) 10ms Forbuilt-inwriters,thedelaybetweenthereceiptofaNACKResponseandtheDataWriter’sretransmissionofdata.

CoreDXDDSProgrammer’sGuide

206

QoSPolicy DefaultValue

Description

nack_response_delay(Duration_t) 1us Forbuilt-inwriters,thedelaybetweenthereceiptofaNACKResponseandtheDataWriter’sretransmissionofdata.

nack_suppress_delay(Duration_t) 0sec NoyetusedbyCoreDXDDS

heartbeat_response_delay(Duration_t)

0sec Forbuilt-inreaders,thedelaybetweenthereceiptofaHeartbeatandtheDataReader’sACK/NACKResponse.

send_initial_nack 1(true) Whensettonon-zero(true),thebuilt-inDataReaderswillsenda“NACK”messagetoeachnewlydiscoveredbuilt-inDataWriter,jumpstartingthehandshakingprocesstoreceiveanydiscoverydatatheDataWriterhastopublish.Thismayneedtobedisabledtosupportinteroperability(inourtestingtodate,oneDDSvendordidnotsupportthisoption).

207

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter18 DynamicTypes

18.1 OverviewTheoriginalDDSstandardswaredesignedaroundtheassumptionthattypesassociatedwithTopicsareknownatcompiletime.Whilethisarchitectureprovidesbettercommunicationperformance(throughputandlatency)andtypesafety,staticdatatypingmakesitdifficulttodynamicallydefineTopicsatruntime.

TheadditionofDynamicTypestotheCoreDXDDSbaselineallowsgreaterflexibilitytoapplicationdevelopers.Developerscandefinetheirdatatypesatcompiletimeordiscoverdatatypesatruntime.Onceadatatypeisdiscovered,theapplicationcandynamicallycreateDataReaderstoreceiveTopicdataanduseintrospectiontoparseandprocessreceiveddata.DataWriterscanalsobecreatedtowritethediscovereddatatype.

Thedynamictypetechnologycanalsobenefitapplicationsthatwillbedeployedtoveryspaceconstrainedenvironments.UsingDynamicTypescanhelpreducethecodesizebyreducingoreliminatingthetypespecificcodegeneratedfromIDLorXML.

TheDynamicTypeAPIisfullydefinedintheCoreDXDDSTypeSystemProgrammer’sGuide.

18.2 SubscribewithDynamicTypesACoreDXDDSapplicationmaysubscribetoaTopicthatisdiscoveredatruntime,withoutanyknowledgeofthedatatypeassociatedwiththeTopic.Thebasicstepsinvolvedinthistypeofapplicationare:

1. Usethebuilt-inDataReadertoDiscoveraDataWriter2. UsetheTypeObjectorTypeCodeinformationfromtheDataWriterto

registeraDataType3. UsethetopicinformationfromtheDataWritertocreateaTopic4. CreateaDynamicDataReader5. Readdata

CoreDXDDSProgrammer’sGuide

208

AnexampleforsubscribingwithDynamicTypescanbefoundintheexamplesdirectoryoftheCoreDXDDSpackage.

18.3 PublishwithDynamicTypesACoreDXDDSapplicationmaypublishtoaTopicthatisdiscoveredatruntime,withoutanyknowledgeofthedatatypeassociatedwiththeTopic.ThisispossiblewiththeDynamicTypesfeaturesandAPI,althoughnotacommonusecaseforDynamicType.Thebasicstepsinvolvedinthistypeofapplicationare:

1. Createadynamicdatatyperepresentingthetypeofdatatobepublished

2. Registerthedynamicdatatype3. CreateaTopic4. CreateaDynamicDataWriter5. Initializeandsenddata

AnexampleforpublishingwithDynamicTypescanbefoundintheexamplesdirectoryoftheCoreDXDDSpackage.

209

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter19 ThreadingOptions

19.1 OverviewCoreDXDDScontainsadvancedmulti-threadedtechnology.Thisfeatureallowsanyapplication(evennon-threadedapplications)runningonmulti-corehardwaretomakeuseofmultiplecores.Usingmultiplecoresonmulti-corehardwareprovidessignificantperformancebenefits,asconfirmedusingIntel’sThreadCheckingbenchmarkingsystem.

Becausemanyofourusersarenotrunningonmulti-corehardware,andinfactarerunningonsignificantlyreduced-powersinglecorehardware,CoreDXDDSisconfigurabletoprovideperformancebenefitsinthistypeofresourceconstrainedenvironments.

19.2 ConfiguringThreadingOptionsCoreDXDDSrunsinanoptimizedthreadedmodelbydefault.ThismodecreatesthreethreadsforeachDomainParticipantcreatedintheapplication:

1. The main (application) thread

Themain(application)threadcontainsthemain()oftheapplication,andmostoftheapplicationexecution.

2. The CoreDX DDS reading thread

TheCoreDXDDSreadingthreadisresponsibleforreadingdataoffthetransport(UDPsocket,orothertransportasconfiguredbytheapplication).Dataisreadoffthetransport,unmarshaled,andputintotheDataCachesoftheappropriateDataReaders.

3. The CoreDX DDS work thread

TheCoreDXDDSworkthreadperformsallremainingDDS“work”.Thisincludesdiscovery,writingapplicationdatatothetransport,maintainingliveliness,performinghandshakingandanynecessaryrepairsforReliablereadersandwriters,andapplicationnotificationofevents.

CoreDXDDSthreadingisconfigurablethroughtheDomainParticipant’sCoreDX_ThreadModelQosPolicy.

CoreDXDDSProgrammer’sGuide

210

19.2.1 SingleThreadedConfigurationCoreDXDDSfeaturesasinglethreadedmodelforhigherperformanceonsignificantlyresourceconstrainedsinglethreadeddevices.EliminatingthreadsallowsCoreDXDDStoeliminatemuchofthelockingcode,andreducetheamountofcontextswitchesrequiredbytheapplication,helpingtoreducetherequiredmemoryandCPUresources.

Thesinglethreadedmodelrequirestheapplicationtoperiodically“handover”CPUtimetoCoreDXDDStoperformitwork(discovery,readingdata,writingdata,maintainingliveliness,etc.).Otherwise,thissinglethreadedmodelusesthesameAPIasthemulti-threadedmodel.Therearenonewlibrariestolinkwith.ThisensuresthereisnotacompletelynewAPItolearn,andmakesiteasytomoveapplicationsfrommulti-threadedtosingle-threadedmodes(andbackagain).

TheCoreDXDDSreleasepackagescontainexamplecodeillustratingtheuseofthesinglethreadedmode.Thisexamplecanbefoundintheexamplesdirectory,“hello_nothr”.Ifyoulookathello_pub.cinthisexample,youwillfindthatthe'nothreads'programmingmodelhasaverysimpleAPI.

First,usetheCoreDX_ThreadModelQoSPolicyontheDomainParticipanttoconfigureCoreDXDDStousethesinglethreadedmodel.

QoSPolicy DefaultValue

Description

CoreDX_ThreadModelQosPolicy

use_threads(unsignedchar) 1(true) Settinguse_threadsto0(false)willconfigureCoreDXDDStousethesinglethreadedmodel.

Next,provideCoreDXDDSwithtimetoperformwork.ItisimportanttoprovideCoreDXDDSwithenoughopportunitiestorunsothatitcanmanageitsinternaltasks.ThisentailsinsertingcallstoDDS_DomainParticipant_do_work()atstrategicpointsinyour'main'program.

DomainParticipant::do_work( duration_t time )

211

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

TheapplicationprovidesCoreDXDDSadurationinwhichitcanperformitsinternalwork.Thedo_workcallwillreturnwhenthistimeexpires.

19.2.2 ListenerThreadConfigurationCoreDXDDScancreatea4ththread(onlyapplicablewhenusingthemultithreadedmodel)thatwillhandleapplicationlistenercallbacks.

Inthestandard3-threadthreadedmodel,applicationlistenercallbacksarehandledbytheworkthread(alongwithdiscovery,writingdata,andmaintainingliveliness).Thismeansthatalong-runningapplicationdefinedlistenercallback(forexample,inaDataReader’son_data_availablelistenercallback)canblockCoreDXDDSfromperformingotherinternaltasks.

Thesolutionforthoseapplicationsthatcannotreducetheirlistenercallbackfunctionsistocreateaseparatethreadforlistenercallbacks.Withthelistenerthreadenabled,anapplicationcanblockinsidealistenercallbackwithouteffectingotherDDSoperations.

QoSPolicy DefaultValue

Description

CoreDX_ThreadModelQosPolicy

create_listener_thread(unsignedchar)

0(false) Settingcreate_listener_threadto1(true)willconfiguretheDomainParticipanttocreatethe4ththreadforapplicationcallbacks.Thisoptionisapplicableonlywhenuse_threadsissettonon-zero(true).

CoreDXDDSProgrammer’sGuide

212

213

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter20 TransmitBuffers

20.1 OverviewEachCoreDXDDSDataWritercontainsatransmitbuffertoholddatathatiswaitingtobepublished.

TransmitbuffersusuallyholdsampledatafromDataWriter::write()calls,butcanalsoholdinstancelifecycleinformationincludingunregisterordisposeactions.Bothbuilt-inDataWritersandapplicationdefinedDataWriterscontainthesetransmitbuffers.

Bydefault,transmitbuffersaredynamic,thatis,theygrowandshrinkasnecessarytominimizetheamountofmemoryconsumedbytheCoreDXDDSinfrastructure.CoreDXDDStransmitbufferscanbeconfiguredtobeastaticsize,orconfiguredtobedynamicwithspecifiedminimumandmaximumsizes.

20.2 DynamicTransmitBuffersCoreDXDDStransmitbuffersarebydefault,dynamic.Withoutanyconfiguration,DataWritertransmitbufferswillgrowandshrinkasnecessarytosupportthesizeofdatawrittenwhileconsumingaminimalamountofmemory.

CoreDXDDStransmitbuffersizescanbeconfiguredwithaQoSpolicy,orwithenvironmentvariables.TheDataWriterQoSpolicytoconfiguretheminimumandmaximumbuffersizesisdescribedinthefollowingtable.

Table20-1:InstanceExample

QoSPolicy DefaultValue

Description

DataWriter_RTPSWriterQoSPolicy(application-definiedDataWriters)

min_buffer_size(unsignedint) 16 Inbytes,thetransmitbufferwillstartatthissize,andindynamic

CoreDXDDSProgrammer’sGuide

214

operations,willnotshrinksmallerthanthissize.

max_buffer_size(unsignedint) 65400 Inbytes,thetransmitbufferwillnotgrowlargerthanthissize.

DataWriter_RTPSWriterQoSPolicy(built-inDataWriters)

min_buffer_size(unsignedint) 16 Forbuilt-inwriters,thetransmitbufferwillstartatthissize,andindynamicoperations,willnotshrinksmallerthanthissize(inbytes).

max_buffer_size(unsignedint) 32768 Forbuilt-inwriters,thetransmitbufferwillnotgrowlargerthanthissize(inbytes).

TheCoreDXDDSenvironmentvariablestoconfigurethetransmitbuffersizeare:COREDX_MIN_TX_BUFFER_SIZEandCOREDX_MAX_TX_BUFFER_SIZE,andareusedinthesamemannerastheDataWriterQoSpolicydescribedabove.TheseenvironmentvariableswilloverridethedefaultsizesofallDDSentities(bothbuilt-inandapplicationdefined).

Thesearethesizesthatboundthedynamicsizingofthebuffers.Thetransmitbufferwillnotgrowbeyondmax_buffer_size,andthetransmitbufferwillnotshrinkbelowmin_buffer_size.

ThemaximumtransmitbuffersizewillaffecthowCoreDXDDSaggregates,batches,and/orfragmentswrittendata.Thisisparticularlynoticeablewithapplicationsthatperformmany,frequentwrites,orhaveburstsofwrites.Withasmallupperboundonthetransmitbuffer,CoreDXDDSwillneedtoperformmanyindividualwrites,ratherthanaggregatingorbatchingsamplestogethertobesentatonetime.

WhentheapplicationwritesasamplethatislargerthantheconfiguredmaximumtransmitbuffersizefortheDataWriter,CoreDXDDSwillfragmentthedatasampleasnecessarytofitthetransmitbuffer,andre-assemblethesampleonthereceivingsidebeforeitisavailabletothereceivingapplication.

215

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Theenvironmentvariable:COREDX_MAX_PACKET_SIZE(availableinearlierCoreDXDDSreleases)wasequivalenttoCOREDX_MAX_TX_BUFFER_SIZE.TheMAX_PACKET_SIZEenvironmentvariableisdeprecated,andshouldnolongerbeused.

20.3 StaticTransmitBuffersSinceallocatingandde-allocatingmemorycanbeexpensiveoperations,applicationsinterestedinverylowlatenciesmaybenefitfromastatictransmitbufferthatdoesnotgroworshrinkthroughthelifeoftheapplication.Thisconfigurationispossiblebysettingthemin_buffer_sizeandmax_buffer_sizetothesamevalue,usingeithertheQoSpoliciesorenvironmentvariablesdescribedabove.

Specialcareshouldbetakenbeforesettingastatictransmitbuffersize.Sincethetransmitbuffermustbelargeenoughtoholdthecompletemarshaleddatasample,itisimportanttounderstandthepossiblesizesforallpossibleapplicationdatasampleswrittenbytheapplication.Thisisespeciallytruewhengloballyconfiguringstaticbuilt-inDataWritertransmitbuffersusingtheenvironmentvariables.

CoreDXDDSProgrammer’sGuide

216

217

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter21 ReceiveBuffers

21.1 OverviewEachCoreDXDDSDomainParticipantcontainsareceivebuffertoholdincomingdatathatwillbepassedtoitsDataReadersandeventuallythereadingapplication.

Receivebuffersareusedtoholddatareadfromthetransportuntilisitprocessed(parsed)bytheCoreDXDDSinfrastructure.ThereisonereceivebufferforeachDomainParticipant(asopposedtooneforeachDataReader).Receivebuffersaredynamic,thatis,theygrowandshrinkasnecessarytominimizetheamountofmemoryconsumedbytheCoreDXDDSinfrastructure.

TheapplicationmaysettheminimumsizeoftheDomainParticipant’sreceivebuffer.ThisiscommonlyusedwheninteroperatingwithotherDDSproducts,whodon’teffectivelycommunicateRTPSmessagesizes.CoreDXDDSwill“learn”howtosizethereceivebuffer,butitmaybeforcedtodropsomeoftheinitialmessagesreceivedduringthislearningperiod.StartingwithasufficientlylargereceivebuffercanoptimizeperformanceinthesemixedDDSproductenvironments.

TheapplicationmaysetthemaximumsizeoftheDomainParticipant’sreceivebuffer,whichlimitsthesizethereceivebuffermaygrowto.Specialcareshouldbetakenwhenconfiguriringthemaximumreceivebuffersize.Iftheconfiguredmaximumsizeissmallerthanthetransport’smaximummessagesize,CoreDXDDSmaybeforcedtodropreceivedsamples.

ThisconfigurationAPIisdescribedintheTransportConfigurationsectionofthisProgrammer’sGuide.

CoreDXDDSProgrammer’sGuide

218

219

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

Chapter22 DataBatching

DataBatchingistheprocessesofcombiningdatasamplesintooneRTPSmessageinordertoreducethenetworkoverheadandimprovethroughput,especiallywithsmallersamples.

Bydefault,databatchingisdisabledinCoreDXDDSDataWriters.DataReadersareconfiguredtoacceptbatchmessagesbydefault.ApplicationscanusethefollowingQoSpoliciestoconfiguredatabatching.

QoSPolicy DefaultValue Description

CoreDX_RTPSWriterQosPolicy

enable_batch_msg(unsignedcharorboolean)

0(orfalse) ConfiguretheDataWritertousebatching.

Possiblevaluesare:0or1(falseortrue)

CoreDX_RTPSReaderQosPolicy

accept_batch_msg(unsignedcharorboolean)

1(ortrue) ConfiguretheDataReadertousebatching.

Possiblevaluesare:0or1(falseortrue)

221

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

222

Chapter23 Licensing

CoreDXDDSusesdevelopmentandrun-timelicenses.AdevelopmentlicenseisrequiredforusingtheCoreDXDDSdatatypecompiler(coredx_ddl).Arun-timelicenseisrequiredforrunninganapplicationbuiltwiththeCoreDXDDSlibrary.Bothrun-timeanddevelopmentlicensescanbecontainedinthesamelicensefileorinseparatefiles.Hereisanexamplelicensefilecontainingbothdevelopmentandrun-timelicenses:

coredx.lic

#====================================================================== # CoreDX DDS License file for CompanyX # # Created: Jul 22, 2008, by Twin Oaks Computing, Inc. # Contains: Development and run-time licenses # #====================================================================== # # development LICENSE lines: # - Contain your development keys - DO NOT EDIT! LICENSE PRODUCT=coredx_ddl BUILD=Release OS=linux ARCH=x86 USERID=ntucker HOSTID=00195b70c3be CUSTOMER=Company_X SIG=abcdefghijklmnopqrstuvwxyz # # run-time LICENSE lines: # # - Contain your run-time keys - DO NOT EDIT! LICENSE PRODUCT=coredx_c BUILD=Release HOSTID=00195b70c3be CUSTOMER=Company_X SIG=abcdefghijklmnopqrstuvwxyz

Figure23-1:ExampleCoreDXDDSlicensefile

23.1 DevelopmentLicensesDevelopmentlicensesarecontainedinalicensefile.ThesedevelopmentlicensekeysarerequiredbytheCoreDXDDSdatatypecompiler.Todevelop(compile)withCoreDXDDS,anenvironmentvariableTWINOAKS_LICENSE_FILEmustbesettothefullpathtothelicensefile.

223

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

23.2 Run-timeLicensesThereareafewwaystouserun-timelicenses.Run-timelicensesmaybecontainedinalicensefile,orotherwisecodedintotheapplicationandprovidedtoCoreDXDDSthroughthelicenseAPI.

1. UseanEnvironmentVariable

TheenvironmentvariableTWINOAKS_LICENSE_FILEmaybesettooneofthefollowing:

• Thefullpathtothelicensefile• TheLICENSEstringcontainingtherun-timelicense

Ifyouhaveaccesstothelicensefilefromtherun-timeenvironment,thesimplestwaytousethelicenseistosetaTWINOAKS_LICENSE_FILEenvironmentvariabletobethefullpathtothelicensefile.

Ifyoudonothaveaccesstothelicensefile,youcanstillusethelicensebysettingtheTWINOAKS_LICENSE_FILEenvironmentvariabletotheappropriaterun-timeLICENSEline.Therun-timelicenselinestartswiththefollowing:

LICENSE PRODUCT=coredx_c

Usingthelicensestringisagoodoptionforembeddedrun-timeenvironments.Fortherun-timelicenseintheaboveexamplelicensefile,setyourTWINOAKS_LICENSE_FILEenvironmentvariablelike:

linux% export TWINOAKS_LICENSE_FILE=<LICENSE PRODUCT=coredx_c HOSTID=00195b70c3be CUSTOMER=Company_X SIG=abcdefghijklmnopqrstuvwxyz>

2. UsetheAPI

TheDomainParticipantFactoryprovidesanAPItosetthelicensestring:

DomainParticipantFactory::set_license(const char * lic)

ThelicargumentmaybesettoanyoftheoptionsthatcanbeusedfortheTWINOAKS_LICENSE_FILEenvironmentvariable,describedabove.Thatisoneofthefollowing:

• Thefullpathtothelicensefile

CoreDXDDSProgrammer’sGuide

224

• TheLICENSEstringcontainingtherun-timelicense

ThelicenseAPIisparticularlyusefulforoperatingsystemsthatdonotsupportenvironmentvariables.Thisallowstheapplicationtoobtainthelicensestringinanymanneracceptablebytheenvironmentandsystemrequirements,andthenusetheAPItopassthelicensestringtoCoreDXDDS.

225

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

226

Chapter24 Troubleshooting

24.1 GeneralTroubleshootingToolsNetworkcommunicationcanbecomplextotroubleshoot.Itisrecommendedthatthedeveloperbecomefamiliarwithstandardtoolsavailableonthedevelopmentnetwork.Forexample,underUNIX,toolssuchasifconfig,netstat,androutecanbeusefultogainanunderstandingofthenetworkconfiguration.Further,toolsthatcaptureanddecodenetworktrafficareveryuseful.ThewiresharktoolhaswideplatformsupportandincludesaprotocolanalyzerforRTPS(theDDSwireprotocol).WiresharkisanindispensibletoolforanalyzingDDSnetworktraffic.(Seewww.wireshark.org).

TwinOaksComputingoffersatoolthatisspeciallydesignedforanalyzinganddebuggingDDSapplications:CoreDXDDSSpy.TheCoreDXDDSSpytooldisplays,ataglance,alltheDDSEntitiesonthenetwork.ThisallowstheapplicationdevelopertoquicklyviewofalltheDataReadersandDataWritersonthenetwork,whatTopictheyarecommunicatingon,andwhichonesarenotcommunicatingduetoQoSordatatypemismatches.Inaddition,CoreDXDDSSpytoviewalltheDDSnetworktraffic,includingsampleswrittenbyDDSapplicationforfurtheranalysisofDDSapplications.TheCoreDXDDSSpytoolisalsousefulinmorecomplexDDSnetworkanalysis.

24.2 NoCommunicationsbetweenDDSapplicationsIfReadersandWritersarenotcommunicatingatall,thenthereareseveralitemstocheck.First,itisrecommendedthatListenersbeinstalledonboththereaderandwritertohandlealloftheevents.Theseeventsmayprovideinsightintowhytheentitiesarenotcommunicating.Forexample,therequested_incompatible_qosandoffered_incompatible_qoslistenersareveryuseful.

24.2.1 NetworkConfiguration(ifrunningacrossanetwork)IfallyourDDSDomainParticipantsarerunningononemachine,skipthissection.

227

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

IftheDDSDomainParticipantsarerunningacrossanetwork,isyournetworkworking?Canyouusepingoranotherprogramtotalkbetweenyourhosts?

24.2.2 DiscoveryThefirststepinDDScommunicationsisthediscoveryprocess,whereDomainParticipantsbroadcasttheirexistenceandlookforpeerDomainParticipants.Thisdiscoveryprotocolusesmulticast.

IfyourDDSDomainParticipantsarecommunicationacrossroutersoraVirtualMachine,youmayneedtoincreasethereachofyourmulticastpacketsbyincreasingthenumberofhops(seetheCoreDXDDSTransportChapterformoreinformation).

24.2.3 DataReader/DataWritermatchingThenextstepinDDScommunicationsismatchingaDataWritertoaDataReader.Matchingrequiresseveralcompatibleattributes:

1. TheTopicnamemustmatch.Carefullycheckthecreate_topic,create_datawriter,andcreate_datareadercallstoensurethesameTopicnamestringisusedforboththeDataWriter’sTopicandtheDataReader’sTopic.

2. Thedatatypesmustmatch.Notonlythenameofthedatatype,butalsothetypesmustmatch.CoreDXDDSserializesthetypeofthedataintoa“typecode”,andcomparesthetypecodeoftheDataWriterwiththetypecodeoftheDataReader.Thesetypesmustmatch.

3. RecallthattheQoSsettingfortheDataReaderandDataWritermustbecompatibleforcommunicationstooccur(seetheQoSCompatibilitysection).

TheSubscriptionMatchedStatusandPublicationMatchedStatusstatusesrecordmatchingDataReadersandDataWriters.TheOfferedIncompatibleQosStatusandRequestedIncompatibleQosStatusrecordmis-matchingDataWritersandDataReadersduetoQoSincompatibility.UseListeners(seetheListenerssection)orConditions(seetheConditionsandWaitSetssection)tocheckthesestatuses.

24.3 MissingorlostsamplesTherearenumerousQoSpoliciesthatcancausesamplestobemissingorlost.Afewofthemorecommononesaredescribedbelow.Inaddition,QoSsettingscaninteractwitheachothercausingnon-intuitiveapplication

Formatted: Font:Italic

Deleted: CoreDXDDSTransport

Formatted: Font:(Default) +Theme Body (Calibri), Italic

Deleted: QoSCompatibility

Formatted: Font:Italic

Deleted: Listeners

Formatted: Font:Italic

Deleted: ConditionsandWaitSets

CoreDXDDSProgrammer’sGuide

228

behavior.Whiletheexamplesbelowdescribesomecommonproblemsandsolutions,yourspecificnetworkenvironmentandotherQoSsettingsmayresultinapplicationbehaviordifferentthanwhatisdescribedbelow.

TwinOaksComputingisdedicatedtothehelpingcustomersgetthemostoutoftheirapplicationcommunicationsusingCoreDXDDS.Pleasecontactusforadditionalsupportwithyourspecificapplication.

24.3.1 ReliabilityIfyouarecommunicatingoveranetwork,asloworunreliablenetworkcancausepacketstobelost.Similarly,one“slow”subscribinghostcanhavetroublekeepingupwithpublishinghosts.SettingtheReliabilityQoSpolicytoRELIABLEcanreduceoreliminatelostpacketsinthisscenario.

ItisimportanttonotethataRELIABLEReliabilitycanonlyhappenwhileboththeDataWriterandDataReaderarebothinexistence.Sometimes,apublishingapplicationwillexit(killingtheDataWriter)beforetheDataReaderhasreceivedallthepublishedsamples,resultinginlostsamples.

24.3.2 DurabilityIfyourDataReaderisconsistentlymissingthefirstoneortwosamplespublishedbyaDataWriter,chancesarethediscoveryprocessisnotcompleting(matchingtheDataWritertotheDataReader)beforethosefirstsamplesarewritten.Ingeneral,thesolutionistoraisetheDurabilityQoSsettingtoTRANSIENT_LOCAL.ThiscanhaveothersideeffectswhencombinedwithotherQoSsettings(seetheHISTORYsection).OtheroptionsincludehavingthepublishingapplicationwaitforadiscoveredDataReaderorsimplypauseforoneortwosecondsbeforestartingtowritedata;allowingthediscoveryprocesstocomplete.

24.3.3 HistoryBydefault,theHistoryQoSpolicyissettoKEEP_LAST,withadepthof1(one).ConsideraDataWriterwritingsamplesfastenoughthattheCoreDXDDSinfrastructuremustqueueanybeforesending,oraDataReaderreceivingsamplesfastenoughthattheymustbequeuedbeforearead()ortake()operationisused.WithaHistorythatisonlykeepingthe1mostrecentdatasampleforeachinstance,thereisapossibilityforsamplestobedropped.ThesolutionistoincreasetheHistorydepthtogreaterthan1,orsettheHistorytoKEEP_ALL.

Formatted: Font:Italic

Deleted: HISTORY

229

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

ThereisonlyonecombinationofQoSsettingsthatwillguaranteesamplesarenotlostduringoperationsandthatis:

Reliability=RELIABLE

History=KEEP_ALL

ResourceLimits=Set

ThiscombinationofQoSpoliciesforcesthepublishingapplicationtoblockonaDataWriter::write()operation,ifanymatchedDataReadersisunabletoacceptanothersample.TheDataWriter::writeoperationwillcomplete(andreturn)onceallmatchedDataReadershaveenoughroomtoreceiveanadditionalsample.

24.3.4 Puttingitalltogether:GuaranteedDeliveryAcommonquestionfromDDSusersis,“HowdoIguaranteedeliverywithDDS?”Thegoalistoguaranteealldatawrittenbyapublishingapplicationwillbedeliveredtoallmatchedsubscribingapplications.

TherearethreeQoSpoliciesthatneedtobeconfiguredtoguaranteedeliveryofdatasamples:

1. Reliability (kind = RELIABLE) 2. History (kind = KEEP_ALL) 3. Resource Limits (set to something other than

infinite)

AlloftheseQoSpoliciesmustbesettoensuredeliveryofpublisheddata.

TheRELIABLEReliabilitysettingallowsCoreDXDDStomonitordatareception,andretransmitdataifitisnotreceivedbyanyDataReaders.

TheKEEP_ALLHistorysettinginstructsCoreDXDDSthatitisNOTOKtooverwriteanydatasamplesintheDataWriter’scache.ThisisimportantifthereareanyDataReadersthatarehavingtrouble“keepingup”,andlotsofsamplesmustbestoredforretransmission.

SettingtheResourceLimitsallowsCoreDXDDStolimitthegrowthoftheDataWriter’scache,evenwiththeKEEP_ALLHistorysetting.Thisisimportant,notonlyforresourceutilizationatruntime,butalsobecauseitallowstheapplication’scalltoDataWriter::write()toblockifthereisno

CoreDXDDSProgrammer’sGuide

230

moreroominthecache(becauseatleastoneDataWriterhasnotacknowledgedanumberofsentsamples).

24.4 TypeSupportversionmismatchCoreDXDDSprovidesstrongdatatyping.ApplicationdevelopersdefinethedatatypesthatwillbeusedforDDScommunicationsatcompiletime,andusetheCoreDXdatatypecompilertogeneratetypespecificDDScodeforeachdatatype.ThisgeneratedcodeinteractsverycloselywiththeDDSlibrarytoperformtypespecificoperations(forexample,serializingdataonawrite()andde-serializingdataonaread()).Forthisreason,itisimportantthatthedatatypecompilerusedtogeneratethecodematchtheDDSlibrarythatislinkedintotheapplication.Iftheseversionsdonotmatch,CoreDXDDSwillprintawarningmessagewhenregister_type()iscalled:

Sample Warning Message for Version Mismatch

WARNING: MyType TypeSupport version does not match CoreDX Library version. This may cause software instability or crashes.

Figure24-1:ExampleCoreDXDDSlicensefile

Toresolvethisissue,re-generateyourtypespecificcodewiththecorrectversionoftheCoreDXdatatypecompiler,andchecktheversionoflibdds.athatyouarelinkingwithyourapplication.

24.5 Can’tfindithere?Callusat720-733-7906,sendanemailtosupport@twinoakscomputing.com,orcheckoutourFrequentlyAskedQuestionsathttp://www.twinoakscomputing.com/coredx/faq,orvisitouronlineforumsathttp://www.twinoakscomputing.com/forums.

231

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

CoreDXDDSProgrammer’sGuide

232

Chapter25 AboutTwinOaksComputing

TwinOaksComputing,Incisacompanydedicatedtodevelopinganddeliveringqualitysoftwaresolutions.Weleverageourtechnicalexperienceandabilitiestoprovideinnovativeandusefulservicesinthedomainofintelligencesystems.

TwinOaksComputingspecializesinhigh-performanceandembeddedcommunicationssolutionsforcommercialandDoDapplications.OurCoreDXDDSwasfirstreleasedin2008.InMarch2009,TwinOaksComputingparticipatedinthefirstpublicmulti-vendorDDSinteroperabilitydemonstration.Formoreinformationonourproducts,pleasevisitourwebsiteathttp://www.twinoakscomputing.com.

TwinOaksComputingisheadquarteredinCastleRock,CO.Ourstaffhasover30yearsofexperiencedevelopingandsupportingDoDsystems.WehaveperformedinstallsandupgradesofcriticalmissionsystemsatU.S.militaryfacilitiesaroundtheworld.Throughthisexperience,weunderstandtheimportanceofthesystemsthatcollect,manage,anddistributeinformationforthewarfighter.

WeapplyourtechnicalexperiencetodevelopsolutionsinthefollowingIntelligenceDomains:

• TacticalCommunications-Link16,IBS,Link11,Link11B

• TacticalDataCorrelation-SingleandMulti-INTCorrelation

• SituationalAwareness-consolidateddisplayoftacticaldata

WehaveTechnicalexperienceinthefollowingareas:

• Networking-Ethernet,IP,UDP,TCP,RDMA

• DeviceDrivers-MILSTD-1553,Serial,NetworkInterface

• InterprocessCommunication-DDS,Sockets,CORBA,RPC,SysVIPC

• OperatingSystems-SolarisTM,LinuxTM,FreeBSDTM,VxWorksTM,andothers

• DatabaseTechnologies-SybaseTM,OracleTM,MySQLTM,andothers

233

CoreDX Data Distribution Service – Programmer’s Guide Version 3.4.0

• NetworkServices-emailservers,HTTPservers,DNSservers,firewalls

• SystemSecurity-DCID6/3securityaccreditation

• SystemAdministration-scriptinglanguages,backup/restore,storagemanagement,softwareinstallation/configuration

Wewouldbehappytodiscusshowwecanhelpyou.Pleasecontactusatcontact@twinoakscomputing.com.

CoreDXDDSProgrammer’sGuide

234

Chapter26 ContactInformation

Haveaquestion?Don’thesitatetocontactusbyanymeansconvenientforyou:

WebSite: http://www.twinoakscomputing.com

Email: support@twinoakscomputing.com

Twitter:@CoreDX_DDS

Phone:720.733.7906

+33(0)962237220

Address:

755MaletaLane

Suite203

CastleRock,CO,80108

Page 81: [1] Deleted Nina Tucker 4/6/17 12:31:00 PM

Table9-2

Page 82: [2] Deleted Nina Tucker 4/6/17 12:31:00 PM

Table9-2

top related