예제 #1
0
/* entry point exported so symbol can be found in shared library */
OS_API_EXPORT
int HelloWorldDataSubscriber(int argc, const char *argv[])
{
   DDS_DomainParticipant domainParticipant;
   DDS_sequence_HelloWorldData_Msg* message_seq = DDS_sequence_HelloWorldData_Msg__alloc();
   DDS_SampleInfoSeq* message_infoSeq = DDS_SampleInfoSeq__alloc();
   DDS_Subscriber message_Subscriber;
   DDS_DataReader message_DataReader;
   DDS_Topic messageTopic;
   DDS_TypeSupport messageTypeSupport;
   char * messageTypeName;
   c_bool isClosed = FALSE;
   int count = 0;
   os_time os_delay200 = { 0, 200000000 };

   // Create DDS DomainParticipant
   domainParticipant = createParticipant("HelloWorld example");

   // Register the Topic's type in the DDS Domain.
   messageTypeSupport = HelloWorldData_MsgTypeSupport__alloc();
   checkHandle(messageTypeSupport, "HelloWorldData_MsgTypeSupport__alloc");
   registerMessageType(domainParticipant, messageTypeSupport);
   // Create the Topic's in the DDS Domain.
   messageTypeName = HelloWorldData_MsgTypeSupport_get_type_name(messageTypeSupport);
   messageTopic = createTopic(domainParticipant, "HelloWorldData_Msg", messageTypeName);
   DDS_free(messageTypeName);
   DDS_free(messageTypeSupport);

   // Create the Subscriber's in the DDS Domain.
   message_Subscriber = createSubscriber(domainParticipant);

   // Request a Reader from the the Subscriber.
   message_DataReader = createDataReader(message_Subscriber, messageTopic);

   printf("=== [Subscriber] Ready ...");

   do
   {
      g_status = HelloWorldData_MsgDataReader_take(
          message_DataReader,
          message_seq,
          message_infoSeq,
          1,
          DDS_ANY_SAMPLE_STATE,
          DDS_ANY_VIEW_STATE,
          DDS_ANY_INSTANCE_STATE );
      checkStatus(g_status, "HelloWorldData_MsgDataReader_take");

      if( message_seq->_length > 0 && message_infoSeq->_buffer[0].valid_data )
      {
         isClosed = TRUE;
         printf("\n=== [Subscriber] message received :" );
         printf( "\n    userID  : %d", message_seq->_buffer[0].userID );
         printf( "\n    Message : \"%s\"\n", message_seq->_buffer[0].message );
         fflush(stdout);
         HelloWorldData_MsgDataReader_return_loan (message_DataReader, message_seq, message_infoSeq);
      }

      if(isClosed == FALSE)
      {
         os_nanoSleep(os_delay200);
         ++count;
      }
   }
   while( isClosed == FALSE && count < 1500 );

   os_nanoSleep(os_delay200);

   // Cleanup DDS from the created Entities.
   deleteDataReader(message_Subscriber, message_DataReader);
   deleteSubscriber(domainParticipant, message_Subscriber);
   deleteTopic(domainParticipant, messageTopic);
   deleteParticipant(domainParticipant);

   // Cleanup C allocations
   // Recursively free the instances sequence using the OpenSplice API.
   DDS_free(message_seq);
   DDS_free(message_infoSeq);

   return 0;
}
예제 #2
0
int main(int argc, char *argv[])
{

   DDS_sequence_LifecycleData_Msg* msgSeq = DDS_sequence_LifecycleData_Msg__alloc();
   DDS_SampleInfoSeq* msgInfoSeq = DDS_SampleInfoSeq__alloc();
   DDS_Subscriber msgSubscriber;
   DDS_DataReader msgDataReader;

   unsigned long j, inputChar;
   os_time os_delay20ms = (os_time)  {0, 20000000};
   os_time os_delay200ms = (os_time) {0, 200000000};

   // Force the output to be unbuffered.
   setbuf(stdout, (char *) 0);

   // First initialize the Topics and their DDS Entities

   // Create DDS DomainParticipant
   createParticipant("Lifecycle example");

   //------------------ Msg topic --------------------//
   // Register Msg Topic's type in the DDS Domain.
   g_msgTypeSupport = LifecycleData_MsgTypeSupport__alloc();
   checkHandle(g_msgTypeSupport, "LifecycleData_MsgTypeSupport__alloc");
   registerMsgType(g_msgTypeSupport);
   // Create Msg Topic in the DDS Domain.
   g_msgTypeName = (char*) LifecycleData_MsgTypeSupport_get_type_name(g_msgTypeSupport);
   g_msgTopic = createTopic("Lifecycle_Msg", g_msgTypeName);
   DDS_free(g_msgTypeName);
   DDS_free(g_msgTypeSupport);

   // Create the Publisher's in the DDS Domain.
   msgSubscriber = createSubscriber();

   // Request a DataReader from the the Subscriber.
   msgDataReader = createDataReader(msgSubscriber, g_msgTopic);
   //End initialization.

   printf("\n=== [Subscriber] Ready...");

   msgInfoSeq->_length = 0;
   DDS_boolean closed = FALSE;
   int nbIter = 1;
   int nbIterMax = 100;
   while ((closed == FALSE) && (nbIter < nbIterMax))
   {
      g_status = LifecycleData_MsgDataReader_read(msgDataReader, msgSeq, msgInfoSeq, 1, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
      checkStatus(g_status, "LifecycleData_MsgDataReader_read");

      if( msgInfoSeq->_length > 0 )
      {
         if( msgInfoSeq->_buffer[0].valid_data == TRUE )
         {
            printf("\n\n Message        : %s", msgSeq->_buffer[0].message);
            printf("\n WriterStates : %s", msgSeq->_buffer[0].writerStates);
            printf("\n valid_data     : %d", msgInfoSeq->_buffer[0].valid_data);
            printf("\n sample_state:%s-view_state:%s-instance_state:%s\n", 
	   		       sSampleState[getIndex(msgInfoSeq->_buffer[0].sample_state)],
			       sViewState[getIndex(msgInfoSeq->_buffer[0].view_state)],
			       sInstanceState[getIndex(msgInfoSeq->_buffer[0].instance_state)]);   
         }
         closed = strcmp(msgSeq->_buffer[0].writerStates, "STOPPING_SUBSCRIBER") == 0 ? TRUE : FALSE;
         printf("=== closed=%d - nbIter %d\n", closed, nbIter);
         g_status = LifecycleData_MsgDataReader_return_loan(msgDataReader, msgSeq, msgInfoSeq);
         checkStatus(g_status, "LifecycleData_MsgDataReader_return_loan");
         // Useless to harass the system, so we wait before to retry.
         os_nanoSleep(os_delay200ms);
         msgInfoSeq->_length = 0;
         nbIter++;
      }
   }
   printf("\n=== [Subscriber] stopping after %d iterations ..\n", nbIter);
   if (nbIter == nbIterMax) printf ("*** Error : max %d iterations reached", nbIterMax);
   // Cleanup DDS from the created Entities.
   deleteDataReader(msgSubscriber, msgDataReader);
   deleteSubscriber(msgSubscriber);
   deleteTopic(g_msgTopic);
   deleteParticipant();

   // Cleanup C allocations, recursively freeing the allocated structures and sequences using the OpenSplice API.
   DDS__free(msgSeq);
   DDS__free(msgInfoSeq);

   return 0;
}
예제 #3
0
main(int argc, const char *argv[])
{
   int x, i;
   DDS_InstanceHandle_t userHandles[10];
   DDS_sequence_DurabilityData_Msg* instances = DDS_sequence_DurabilityData_Msg__alloc();
   DDS_boolean isTransient;
   DDS_boolean isPersistent;
   DDS_boolean isAutodisposeTrue;
   DDS_boolean isAutodisposeFalse;
   DDS_boolean isAutomated;
   os_time delay_10s = { 10, 0 };

   if( argc < 4 )
   {
      usage();
   }

   isTransient = (strcmp(argv[1], "transient") == 0) ? TRUE : FALSE;
   isPersistent = (strcmp(argv[1], "persistent") == 0) ? TRUE : FALSE;
   isAutodisposeTrue = (strcmp(argv[2], "true") == 0) ? TRUE : FALSE;
   isAutodisposeFalse = (strcmp(argv[2], "false") == 0) ? TRUE : FALSE;
   if( !((isTransient || isPersistent) && (isAutodisposeTrue || isAutodisposeFalse)) )
   {
      usage();
   }
   isAutomated = (strcmp(argv[3], "true") == 0) ? TRUE : FALSE;

   g_durability_kind = (char*) argv[1];

   g_autodispose_unregistered_instances = isAutodisposeTrue ? (DDS_boolean) TRUE : (DDS_boolean) FALSE;

   // Create DDS DomainParticipant
   createParticipant("Durability example");

   // Register the Topic's type in the DDS Domain.
   g_MsgTypeSupport = DurabilityData_MsgTypeSupport__alloc();
   checkHandle(g_MsgTypeSupport, "DurabilityData_MsgTypeSupport__alloc");
   registerType(g_MsgTypeSupport);
   // Create the Topic's in the DDS Domain.
   g_MsgTypeName = (char*) DurabilityData_MsgTypeSupport_get_type_name(g_MsgTypeSupport);
   createTopic("DurabilityData_Msg", g_MsgTypeName);
   DDS_free(g_MsgTypeName);
   DDS_free(g_MsgTypeSupport);

   // Create the Publisher's in the DDS Domain.
   createPublisher();

   // Request a Writer from the the Publisher.
   createWriter();

   instances->_buffer = DDS_sequence_DurabilityData_Msg_allocbuf(10);

   for( x = 0; x < 10 ; x++ )
   {
      instances->_buffer[x].id = x;

      instances->_buffer[x].content = DDS_string_alloc(1);

      snprintf(instances->_buffer[x].content, 2, "%d", x);

      userHandles[x] = DurabilityData_MsgDataWriter_register_instance(g_DataWriter, &instances->_buffer[x]);

      printf("\n%s", instances->_buffer[x].content);
      g_status = DurabilityData_MsgDataWriter_write(g_DataWriter, &instances->_buffer[x], userHandles[x]);
      checkStatus(g_status, "DurabilityData_MsgDataWriter_write");
   }

   if( isAutomated == FALSE )
   {
      int c = 0;
      printf("\n Type 'E' + Enter to exit:\n");
      do
      {
         c = getchar();
         printf("\n You Typed %c", c);
      }
      while( c != (int) 'E' );
      printf("\n Exiting.\n\n");
   }
   else
   {
      printf( "\n === sleeping 10s..." );;
      os_nanoSleep(delay_10s);

   }

   // Cleanup DDS from the created Entities.
   deleteDataWriter();
   deletePublisher();
   deleteTopic();
   deleteParticipant();

   // Cleanup C allocations, recursively freeing the allocated structures and sequences using the OpenSplice API.
   DDS_free(instances);

   // Print out an empty line, just to let behind a clean new line for the shell..
   printf("\n");
   return 0;
}
예제 #4
0
u_group
u_groupNew(
    u_participant participant,
    const c_char *partitionName,
    const c_char *topicName,
    v_duration timeout)
{
    u_result r;
    v_participant kparticipant;
    v_kernel kernel;
    v_topic ktopic;
    v_partition kpartition;
    v_group kgroup;
    c_iter topics;
    os_time delay;
    u_group group = NULL;

    if ((partitionName != NULL) && (topicName != NULL)) {
        if (participant != NULL) {
            r = u_entityWriteClaim(u_entity(participant), (v_entity*)(&kparticipant));
            if (r == U_RESULT_OK){
                assert(kparticipant);
                kernel = v_objectKernel(kparticipant);
                topics = v_resolveTopics(kernel,topicName);
                if (c_iterLength(topics) == 0) {
                    c_iterFree(topics);
                    delay.tv_sec = timeout.seconds;
                    delay.tv_nsec = timeout.nanoseconds;
                    os_nanoSleep(delay);
                    topics = v_resolveTopics(v_objectKernel(kparticipant),
                                             topicName);
                }
                if (c_iterLength(topics) > 1) {
                    OS_REPORT_1(OS_WARNING, "u_groupNew", 0,
                                "Internal error: "
                                "Multiple topics found with name = <%s>.",
                                topicName);
                }

                ktopic = c_iterTakeFirst(topics);

                /* If ktopic == NULL, the topic definition is unknown.
                 * This is not critical since it may become known in the near future.
                 * In that case the caller is responsible for retrying to create this group,
                 * and log something if, eventually, the group still cannot be created.
                 */
                if (ktopic != NULL) {
                    kpartition = v_partitionNew(kernel, partitionName, NULL);
                    if (kpartition != NULL) {
                        kgroup = v_groupSetCreate(kernel->groupSet, kpartition, ktopic);
                        if (kgroup != NULL) {
                            group = u_groupCreate(kgroup, participant);
                            if (group == NULL) {
                                OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                                            "Create proxy failed. "
                                            "For Partition <%s> and Topic <%s>.",
                                            partitionName, topicName);
                            }
                            c_free(kgroup);
                        } else {
                            OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                                        "Create kernel entity failed. "
                                        "For Partition <%s> and Topic <%s>.",
                                        partitionName, topicName);
                        }
                        c_free(kpartition);
                    } else {
                        OS_REPORT_2(OS_ERROR,"u_groupNew", 0,
                                    "Failed to create partition. "
                                    "For Partition <%s> and Topic <%s>.",
                                    partitionName, topicName);
                    }
                    c_free(ktopic);
                }
                ktopic = c_iterTakeFirst(topics);
                while (ktopic != NULL) {
                    c_free(ktopic);
                    ktopic = c_iterTakeFirst(topics);
                }
                c_iterFree(topics);
                r = u_entityRelease(u_entity(participant));
            } else {
                OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                            "Claim kernel participant failed."
                            "For Partition <%s> and Topic <%s>.",
                            partitionName, topicName);
            }
        } else {
            OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                        "No participant specified. "
                        "For Partition <%s> and Topic <%s>.",
                        partitionName, topicName);
        }
    } else {
        OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                    "Illegal parameter."
                    "partitionName = <0x%x>, topicName = <0x%x>.",
                    partitionName, topicName);
    }
    return group;
}
예제 #5
0
static void*
d_groupCreationQueueRun(
    void* userData)
{
    d_groupCreationQueue queue;
    c_iter groupsToCreate, reinsert;
    d_group group, localGroup;
    d_durability durability;
    d_durabilityKind kind;
    u_participant uservice;
    c_char *partition, *topic;
    v_duration duration;
    u_group ugroup;
    c_long creationCountVolatile, creationCountTransient, creationCountPersistent;
    c_ulong maxBurst;
    os_time sleepTime, maxBurstSleepTime;
    c_bool update;

    sleepTime.tv_sec          = 1;
    sleepTime.tv_nsec         = 0;
    duration.seconds          = 0;
    duration.nanoseconds      = 5000000; /*5ms*/
    creationCountVolatile     = 0;
    creationCountTransient    = 0;
    creationCountPersistent   = 0;
    maxBurstSleepTime.tv_sec  = 0;
    maxBurstSleepTime.tv_nsec = 10000000; /*10ms*/

    queue                = d_groupCreationQueue(userData);
    groupsToCreate       = c_iterNew(NULL);
    reinsert             = c_iterNew(NULL);
    durability           = d_adminGetDurability(queue->admin);
    uservice             = u_participant(d_durabilityGetService(durability));

    d_waitForCompletenessDCPSTopic(queue);

    while(queue->terminate == FALSE) {
        d_lockLock(d_lock(queue));

        queue->groupsToCreateVolatile -= creationCountVolatile;
        assert(queue->groupsToCreateVolatile >= 0);
        queue->groupsToCreateTransient -= creationCountTransient;
        assert(queue->groupsToCreateTransient >= 0);
        queue->groupsToCreatePersistent -= creationCountPersistent;
        assert(queue->groupsToCreatePersistent >= 0);

        group = d_group(c_iterTakeFirst(queue->groups));

        while(group){
            groupsToCreate = c_iterInsert(groupsToCreate, group);
            group = d_group(c_iterTakeFirst(queue->groups));
        }
        assert((queue->groupsToCreateVolatile +
                queue->groupsToCreateTransient +
                queue->groupsToCreatePersistent) ==
               c_iterLength(groupsToCreate));

        durability = d_adminGetDurability(queue->admin);
        d_durabilityUpdateStatistics(durability, d_statisticsUpdateGroupsToCreate, queue);

        d_lockUnlock(d_lock(queue));

        creationCountVolatile   = 0;
        creationCountTransient  = 0;
        creationCountPersistent = 0;
        maxBurst                = 10;

        group = c_iterTakeFirst(groupsToCreate);

        while(group && (queue->terminate == FALSE)){
            partition  = d_groupGetPartition(group);
            topic      = d_groupGetTopic(group);
            kind       = d_groupGetKind(group);
            localGroup = d_adminGetLocalGroup(queue->admin, partition, topic, kind);
            update     = FALSE;

            if(localGroup) {
                d_printTimedEvent(durability,
                            D_LEVEL_FINE,
                            D_THREAD_GROUP_CREATION,
                            "Remote group %s.%s has already been created locally.\n",
                            partition, topic);
                update = TRUE;
            } else {
                ugroup = u_groupNew(uservice, partition, topic, duration);

                if(ugroup){
                    d_printTimedEvent(durability,
                                    D_LEVEL_FINE,
                                    D_THREAD_GROUP_CREATION,
                                    "Remote group %s.%s created locally.\n",
                                    partition, topic);
                    update = TRUE;
                    u_entityFree(u_entity(ugroup));
                    maxBurst--;

                    if(maxBurst == 0){
                        os_nanoSleep(maxBurstSleepTime);
                        maxBurst = 10;
                    }
                } else {
                    maxBurst++;
                    d_printTimedEvent(durability, D_LEVEL_FINE,
                                D_THREAD_GROUP_CREATION,
                                "Remote group %s.%s could not be created locally.\n",
                                partition, topic);

                    if(d_durabilityGetState(durability) == D_STATE_COMPLETE){
                        d_printTimedEvent(durability, D_LEVEL_FINE,
                                D_THREAD_GROUP_CREATION,
                                "I am complete so it will not be available anymore.\n");
                        update = TRUE;
                    } else if(d_adminGetFellowCount(queue->admin) == 0){
                        d_printTimedEvent(durability, D_LEVEL_WARNING,
                                D_THREAD_GROUP_CREATION,
                                "No fellows available to provide me with group information. " \
                                "Ignoring group.\n",
                                partition, topic);
                        update = TRUE;
                    } else {
                        reinsert = c_iterInsert(reinsert, group);
                    }
                }
            }
            if(update){
                switch(d_groupGetKind(group)){
                case D_DURABILITY_VOLATILE:
                    creationCountVolatile++;
                    break;
                case D_DURABILITY_TRANSIENT:
                case D_DURABILITY_TRANSIENT_LOCAL:
                    creationCountTransient++;
                    break;
                case D_DURABILITY_PERSISTENT:
                    creationCountPersistent++;
                    break;
                default:
                    assert(FALSE);
                    break;
                }
                d_groupFree(group);
            }
            os_free(partition);
            os_free(topic);
            group = c_iterTakeFirst(groupsToCreate);
        }
        group = d_group(c_iterTakeFirst(reinsert));

        while(group){
            groupsToCreate = c_iterInsert(groupsToCreate, group);
            group = d_group(c_iterTakeFirst(reinsert));
        }
        if(queue->terminate == FALSE){
            os_nanoSleep(sleepTime);
        }
    }

    group = d_group(c_iterTakeFirst(groupsToCreate));

    while(group) {
        d_groupFree(group);
        group = d_group(c_iterTakeFirst(groupsToCreate));
    }
    c_iterFree(groupsToCreate);
    c_iterFree(reinsert);

    d_lockLock(d_lock(queue));
    group = d_group(c_iterTakeFirst(queue->groups));

    while(group) {
        d_groupFree(group);
        group = d_group(c_iterTakeFirst(queue->groups));
    }
    d_lockUnlock(d_lock(queue));

    return NULL;
}
예제 #6
0
파일: u_user.c 프로젝트: cynron/opensplice
u_result
u_userInitialise(
    void)
{
    u_user u;
    u_result rm = U_RESULT_OK;
    os_mutexAttr mutexAttr;
    os_uint32 initCount;
    void* initUser;
    os_result osResult;
    os_signalHandlerExitRequestCallback exitRequestCallback;
    os_signalHandlerExceptionCallback exceptionCallback;

    initCount = pa_increment(&_ospl_userInitCount);
    /* If initCount == 0 then an overflow has occurred.
     * This can only realistically happen when u_userDetach()
     * is called more often than u_userInitialize().
     */
    assert(initCount != 0);

    os_osInit();
    if (initCount == 1) {
        /* Will start allocating the object, so it should currently be empty. */
        assert(user == NULL);

        /* Use indirection, as user != NULL is a precondition for user-layer
         * functions, so make sure it only holds true when the user-layer is
         * initialized. */
        initUser = os_malloc(sizeof(C_STRUCT(u_user)));
        if (initUser == NULL) {
            /* Initialization failed, so decrement the initialization counter. */
            pa_decrement(&_ospl_userInitCount);
            os_osExit();
            OS_REPORT(OS_ERROR, "u_userInitialise", 0,
                      "Allocation of user admin failed: out of memory.");
            rm = U_RESULT_OUT_OF_MEMORY;
        } else {
            u = u_user(initUser);
            os_mutexAttrInit(&mutexAttr);
            mutexAttr.scopeAttr = OS_SCOPE_PRIVATE;
            os_mutexInit(&u->mutex,&mutexAttr);
            osResult = os_signalHandlerNew();
            if(osResult != os_resultSuccess)
            {
                /* Initialization did not succeed, undo increment and return error */
                initCount = pa_decrement(&_ospl_userInitCount);
                OS_REPORT(OS_ERROR, "u_userInitialise", 0,
                      "Failed to create the signal handler. No proper signal handling can be performed.");
                rm = U_RESULT_INTERNAL_ERROR;
            } else
            {
                exitRequestCallback = os_signalHandlerSetExitRequestCallback(u__userExitRequestCallbackWrapper);
                if(exitRequestCallback && exitRequestCallback != u__userExitRequestCallbackWrapper)
                {
                    initCount = pa_decrement(&_ospl_userInitCount);
                    OS_REPORT(OS_ERROR, "u_userInitialise", 0,
                        "Replaced an exit request callback on the signal handler while this was not expected.");
                    rm = U_RESULT_INTERNAL_ERROR;
                }
                if(rm == U_RESULT_OK){
                    exceptionCallback = os_signalHandlerSetExceptionCallback(u__userExceptionCallbackWrapper);
                    if(exceptionCallback && exceptionCallback != u__userExceptionCallbackWrapper)
                    {
                        initCount = pa_decrement(&_ospl_userInitCount);
                        OS_REPORT(OS_ERROR, "u_userInitialise", 0,
                            "Replaced an exception callback on the signal handler while this was not expected.");
                        rm = U_RESULT_INTERNAL_ERROR;
                    }
                }
                if(rm == U_RESULT_OK)
                {
                    u->domainCount = 0;
                    u->protectCount = 0;
                    u->detachThreadId = OS_THREAD_ID_NONE;

                    /* This will mark the user-layer initialized */
                    user = initUser;
                }
            }
        }
    } else {
        if(user == NULL){
            os_time sleep = {0, 100000}; /* 100ms */
            /* Another thread is currently initializing the user-layer. Since
             * user != NULL is a precondition for calls after u_userInitialise(),
             * a sleep is performed, to ensure that (if succeeded) successive
             * user-layer calls will also actually pass.*/
            os_nanoSleep(sleep);
        }

        if(user == NULL){
            /* Initialization did not succeed, undo increment and return error */
            initCount = pa_decrement(&_ospl_userInitCount);
            OS_REPORT_1(OS_ERROR,"u_userInitialise",0,
                        "Internal error: User-layer should be initialized "
                        "(initCount = %d), but user == NULL (waited 100ms).",
                        initCount);
            rm = U_RESULT_INTERNAL_ERROR;
        }
    }
    return rm;
}
예제 #7
0
파일: u_group.c 프로젝트: xrl/opensplice
u_group
u_groupNew(
    u_participant participant,
    const c_char *partitionName,
    const c_char *topicName,
    v_duration timeout)
{
    u_result r;
    v_participant kparticipant;
    v_kernel kernel;
    v_topic ktopic;
    v_partition kpartition;
    v_group kgroup;
    c_iter topics;
    os_time delay;
    u_group group = NULL;

    if ((partitionName != NULL) && (topicName != NULL)) {
        if (participant != NULL) {
            r = u_entityWriteClaim(u_entity(participant), (v_entity*)(&kparticipant));
            if (r == U_RESULT_OK){
                assert(kparticipant);
                kernel = v_objectKernel(kparticipant);
                topics = v_resolveTopics(kernel,topicName);
                if (c_iterLength(topics) == 0) {
                    c_iterFree(topics);
                    delay.tv_sec = timeout.seconds;
                    delay.tv_nsec = timeout.nanoseconds;
                    os_nanoSleep(delay);
                    topics = v_resolveTopics(v_objectKernel(kparticipant),
                                             topicName);
                }
                if (c_iterLength(topics) > 1) {
                    OS_REPORT_1(OS_WARNING, "u_groupNew", 0,
                                "Internal error: "
                                "Multiple topics found with name = <%s>.",
                                topicName);
                }
                ktopic = c_iterTakeFirst(topics);
                if (ktopic != NULL) {
                    kpartition = v_partitionNew(kernel, partitionName, NULL);
                    if (kpartition != NULL) {
                        kgroup = v_groupSetCreate(kernel->groupSet, kpartition, ktopic);
                        if (kgroup != NULL) {
                            group = u_groupCreate(kgroup, participant);
                            if (group == NULL) {
                                OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                                            "Create proxy failed. "
                                            "For Partition <%s> and Topic <%s>.",
                                            partitionName, topicName);
                            }
                            c_free(kgroup);
                        } else {
                            OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                                        "Create kernel entity failed. "
                                        "For Partition <%s> and Topic <%s>.",
                                        partitionName, topicName);
                        }
                        c_free(kpartition);
                    } else {
                        OS_REPORT_2(OS_ERROR,"u_groupNew", 0,
                                    "Failed to create partition. "
                                    "For Partition <%s> and Topic <%s>.",
                                    partitionName, topicName);
                    }
                    c_free(ktopic);
                }else {
                    OS_REPORT_2(OS_ERROR,"u_groupNew", 0,
                                    "Topic not (yet) known. "
                                    "For Partition <%s> and Topic <%s>.",
                                    partitionName, topicName);
                }
                ktopic = c_iterTakeFirst(topics);
                while (ktopic != NULL) {
                    c_free(ktopic);
                    ktopic = c_iterTakeFirst(topics);
                }
                c_iterFree(topics);
                r = u_entityRelease(u_entity(participant));
            } else {
                OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                            "Claim kernel participant failed."
                            "For Partition <%s> and Topic <%s>.",
                            partitionName, topicName);
            }
        } else {
            OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                        "No participant specified. "
                        "For Partition <%s> and Topic <%s>.",
                        partitionName, topicName);
        }
    } else {
        OS_REPORT_2(OS_ERROR,"u_groupNew",0,
                    "Illegal parameter."
                    "partitionName = <0x%x>, topicName = <0x%x>.",
                    partitionName, topicName);
    }
    return group;
}
예제 #8
0
static void
d_waitForCompletenessDCPSTopic(
    d_groupCreationQueue queue)
{
    d_group dcpstopicGroup;
    d_completeness completeness;
    d_admin admin;
    os_time sleepTime;
    d_durability durability;

    sleepTime.tv_sec  = 1;
    sleepTime.tv_nsec = 0;
    admin             = queue->admin;
    durability        = d_adminGetDurability(admin);

    d_printTimedEvent(durability,
                            D_LEVEL_FINE,
                            D_THREAD_GROUP_CREATION,
                            "Waiting for group '%s.%s' to be created.\n",
                            V_BUILTIN_PARTITION, V_TOPICINFO_NAME);

    do{
        dcpstopicGroup    = d_adminGetLocalGroup(admin,
                                    V_BUILTIN_PARTITION, V_TOPICINFO_NAME,
                                    D_DURABILITY_TRANSIENT);
        if((dcpstopicGroup == NULL) && (queue->terminate == FALSE)){
            os_nanoSleep(sleepTime);
        }
    } while((dcpstopicGroup == NULL) && (queue->terminate == FALSE));

    if(queue->terminate == FALSE){
        d_printTimedEvent(durability,
                                D_LEVEL_FINE,
                                D_THREAD_GROUP_CREATION,
                                "Group '%s.%s' is available. Waiting for completeness...\n",
                                V_BUILTIN_PARTITION, V_TOPICINFO_NAME);
    }

    do{
        if(dcpstopicGroup){
            completeness = d_groupGetCompleteness(dcpstopicGroup);

            if((completeness != D_GROUP_COMPLETE) && (queue->terminate == FALSE)){
                os_nanoSleep(sleepTime);
            }
        } else {
            completeness = D_GROUP_KNOWLEDGE_UNDEFINED;
        }
    } while((completeness != D_GROUP_COMPLETE) && (queue->terminate == FALSE));

    if(queue->terminate == FALSE){
        d_printTimedEvent(durability,
                                D_LEVEL_FINE,
                                D_THREAD_GROUP_CREATION,
                                "Group '%s.%s' is complete now.\n",
                                V_BUILTIN_PARTITION, V_TOPICINFO_NAME);
    } else {
        d_printTimedEvent(durability,
                                D_LEVEL_FINE,
                                D_THREAD_GROUP_CREATION,
                                "Not waiting for group '%s.%s', because termination is in progress.\n",
                                V_BUILTIN_PARTITION, V_TOPICINFO_NAME);
    }
    return;
}
예제 #9
0
int OSPL_MAIN (int argc, char *argv[])
{
   char* publisher_name;
   int i, sampleIndex, ownership_strength, nb_iteration;
   c_bool isStoppingSubscriber;
   float price;
   os_time os_delay200 = { 0, 200000000 };
   os_time os_delay2000 = { 2, 0 };


   DDS_Publisher OwnershipDataPublisher;
   DDS_DataWriter OwnershipDataDataWriter;
   OwnershipData_Stock* OwnershipDataSample;
   DDS_InstanceHandle_t userHandle;
   const char ticker [] = "MSFT";
   DDS_unsigned_long stringLength = sizeof(ticker) - 1;

   // usage : Publisher.exe <publisher_name> <ownership_strength> <nb_iterations>
   if( argc < 5 )
   {
      usage();
   }
   printf("\n\n Starting OwnershipDataPublisher...");
   printf("\n\n Parameters are:");
   for( i = 1; i < argc ; ++i )
   {
      printf("\n %d: %s", i, argv[i]);
   }

   publisher_name = argv[1];
   ownership_strength = atoi(argv[2]);
   nb_iteration = atoi(argv[3]);
   isStoppingSubscriber =  argv[4][0] == '1' ? TRUE : FALSE;

   createParticipant("Ownership example");

   // Register Stock Topic's type in the DDS Domain.
   g_StockTypeSupport = (DDS_TypeSupport) OwnershipData_StockTypeSupport__alloc();
   checkHandle(g_StockTypeSupport, "OwnershipData_StockTypeSupport__alloc");
   registerStockType(g_StockTypeSupport);
   // Create Stock Topic in the DDS Domain.
   g_StockTypeName = OwnershipData_StockTypeSupport_get_type_name(g_StockTypeSupport);
   g_StockTopic = createTopic("StockTrackerExclusive", g_StockTypeName);
   DDS_free(g_StockTypeName);
   DDS_free(g_StockTypeSupport);

   // Create the Publisher's in the DDS Domain.
   OwnershipDataPublisher = createPublisher();

   // Request a Writer from the the Publisher.
   OwnershipDataDataWriter = createDataWriter(OwnershipDataPublisher, g_StockTopic, FALSE, ownership_strength);

   // Publish a Stock Sample reflecting the state of the Msg DataWriter.
   OwnershipDataSample = OwnershipData_Stock__alloc();

   OwnershipDataSample->ticker = DDS_string_alloc(stringLength);
   snprintf(OwnershipDataSample->ticker, stringLength + 1, "%s", ticker);
   OwnershipDataSample->price = 0.0;
   OwnershipDataSample->publisher = DDS_string_dup(publisher_name);
   OwnershipDataSample->strength = ownership_strength;

   userHandle = OwnershipData_StockDataWriter_register_instance(OwnershipDataDataWriter, OwnershipDataSample);

   //Publisher publishes the prices in dollars
   printf("\n=== [Publisher] Publisher %d with strength : ", ownership_strength);
   printf("\n / sending %d prices...", nb_iteration);
   // The subscriber should display the prices sent by the publisher with the highest ownership strength
   price = 10.0f;
   for( sampleIndex = 0; sampleIndex < nb_iteration ; ++sampleIndex )
   {
      OwnershipDataSample->price = price;
      writeStockSample(OwnershipDataDataWriter, userHandle, OwnershipDataSample);
      os_nanoSleep(os_delay200);
      price = price + 0.5f;
   }
   if( isStoppingSubscriber == TRUE )
   {
      // This special price gives the end signal to the Subscriber:
      OwnershipDataSample->price =  (DDS_float) -1.0f;
      writeStockSample(OwnershipDataDataWriter, userHandle, OwnershipDataSample);
   }
   // This to make sure the Subscriber will get all the Samples.
   os_nanoSleep(os_delay2000);

   OwnershipData_StockDataWriter_unregister_instance (OwnershipDataDataWriter, OwnershipDataSample, userHandle);


   // Cleanup DDS from the created Entities.
   deleteDataWriter(OwnershipDataPublisher, OwnershipDataDataWriter);
   deletePublisher(OwnershipDataPublisher);
   deleteTopic(g_StockTopic);
   deleteParticipant();

   // Cleanup C allocations,
   // recursively freeing the allocated structures and sequences using the OpenSplice API.
   DDS_free(OwnershipDataSample);

   // Print out an empty line, just to let behind a clean new line for the shell..
   printf("\n\r");
   return 0;
}
int main(int argc, char *argv[])
{
   char* partition_name = "ContentFilteredTopic example";
   char* publisher_name;
   int i, sampleIndex, nb_iteration;
   c_bool isStoppingSubscriber;
   float price;
   char* geTicker = "GE";
   int geTickerLength = strlen(geTicker);
   char* msftTicker = "MSFT";
   int msftTickerLength = strlen(msftTicker);
   os_time os_delay100 = { 0, 100000000 };
   os_time os_delay2000 = { 2, 0 };

   DDS_Publisher ContentFilteredTopicDataPublisher;
   DDS_DataWriter ContentFilteredTopicDataDataWriter;
   ContentFilteredTopicData_Stock* geStockSample;
   ContentFilteredTopicData_Stock* msftStockSample;
   DDS_InstanceHandle_t geInstanceHandle;
   DDS_InstanceHandle_t msftInstanceHandle;

   createParticipant( partition_name );

   // Register Stock Topic's type in the DDS Domain.
   g_StockTypeSupport = (DDS_TypeSupport) ContentFilteredTopicData_StockTypeSupport__alloc();
   checkHandle(g_StockTypeSupport, "ContentFilteredTopicData_StockTypeSupport__alloc");
   registerStockType(g_StockTypeSupport);
   // Create Stock Topic in the DDS Domain.
   g_StockTypeName = (char*) ContentFilteredTopicData_StockTypeSupport_get_type_name(g_StockTypeSupport);
   g_StockTopic = createTopic("StockTrackerExclusive", g_StockTypeName);
   DDS_free(g_StockTypeName);
   DDS_free(g_StockTypeSupport);

   // Create the Publisher's in the DDS Domain.
   ContentFilteredTopicDataPublisher = createPublisher();

   // Request a Writer from the the Publisher.
   ContentFilteredTopicDataDataWriter = createDataWriter(ContentFilteredTopicDataPublisher, g_StockTopic, FALSE);

   // Publish a Stock Sample reflecting the state of the Msg DataWriter.
   geStockSample = ContentFilteredTopicData_Stock__alloc();
   msftStockSample = ContentFilteredTopicData_Stock__alloc();

   msftStockSample->ticker = DDS_string_alloc(msftTickerLength);
   snprintf(msftStockSample->ticker, msftTickerLength + 1, "%s", msftTicker);
   msftStockSample->price = 25.00f;

   geStockSample->ticker = DDS_string_alloc(geTickerLength);
   snprintf(geStockSample->ticker, geTickerLength + 1, "%s", geTicker);
   geStockSample->price = 12.00f;

   geInstanceHandle = ContentFilteredTopicData_StockDataWriter_register_instance(ContentFilteredTopicDataDataWriter, geStockSample);
   msftInstanceHandle = ContentFilteredTopicData_StockDataWriter_register_instance(ContentFilteredTopicDataDataWriter, msftStockSample);  

   nb_iteration = 20;

   printf("=== ContentFilteredTopicDataPublisher");

   // The subscriber should display the prices sent by the publisher with the highest ownership strength
   sampleIndex = 0;
   do
   {
      printf("\n=== [ContentFilteredTopicDataPublisher] sends 2 stockQuotes : (GE, %.1f) (MSFT, %.1f)", geStockSample->price, msftStockSample->price);
      writeStockSample(ContentFilteredTopicDataDataWriter, geInstanceHandle, geStockSample);
      writeStockSample(ContentFilteredTopicDataDataWriter, msftInstanceHandle, msftStockSample);
      geStockSample->price += 0.5;
      msftStockSample->price += 1.5;
      os_nanoSleep(os_delay100);
   }
   while( ++sampleIndex < nb_iteration );

   // This special price gives the end signal to the Subscriber:
   // signal to terminate
   geStockSample->price =  -1.0f;
   msftStockSample->price =  -1.0f;
   writeStockSample(ContentFilteredTopicDataDataWriter, geInstanceHandle, geStockSample);
   writeStockSample(ContentFilteredTopicDataDataWriter, msftInstanceHandle, msftStockSample);

   // This to make sure the Subscriber will get all the Samples.
   os_nanoSleep(os_delay2000);

   printf("\nMarket Closed\n");

   ContentFilteredTopicData_StockDataWriter_unregister_instance(ContentFilteredTopicDataDataWriter, geStockSample, geInstanceHandle);
   ContentFilteredTopicData_StockDataWriter_unregister_instance(ContentFilteredTopicDataDataWriter, msftStockSample, msftInstanceHandle);



   // Cleanup DDS from the created Entities.
   deleteDataWriter(ContentFilteredTopicDataPublisher, ContentFilteredTopicDataDataWriter);
   deletePublisher(ContentFilteredTopicDataPublisher);
   deleteTopic(g_StockTopic);
   deleteParticipant();

   // Cleanup C allocations,
   // recursively freeing the allocated structures and sequences using the OpenSplice API.
   DDS_free(geStockSample);
   DDS_free(msftStockSample);

   // Print out an empty line, just to let behind a clean new line for the shell..
   // Removed to comply with expected results
   //printf("\n\r");
   return 0;
}
int OSPL_MAIN (int argc, char *argv[])
{
   int sampleIndex, nb_iteration;
   const char geTicker [] = "GE";
   DDS_unsigned_long geTickerLength = sizeof(geTicker) - 1;
   const char msftTicker [] = "MSFT";
   DDS_unsigned_long msftTickerLength = sizeof(msftTicker) - 1;
   os_time os_delay100 = { 0, 100000000 };
   os_time os_delay2000 =  { 2, 0 };

   DDS_Publisher QueryConditionDataPublisher;
   DDS_DataWriter QueryConditionDataDataWriter;
   StockMarket_Stock* geStockSample;
   StockMarket_Stock* msftStockSample;
   DDS_InstanceHandle_t geInstanceHandle;
   DDS_InstanceHandle_t msftInstancetHandle;

   createParticipant("QueryCondition example");

   // Register Stock Topic's type in the DDS Domain.
   g_StockTypeSupport = (DDS_TypeSupport) StockMarket_StockTypeSupport__alloc();
   checkHandle(g_StockTypeSupport, "StockMarket_StockTypeSupport__alloc");
   registerStockType(g_StockTypeSupport);
   // Create Stock Topic in the DDS Domain.
   g_StockTypeName = StockMarket_StockTypeSupport_get_type_name(g_StockTypeSupport);
   g_StockTopic = createTopic("StockTrackerExclusive", g_StockTypeName);
   DDS_free(g_StockTypeName);
   DDS_free(g_StockTypeSupport);

   // Create the Publisher's in the DDS Domain.
   QueryConditionDataPublisher = createPublisher();

   // Request a Writer from the the Publisher.
   QueryConditionDataDataWriter = createDataWriter(QueryConditionDataPublisher, g_StockTopic, FALSE);

   // Publish a Stock Sample reflecting the state of the Msg DataWriter.
   geStockSample = StockMarket_Stock__alloc();
   msftStockSample = StockMarket_Stock__alloc();

   msftStockSample->ticker = DDS_string_alloc(msftTickerLength);
   snprintf(msftStockSample->ticker, msftTickerLength + 1, "%s", msftTicker);
   msftStockSample->price = 12.00f;

   geStockSample->ticker = DDS_string_alloc(geTickerLength);
   snprintf(geStockSample->ticker, geTickerLength + 1, "%s", geTicker);
   geStockSample->price = 25.00f;

   geInstanceHandle = StockMarket_StockDataWriter_register_instance(QueryConditionDataDataWriter, geStockSample);
   msftInstancetHandle = StockMarket_StockDataWriter_register_instance(QueryConditionDataDataWriter, msftStockSample);

   nb_iteration = 20;
   // The subscriber should display the prices sent by the publisher with the highest ownership strength
   for( sampleIndex = 0; sampleIndex < nb_iteration ; ++sampleIndex )
   {
      printf("GE : %.1f MSFT : %.1f\n", geStockSample->price, msftStockSample->price);
      writeStockSample(QueryConditionDataDataWriter, geInstanceHandle, geStockSample);
      writeStockSample(QueryConditionDataDataWriter, msftInstancetHandle, msftStockSample);
      geStockSample->price += 0.5;
      msftStockSample->price += 1.5;

      os_nanoSleep(os_delay100);
   }

   // This special price gives the end signal to the Subscriber:
   // signal to terminate
   geStockSample->price =  -1.0f;
   msftStockSample->price =  -1.0f;
   writeStockSample(QueryConditionDataDataWriter, geInstanceHandle, geStockSample);
   writeStockSample(QueryConditionDataDataWriter, msftInstancetHandle, msftStockSample);

   // This to make sure the Subscriber will get all the Samples.
   os_nanoSleep(os_delay2000);
   printf("Market Closed");

   StockMarket_StockDataWriter_unregister_instance (QueryConditionDataDataWriter, geStockSample, geInstanceHandle);
   StockMarket_StockDataWriter_unregister_instance (QueryConditionDataDataWriter, msftStockSample, msftInstancetHandle);

   // Cleanup DDS from the created Entities.
   deleteDataWriter(QueryConditionDataPublisher, QueryConditionDataDataWriter);
   deletePublisher(QueryConditionDataPublisher);
   deleteTopic(g_StockTopic);
   deleteParticipant();

   // Cleanup C allocations,
   // recursively freeing the allocated structures and sequences using the OpenSplice API.
   DDS_free(geStockSample);
   DDS_free(msftStockSample);

   // Print out an empty line, just to let behind a clean new line for the shell..
   printf("\n\r");
   return 0;
}
예제 #12
0
int OSPL_MAIN (int argc, const char *argv[])
{
   os_time os_delay_500ms = {  0, 500000000  };
   os_time os_delay_200ms =  {  0, 200000000  };
   DDS_boolean autodispose_unregistered_instances = FALSE;

   DDS_Publisher msgPublisher;
   DDS_DataWriter msgWriter;
   DDS_DataWriter msgWriter_stopper;

   DDS_unsigned_long messageLength;
   LifecycleData_Msg *sample_Msg;

   printf("\n\n Starting LifecyclePublisher...");

   if( argc < 3 )
   {
      usage();
   }
   if ((strcmp(argv[1], "false") != 0) &&
     (strcmp(argv[1], "true") != 0) &&
     (strcmp(argv[2], "dispose") != 0) &&
     (strcmp(argv[2], "unregister") != 0) &&
     (strcmp(argv[2], "stoppub") != 0))
   {
    usage();
   }

   autodispose_unregistered_instances = (strcmp(argv[1], "true") == 0);

   // First initialize the Topics and their DDS Entities

   // Create DDS DomainParticipant
   createParticipant("Lifecycle example");

   //------------------ Msg topic --------------------//

   // Register Msg Topic's type in the DDS Domain.
   g_msgTypeSupport = LifecycleData_MsgTypeSupport__alloc();
   checkHandle(g_msgTypeSupport, "LifecycleData_MsgTypeSupport__alloc");
   registerMsgType(g_msgTypeSupport);
   // Create Msg Topic in the DDS Domain.
   g_msgTypeName = LifecycleData_MsgTypeSupport_get_type_name(g_msgTypeSupport);
   g_msgTopic = createTopic("Lifecycle_Msg", g_msgTypeName);
   DDS_free(g_msgTypeName);
   DDS_free(g_msgTypeSupport);

   // Create the Publisher's in the DDS Domain.
   msgPublisher = createPublisher();

   // Request a Writer from the the Publisher.
   msgWriter = createDataWriter(msgPublisher, g_msgTopic, autodispose_unregistered_instances);
   msgWriter_stopper = createDataWriter(msgPublisher, g_msgTopic, autodispose_unregistered_instances);
   //End initialization.
   os_nanoSleep(os_delay_200ms);

   // Start publishing...
   printf("\n=== [Publisher] Ready...");

  if (strcmp(argv[2], "dispose") == 0)
      {
        // Publish a Msg Sample and dispose the instance
         LifecycleData_Msg *sample_Msg = LifecycleData_Msg__alloc();
        sample_Msg->userID = 1;
        messageLength = sizeof("Lifecycle_1") - 1;
        sample_Msg->message = DDS_string_alloc(messageLength);
        snprintf(sample_Msg->message, messageLength + 1, "%s", "Lifecycle_1");
        messageLength = sizeof("SAMPLE_SENT -> INSTANCE_DISPOSED -> DATAWRITER_DELETED") - 1;
        sample_Msg->writerStates = DDS_string_alloc(messageLength);
        snprintf(sample_Msg->writerStates, messageLength + 1, "%s", "SAMPLE_SENT -> INSTANCE_DISPOSED -> DATAWRITER_DELETED");
        printf("\n=== [Publisher]  :");
        printf("\n    userID  : %d", sample_Msg->userID);
        printf("\n    Message : %s", sample_Msg->message);
        printf("\n    writerStates : %s", sample_Msg->writerStates);
        g_status = LifecycleData_MsgDataWriter_write(msgWriter, sample_Msg, DDS_HANDLE_NIL);
        checkStatus(g_status, "MsgDataWriter_write");
        os_nanoSleep(os_delay_500ms);
        printf("\n=== [Publisher]  : SAMPLE_SENT");
        fflush(stdout);
        // Dispose instance
        g_status = LifecycleData_MsgDataWriter_dispose(msgWriter, sample_Msg, DDS_HANDLE_NIL);
        checkStatus(g_status, "LifecycleData_MsgDataWriter_dispose");
        printf("\n=== [Publisher]  : INSTANCE_DISPOSED");
        fflush(stdout);
        // OpenSplice will recursively free the content of the sample,
        // provided it has all been allocated through the DDS_xxxx_alloc API...
        DDS_free(sample_Msg);

      }
    else if (strcmp(argv[2], "unregister") == 0)
      {

        // Publish a Msg Sample and unregister the instance
        LifecycleData_Msg *sample_Msg = LifecycleData_Msg__alloc();
        sample_Msg->userID = 1;
        messageLength = sizeof("Lifecycle_2") - 1;
        sample_Msg->message = DDS_string_alloc(messageLength);
        snprintf(sample_Msg->message, messageLength + 1, "%s", "Lifecycle_2");
        messageLength = sizeof("SAMPLE_SENT -> INSTANCE_UNREGISTERED -> DATAWRITER_DELETED") - 1;
        sample_Msg->writerStates = DDS_string_alloc(messageLength);
        snprintf(sample_Msg->writerStates, messageLength + 1, "%s", "SAMPLE_SENT -> INSTANCE_UNREGISTERED -> DATAWRITER_DELETED");
        printf("\n=== [Publisher]  :");
        printf("\n    userID  : %d", sample_Msg->userID);
        printf("\n    Message : %s", sample_Msg->message);
        printf("\n    writerStates : %s", sample_Msg->writerStates);
        g_status = LifecycleData_MsgDataWriter_write(msgWriter, sample_Msg, DDS_HANDLE_NIL);
        checkStatus(g_status, "MsgDataWriter_write");
        os_nanoSleep(os_delay_500ms);
        printf("\n=== [Publisher]  : SAMPLE_SENT");
        fflush(stdout);
        // Unregister instance : the auto_dispose_unregistered_instances flag
        // is currently ignored and the instance is never disposed automatically
        g_status = LifecycleData_MsgDataWriter_unregister_instance(msgWriter, sample_Msg, 0);
        checkStatus(g_status, "LifecycleData_MsgDataWriter_unregister_instance");
        printf("\n=== [Publisher]  : INSTANCE_UNREGISTERED");
        fflush(stdout);
        // OpenSplice will recursively free the content of the sample,
        // provided it has all been allocated through the DDS_xxxx_alloc API...
        DDS_free(sample_Msg);
      }
    else if (strcmp(argv[2], "stoppub") == 0)
      {
        // Publish a Msg Sample
        LifecycleData_Msg *sample_Msg = LifecycleData_Msg__alloc();
        sample_Msg->userID = 1;
        messageLength = sizeof("Lifecycle_3") - 1;
        sample_Msg->message = DDS_string_alloc(messageLength);
        snprintf(sample_Msg->message, messageLength + 1, "%s", "Lifecycle_3");
        messageLength = sizeof("SAMPLE_SENT -> DATAWRITER_DELETED") - 1;
        sample_Msg->writerStates = DDS_string_alloc(messageLength);
        snprintf(sample_Msg->writerStates, messageLength + 1, "%s", "SAMPLE_SENT -> DATAWRITER_DELETED");
        printf("\n=== [Publisher]  :");
        printf("\n    userID  : %d", sample_Msg->userID);
        printf("\n    Message : %s", sample_Msg->message);
        printf("\n    writerStates : %s", sample_Msg->writerStates);
        g_status = LifecycleData_MsgDataWriter_write(msgWriter, sample_Msg, DDS_HANDLE_NIL);
        checkStatus(g_status, "MsgDataWriter_write");
        os_nanoSleep(os_delay_500ms);
        printf("\n=== [Publisher]  : SAMPLE_SENT");
        fflush(stdout);
        // OpenSplice will recursively free the content of the sample,
        // provided it has all been allocated through the DDS_xxxx_alloc API...
        DDS_free(sample_Msg);
      }
   // let the subscriber treat the previous writer state !!!!
   printf("\n=== [Publisher] waiting 500ms to let the subscriber treat the previous write state ...");
   fflush(stdout);
   os_nanoSleep(os_delay_500ms);

   /* Remove the DataWriters */
   deleteDataWriter(msgPublisher, &msgWriter);
   printf("\n=== [Publisher]  : DATAWRITER_DELETED");
   fflush(stdout);
   os_nanoSleep(os_delay_500ms);
   printf("\n=== [Publisher]  : Sending a message to stop the subscriber");
   /* send a Msg sample to stop the subscriber */
   sample_Msg = LifecycleData_Msg__alloc();
   sample_Msg->userID = 1;
   messageLength = sizeof("Lifecycle_4") - 1;
   sample_Msg->message = DDS_string_alloc(messageLength);
   snprintf(sample_Msg->message, messageLength + 1, "%s", "Lifecycle_4");
   messageLength = sizeof("STOPPING_SUBSCRIBER") - 1;
   sample_Msg->writerStates = DDS_string_alloc(messageLength);
   snprintf(sample_Msg->writerStates, messageLength + 1, "%s", "STOPPING_SUBSCRIBER");
   printf("\n=== [Publisher]  :");
   printf("\n    userID  : %d", sample_Msg->userID);
   printf("\n    Message : %s", sample_Msg->message);
   printf("\n    writerStates : %s\n", sample_Msg->writerStates);
   g_status = LifecycleData_MsgDataWriter_write(msgWriter_stopper, sample_Msg, DDS_HANDLE_NIL);
   checkStatus(g_status, "MsgDataWriter_write");
   fflush(stdout);
   os_nanoSleep(os_delay_500ms);
   // OpenSplice will recursively free the content of the sample,
   // provided it has all been allocated through the DDS_xxxx_alloc API...
   DDS_free(sample_Msg);
   /* Remove the DataWriter */
   deleteDataWriter(msgPublisher, &msgWriter_stopper);

   // Cleanup DDS from the created Entities.
   deletePublisher(&msgPublisher);
   deleteTopic(g_msgTopic);
   deleteParticipant();

   return 0;
}
예제 #13
0
int main(int argc, char *argv[])
{
   DDS_Subscriber OwnershipDataSubscriber;
   DDS_DataReader OwnershipDataDataReader;
   OwnershipData_Stock* OwnershipDataSample;
   DDS_InstanceHandle_t userHandle;
   DDS_sequence_OwnershipData_Stock* msgList = DDS_sequence_OwnershipData_Stock__alloc();
   DDS_SampleInfoSeq* infoSeq = DDS_SampleInfoSeq__alloc();
   c_bool isClosed;
   int count = 0;
   unsigned long j, userInput, timeOut;
   os_time os_delay200 = { 0, 200000000 };

   printf("\n\n Starting LifecycleSubscriber...");

   createParticipant("Ownership example");

   // Register Stock Topic's type in the DDS Domain.
   g_StockTypeSupport = (DDS_TypeSupport) OwnershipData_StockTypeSupport__alloc();
   checkHandle(g_StockTypeSupport, "OwnershipData_StockTypeSupport__alloc");
   registerStockType(g_StockTypeSupport);
   // Create Stock Topic in the DDS Domain.
   g_StockTypeName = (char*) OwnershipData_StockTypeSupport_get_type_name(g_StockTypeSupport);
   g_StockTopic = createTopic("StockTrackerExclusive", g_StockTypeName);
   DDS_free(g_StockTypeName);
   DDS_free(g_StockTypeSupport);

   // Create the Subscriber's in the DDS Domain.
   OwnershipDataSubscriber = createSubscriber();

   // Request a Reader from the the Subscriber.
   OwnershipDataDataReader = createDataReader(OwnershipDataSubscriber, g_StockTopic);

   printf("\n\n ===[OwnershipDataSubscriber] Ready...");
   printf("\n\n    Ticker   Price   Publisher   ownership strength");
   isClosed = FALSE;

   do
   {
      g_status = OwnershipData_StockDataReader_take(OwnershipDataDataReader, msgList, infoSeq, 1, DDS_ANY_SAMPLE_STATE, DDS_ANY_VIEW_STATE, DDS_ANY_INSTANCE_STATE);
      checkStatus(g_status, "OwnershipData_StockDataReaderView_take");
      if( msgList->_length > 0 )
      {
         j = 0;
         do
         {
            OwnershipDataSample = &msgList->_buffer[j];
            // When is this supposed to happen?
            // Needs comment...
            if( infoSeq->_buffer[j].valid_data )
            {
               printf("\n   %s %8.1f    %s        %d", OwnershipDataSample->ticker, OwnershipDataSample->price, OwnershipDataSample->publisher, OwnershipDataSample->strength);
               if( OwnershipDataSample->price == (DDS_float) -1.0f )
               {
                  printf("\n ===[OwnershipDataSubscriber] OwnershipDataSample->price == -1.0f ");
                  isClosed = TRUE;
               }
            }
         }
         while( ++j < msgList->_length );

         g_status = OwnershipData_StockDataReader_return_loan(OwnershipDataDataReader, msgList, infoSeq);
         checkStatus(g_status, "OwnershipData_StockDataReaderView_return_loan");
      }

      os_nanoSleep(os_delay200);
      ++count;
   }
   while( isClosed == FALSE && count < 1500 );

   printf("\n\n ===[OwnershipDataSubscriber] Market closed");

   // Cleanup DDS from the created Entities.
   deleteDataReader(OwnershipDataSubscriber, OwnershipDataDataReader);
   deleteSubscriber(OwnershipDataSubscriber);
   deleteTopic(g_StockTopic);
   deleteParticipant();

   // Cleanup C allocations,
   // recursively freeing the allocated structures and sequences using the OpenSplice API.
   DDS__free(msgList);
   DDS__free(infoSeq);

   // Print out an empty line, just to let behind a clean new line for the shell..
   printf("\n\r");
   return 0;
}
예제 #14
0
int OSPL_MAIN (int argc, const char *argv[])
{
   DDS_Publisher message_Publisher;
   DDS_DataWriter message_DataWriter;
   WaitSetData_Msg* message_Sample;
   const DDS_char firstHello[] = "First Hello";
   DDS_unsigned_long firstHelloLength = sizeof(firstHello) - 1;
   const DDS_char helloAgain[] = "Hello again";
   DDS_unsigned_long helloAgainLength = sizeof(helloAgain) - 1;
   os_time os_delay300ms = { 0, 300000000 };

   printf("\n Starting WaitSetDataPublisher...");

   // Create DDS DomainParticipant
   printf("\n create Participant...");
   createParticipant("WaitSet example");

   // Register the Topic's type in the DDS Domain.
   g_MessageTypeSupport = WaitSetData_MsgTypeSupport__alloc();
   checkHandle(g_MessageTypeSupport, "WaitSetData_MsgTypeSupport__alloc");
   registerMessageType(g_MessageTypeSupport);
   // Create the Topic's in the DDS Domain.
   g_MessageTypeName = WaitSetData_MsgTypeSupport_get_type_name(g_MessageTypeSupport);
   g_MessageTopic = createTopic("WaitSetData_Msg", g_MessageTypeName);
   DDS_free(g_MessageTypeName);
   DDS_free(g_MessageTypeSupport);

   // Create the Publisher's in the DDS Domain.
   message_Publisher = createPublisher();

   // Request a Writer from the the Publisher.
   message_DataWriter = createDataWriter(message_Publisher, g_MessageTopic);

   message_Sample = WaitSetData_Msg__alloc();
   message_Sample->userID = 1;
   message_Sample->message = DDS_string_alloc(firstHelloLength);
   strncpy(message_Sample->message, firstHello, firstHelloLength);

   printf("\n=== [WaitSetDataPublisher] writing a message containing :");
   printf("\n    userID  : %d", message_Sample->userID);
   printf("\n    Message : \"%s\"", message_Sample->message);

   g_status = WaitSetData_MsgDataWriter_write(message_DataWriter, message_Sample, DDS_HANDLE_NIL);
   checkStatus(g_status, "WaitSetData_MsgDataWriter_write");
   DDS_free(message_Sample->message);

   // Let the time for the new StatusCondition to be handled by the Subscriber.
   os_nanoSleep(os_delay300ms);

   message_Sample->message = DDS_string_alloc(helloAgainLength);
   strncpy(message_Sample->message, helloAgain, helloAgainLength);

   printf("\n=== [WaitSetDataPublisher] writing a message containing :");
   printf("\n    userID  : %d", message_Sample->userID);
   printf("\n    Message : \"%s\"", message_Sample->message);

   g_status = WaitSetData_MsgDataWriter_write(message_DataWriter, message_Sample, DDS_HANDLE_NIL);
   checkStatus(g_status, "WaitSetData_MsgDataWriter_write");
   // This time, no need to free message_Sample->message as it will be freed by DDS_free(message_Sample);

   // Let the time for the new StatusCondition to be handled by the Subscriber.
   os_nanoSleep(os_delay300ms);

   printf("\n=== [WaitSetDataPublisher] Exiting.\n\n");

   // Cleanup DDS
   deleteDataWriter(message_Publisher, message_DataWriter);

   // Let the time for the new StatusCondition to be handled by the Subscriber.
   os_nanoSleep(os_delay300ms);

   deletePublisher(message_Publisher);
   deleteTopic(g_MessageTopic);
   deleteParticipant();

   // Cleanup C allocations
   DDS_free(message_Sample);
   return 0;
}
예제 #15
0
파일: ddsi.c 프로젝트: diorahman/opensplice
void
in_serviceMain(
    const os_char* serviceName,
    const os_char* uri)
{
    u_service service;
    in_config config;
    in_result result;
    u_serviceManager serviceManager;
    in_controller controller;
    v_duration leasePeriod;
    os_time sleepTime;
    os_boolean terminate = OS_FALSE;
    in_connectivityAdmin admin;

    assert(serviceName);
    assert(uri);

    /* Create networking service with kernel */
    service = u_serviceNew(
        uri,
        IN_ATTACH_TIMEOUT,
        serviceName,
        NULL,
        U_SERVICE_NETWORKING,
        NULL);
    assert(service);
    /* Initialize configuration */
    config = in_configGetInstance();
    result = in_configConvertDomTree(config, uri, service);
    if(result == IN_RESULT_OK)
    {
        /* Ask service manager for splicedaemon state */
        serviceManager = u_serviceManagerNew(u_participant(service));

        admin = in_connectivityAdminGetInstance();
        /* Create the controller which starts the updating */
        controller = in_controllerNew(service);
        if (controller)
        {
            /* Start the actual engine */
            IN_REPORT_INFO(1, "DDSI networking started");
            IN_TRACE(Mainloop, 1, "DDSI networking started");
            in_controllerStart(controller);
            /* Change state for spliced */
            u_serviceChangeState(service, STATE_INITIALISING);
            u_serviceChangeState(service, STATE_OPERATIONAL);
            /* Get sleeptime from configuration */
            in_retrieveLeaseSettings(&leasePeriod, &sleepTime);

            u_serviceRenewLease(service, leasePeriod);
            /* Loop until termination is requested */
            u_serviceWatchSpliceDaemon(
                service,
                in_splicedaemonListener,
                &terminate);
            /* terminate flag is modified by the splice deamon listener thread*/
            while (!terminate)
            {
                /* Assert my liveliness and the Splicedaemon's liveliness */
                u_serviceRenewLease(service, leasePeriod);
                /* Wait before renewing again */
                os_nanoSleep(sleepTime);
            }
            leasePeriod.seconds = 20;
            u_serviceRenewLease(service, leasePeriod);
            u_serviceChangeState(service, STATE_TERMINATING);
            in_controllerStop(controller);
            in_controllerFree(controller);
            IN_REPORT_INFO(1, "DDSI networking stopped");
            IN_TRACE(Mainloop, 1, "DDSI networking stopped");
        }
        u_serviceChangeState(service, STATE_TERMINATED);
		u_serviceManagerFree(serviceManager);
		in_objectFree(in_object(admin));
    }
    /* Clean up */
    in_configFree(config);
    u_serviceFree(service);
}