void wait_match(const DataReader_var& dr, int n)
{
  StatusCondition_var condition = dr->get_statuscondition();
  condition->set_enabled_statuses(SUBSCRIPTION_MATCHED_STATUS);
  WaitSet_var ws = new DDS::WaitSet;
  ws->attach_condition(condition);
  ConditionSeq conditions;
  SubscriptionMatchedStatus ms = {0, 0, 0, 0, 0};
  const Duration_t timeout = {1, 0};
  while (dr->get_subscription_matched_status(ms) == RETCODE_OK
         && ms.current_count != n) {
    ws->wait(conditions, timeout);
  }
  ws->detach_condition(condition);
}
bool waitForSample(const DataReader_var& dr)
{
  ReadCondition_var dr_rc = dr->create_readcondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, ALIVE_INSTANCE_STATE);
  WaitSet_var ws = new WaitSet;
  ws->attach_condition(dr_rc);
  Duration_t infinite = {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC};
  ConditionSeq active;
  ReturnCode_t ret = ws->wait(active, infinite);
  ws->detach_condition(dr_rc);
  dr->delete_readcondition(dr_rc);
  if (ret != RETCODE_OK) {
    cout << "ERROR: wait(rc) failed" << endl;
    return false;
  }
  return true;
}
Beispiel #3
0
bool DDSBroker::setListener(std::string topicName, DDS::DataReaderListener_var listener)
{
  DataReader_var reader = getReader(topicName);
  if (!reader.in())
  {
    ROS_ERROR("[DDS] Failed to get reader on topic %s.", topicName.c_str());
    return false;
  }

  // set a callback listener
  DDS::ReturnCode_t status;
  DDS::StatusMask mask = DDS::DATA_AVAILABLE_STATUS;
  status = reader->set_listener(listener, mask);
  if (status != DDS::RETCODE_OK)
  {
    ROS_ERROR("[DDS] Failed to set a listener on topic %s (%s).", topicName.c_str(), RETCODE_DESC(status));
    return false;
  }

  ROS_INFO("[DDS] DDSListener on %s is ready...", topicName.c_str());

  return true;
}
bool run_filtering_test(const DomainParticipant_var& dp,
  const MessageTypeSupport_var& ts, const Publisher_var& pub,
  const Subscriber_var& sub)
{
  DataWriter_var dw;
  DataReader_var dr;
  test_setup(dp, ts, pub, sub, "MyTopic2", dw, dr);

  MessageDataWriter_var mdw = MessageDataWriter::_narrow(dw);
  Message sample;
  sample.key = 1;
  ReturnCode_t ret = mdw->write(sample, HANDLE_NIL);
  if (ret != RETCODE_OK) return false;
  if (!waitForSample(dr)) return false;

  ReadCondition_var dr_qc = dr->create_querycondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, ALIVE_INSTANCE_STATE, "key > 1", DDS::StringSeq());
  if (!dr_qc.in()) {
    cout << "ERROR: failed to create QueryCondition" << endl;
    return false;
  }
  WaitSet_var ws = new WaitSet;
  ws->attach_condition(dr_qc);
  ConditionSeq active;
  Duration_t three_sec = {3, 0};
  ret = ws->wait(active, three_sec);
  // expect a timeout because the sample doesn't match the query string
  if (ret != RETCODE_TIMEOUT) {
    cout << "ERROR: wait(qc) should have timed out" << endl;
    return false;
  }
  ws->detach_condition(dr_qc);

  MessageDataReader_var mdr = MessageDataReader::_narrow(dr);
  MessageSeq data;
  SampleInfoSeq infoseq;
  ret = mdr->take_w_condition(data, infoseq, LENGTH_UNLIMITED, dr_qc);
  if (ret != RETCODE_NO_DATA) {
    cout << "ERROR: take_w_condition(qc) shouldn't have returned data" << endl;
    return false;
  }

  SampleInfo info;
  if (mdr->take_next_sample(sample, info) != RETCODE_OK) {
    cout << "ERROR: take_next_sample() should have returned data" << endl;
    return false;
  }

  sample.key = 2;
  if (mdw->write(sample, HANDLE_NIL) != RETCODE_OK) return false;
  if (!waitForSample(dr)) return false;

  ws->attach_condition(dr_qc);
  ret = ws->wait(active, three_sec);
  if (ret != RETCODE_OK) {
    cout << "ERROR: wait(qc) should not time out" << endl;
    return false;
  }
  ws->detach_condition(dr_qc);

  ret = mdr->take_w_condition(data, infoseq, LENGTH_UNLIMITED, dr_qc);
  if (ret != RETCODE_OK) {
    cout << "ERROR: take_w_condition(qc) should have returned data" << endl;
    return false;
  }

  dr->delete_readcondition(dr_qc);
  return true;
}
bool run_sorting_test(const DomainParticipant_var& dp,
  const MessageTypeSupport_var& ts, const Publisher_var& pub,
  const Subscriber_var& sub)
{
  DataWriter_var dw;
  DataReader_var dr;
  test_setup(dp, ts, pub, sub, "MyTopic", dw, dr);

  ReturnCode_t ret = RETCODE_OK;
  MessageDataWriter_var mdw = MessageDataWriter::_narrow(dw);
  Message sample;
  sample.key = 0;
  sample.name = "data_X";
  sample.nest.value = B;
  for (int i(0); i < 20; ++i, ++sample.key) {
    //replace the 'X' with a random letter
    sample.name.inout()[5] = static_cast<char>((rand() % 26) + 'A');
    ret = mdw->write(sample, HANDLE_NIL);
    if (ret != RETCODE_OK) return false;
    if (!(i % 4)) { //once in a while write more than 1 sample per instance
      Message sample2(sample);
      sample2.nest.value = A;
      sample2.name.inout()[5] = static_cast<char>((rand() % 26) + 'A');
      ret = mdw->write(sample2, HANDLE_NIL);
      if (ret != RETCODE_OK) return false;
      sample2.nest.value = C;
      ret = mdw->write(sample2, HANDLE_NIL);
      if (ret != RETCODE_OK) return false;
    }
  }

  DDS::StringSeq empty_query_params;
  ReadCondition_var dr_qc = dr->create_querycondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, ALIVE_INSTANCE_STATE, "ORDER BY name, nest.value",
    empty_query_params);
  WaitSet_var ws = new WaitSet;
  ws->attach_condition(dr_qc);
  MessageDataReader_var mdr = MessageDataReader::_narrow(dr);
  Duration_t five_seconds = {5, 0};
  bool passed = true, done = false;
  while (!done) {
    ConditionSeq active;
    ret = ws->wait(active, five_seconds);
    if (ret == RETCODE_TIMEOUT) {
      cout << "timeout ";
      done = true; //continue to try and read
    } else if (ret != RETCODE_OK) {
      passed = false;
      break;
    }
    cout << "wait returned" << endl;
    MessageSeq data;
    SampleInfoSeq info;
    ret = mdr->take_w_condition(data, info, LENGTH_UNLIMITED, dr_qc);
    if (ret == RETCODE_NO_DATA) {
      // fall-through
    } else if (ret != RETCODE_OK) {
      cout << "ERROR: take_w_condition returned " << ret << endl;
      passed = false;
      done = true;
    } else {
      char largest = 0;
      for (CORBA::ULong i(0); i < data.length(); ++i)  {
        cout << "Info:\tinstance_handle = " << info[i].instance_handle <<
          "\tsample_rank = " << info[i].sample_rank << '\n';
        if (info[i].valid_data) {
          cout << "Data:\tkey = " << data[i].key <<
            " \tname = " << data[i].name <<
            "\tnest.value = " << data[i].nest.value <<
            '\n';
          if (data[i].name[5] >= largest) {
            largest = data[i].name[5];
          } else {
            cout << "ERROR: data is not sorted for key: " <<
              data[i].key << endl;
            passed = false;
          }
        }
        cout << endl;
      }
    }
  }

  MessageSeq data;
  SampleInfoSeq info;
  ret = mdr->take_w_condition(data, info, LENGTH_UNLIMITED, dr_qc);
  if (ret != RETCODE_NO_DATA) {
    cout << "WARNING: there is still data in the reader\n";
  }

  ws->detach_condition(dr_qc);
  dr->delete_readcondition(dr_qc);
  return passed;
}
Beispiel #6
0
int
OSPL_MAIN (
    int argc,
    char *argv[])
{
    /* Generic DDS entities */
    DomainParticipantFactory_var    dpf;
    DomainParticipant_var           parentDP;
    ExtDomainParticipant_var        participant;
    Topic_var                       chatMessageTopic;
    Topic_var                       nameServiceTopic;
    TopicDescription_var            namedMessageTopic;
    Subscriber_var                  chatSubscriber;
    DataReader_var                  parentReader;

    /* Type-specific DDS entities */
    ChatMessageTypeSupport_var      chatMessageTS;
    NameServiceTypeSupport_var      nameServiceTS;
    NamedMessageTypeSupport_var     namedMessageTS;
    NamedMessageDataReader_var      chatAdmin;
    NamedMessageSeq_var             msgSeq = new NamedMessageSeq();
    SampleInfoSeq_var               infoSeq = new SampleInfoSeq();

    /* QosPolicy holders */
    TopicQos                        reliable_topic_qos;
    TopicQos                        setting_topic_qos;
    SubscriberQos                   sub_qos;
    DDS::StringSeq                  parameterList;

    /* DDS Identifiers */
    DomainId_t                      domain = DOMAIN_ID_DEFAULT;
    ReturnCode_t                    status;

    /* Others */
    bool                            terminated = false;
    const char *                    partitionName = "ChatRoom";
    char  *                         chatMessageTypeName = NULL;
    char  *                         nameServiceTypeName = NULL;
    char  *                         namedMessageTypeName = NULL;

#ifdef USE_NANOSLEEP
    struct timespec                 sleeptime;
    struct timespec                 remtime;
#endif

    /* Options: MessageBoard [ownID] */
    /* Messages having owner ownID will be ignored */
    parameterList.length(1);

    if (argc > 1) {
        parameterList[0] = DDS::string_dup(argv[1]);
    }
    else
    {
        parameterList[0] = "0";
    }

    /* Create a DomainParticipantFactory and a DomainParticipant (using Default QoS settings. */
    dpf = DomainParticipantFactory::get_instance();
    checkHandle(dpf.in(), "DDS::DomainParticipantFactory::get_instance");
    parentDP = dpf->create_participant (
        domain,
        PARTICIPANT_QOS_DEFAULT,
        NULL,
        STATUS_MASK_NONE);
    checkHandle(parentDP.in(), "DDS::DomainParticipantFactory::create_participant");

    /* Narrow the normal participant to its extended representative */
    participant = ExtDomainParticipantImpl::_narrow(parentDP.in());
    checkHandle(participant.in(), "DDS::ExtDomainParticipant::_narrow");

    /* Register the required datatype for ChatMessage. */
    chatMessageTS = new ChatMessageTypeSupport();
    checkHandle(chatMessageTS.in(), "new ChatMessageTypeSupport");
    chatMessageTypeName = chatMessageTS->get_type_name();
    status = chatMessageTS->register_type(
        participant.in(),
        chatMessageTypeName);
    checkStatus(status, "Chat::ChatMessageTypeSupport::register_type");

    /* Register the required datatype for NameService. */
    nameServiceTS = new NameServiceTypeSupport();
    checkHandle(nameServiceTS.in(), "new NameServiceTypeSupport");
    nameServiceTypeName =  nameServiceTS->get_type_name();
    status = nameServiceTS->register_type(
        participant.in(),
        nameServiceTypeName);
    checkStatus(status, "Chat::NameServiceTypeSupport::register_type");

    /* Register the required datatype for NamedMessage. */
    namedMessageTS = new NamedMessageTypeSupport();
    checkHandle(namedMessageTS.in(), "new NamedMessageTypeSupport");
    namedMessageTypeName = namedMessageTS->get_type_name();
    status = namedMessageTS->register_type(
        participant.in(),
        namedMessageTypeName);
    checkStatus(status, "Chat::NamedMessageTypeSupport::register_type");

    /* Set the ReliabilityQosPolicy to RELIABLE. */
    status = participant->get_default_topic_qos(reliable_topic_qos);
    checkStatus(status, "DDS::DomainParticipant::get_default_topic_qos");
    reliable_topic_qos.reliability.kind = DDS::RELIABLE_RELIABILITY_QOS;

    /* Make the tailored QoS the new default. */
    status = participant->set_default_topic_qos(reliable_topic_qos);
    checkStatus(status, "DDS::DomainParticipant::set_default_topic_qos");

    /* Use the changed policy when defining the ChatMessage topic */
    chatMessageTopic = participant->create_topic(
        "Chat_ChatMessage",
        chatMessageTypeName,
        reliable_topic_qos,
        NULL,
        STATUS_MASK_NONE);
    checkHandle(chatMessageTopic.in(), "DDS::DomainParticipant::create_topic (ChatMessage)");

    /* Set the DurabilityQosPolicy to TRANSIENT. */
    status = participant->get_default_topic_qos(setting_topic_qos);
    checkStatus(status, "DDS::DomainParticipant::get_default_topic_qos");
    setting_topic_qos.durability.kind = DDS::TRANSIENT_DURABILITY_QOS;

    /* Create the NameService Topic. */
    nameServiceTopic = participant->create_topic(
        "Chat_NameService",
        nameServiceTypeName,
        setting_topic_qos,
        NULL,
        STATUS_MASK_NONE);
    checkHandle(nameServiceTopic.in(), "DDS::DomainParticipant::create_topic");

    /* Create a multitopic that substitutes the userID with its corresponding userName. */
    namedMessageTopic = participant->create_simulated_multitopic(
        "Chat_NamedMessage",
        namedMessageTypeName,
        "SELECT userID, name AS userName, index, content "
            "FROM Chat_NameService NATURAL JOIN Chat_ChatMessage WHERE userID <> %0",
        parameterList);
    checkHandle(namedMessageTopic.in(), "DDS::ExtDomainParticipant::create_simulated_multitopic");

    /* Adapt the default SubscriberQos to read from the "ChatRoom" Partition. */
    status = participant->get_default_subscriber_qos (sub_qos);
    checkStatus(status, "DDS::DomainParticipant::get_default_subscriber_qos");
    sub_qos.partition.name.length(1);
    sub_qos.partition.name[0] = partitionName;

    /* Create a Subscriber for the MessageBoard application. */
    chatSubscriber = participant->create_subscriber(sub_qos, NULL, STATUS_MASK_NONE);
    checkHandle(chatSubscriber.in(), "DDS::DomainParticipant::create_subscriber");

    /* Create a DataReader for the NamedMessage Topic (using the appropriate QoS). */
    parentReader = chatSubscriber->create_datareader(
        namedMessageTopic.in(),
        DATAREADER_QOS_USE_TOPIC_QOS,
        NULL,
        STATUS_MASK_NONE);
    checkHandle(parentReader.in(), "DDS::Subscriber::create_datareader");

    /* Narrow the abstract parent into its typed representative. */
    chatAdmin = Chat::NamedMessageDataReader::_narrow(parentReader.in());
    checkHandle(chatAdmin.in(), "Chat::NamedMessageDataReader::_narrow");

    /* Print a message that the MessageBoard has opened. */
    cout << "MessageBoard has opened: send a ChatMessage with userID = -1 to close it...." << endl << endl;

    while (!terminated) {
        /* Note: using read does not remove the samples from
           unregistered instances from the DataReader. This means
           that the DataRase would use more and more resources.
           That's why we use take here instead. */

        status = chatAdmin->take(
            msgSeq,
            infoSeq,
            LENGTH_UNLIMITED,
            ANY_SAMPLE_STATE,
            ANY_VIEW_STATE,
            ALIVE_INSTANCE_STATE );
        checkStatus(status, "Chat::NamedMessageDataReader::take");

        for (DDS::ULong i = 0; i < msgSeq->length(); i++) {
            NamedMessage *msg = &(msgSeq[i]);
            if (msg->userID == TERMINATION_MESSAGE) {
                cout << "Termination message received: exiting..." << endl;
                terminated = true;
            } else {
                cout << msg->userName << ": " << msg->content << endl;
            }
            fflush(stdout);
        }

        status = chatAdmin->return_loan(msgSeq, infoSeq);
        checkStatus(status, "Chat::ChatMessageDataReader::return_loan");

        /* Sleep for some amount of time, as not to consume too much CPU cycles. */
#ifdef USE_NANOSLEEP
        sleeptime.tv_sec = 0;
        sleeptime.tv_nsec = 100000000;
        nanosleep(&sleeptime, &remtime);
#elif defined _WIN32
        Sleep(100);
#else
        usleep(100000);
#endif
    }

    /* Remove the DataReader */
    status = chatSubscriber->delete_datareader(chatAdmin.in());
    checkStatus(status, "DDS::Subscriber::delete_datareader");

    /* Remove the Subscriber. */
    status = participant->delete_subscriber(chatSubscriber.in());
    checkStatus(status, "DDS::DomainParticipant::delete_subscriber");

    /* Remove the Topics. */
    status = participant->delete_simulated_multitopic(namedMessageTopic.in());
    checkStatus(status, "DDS::ExtDomainParticipant::delete_simulated_multitopic");

    status = participant->delete_topic(nameServiceTopic.in());
    checkStatus(status, "DDS::DomainParticipant::delete_topic (nameServiceTopic)");

    status = participant->delete_topic(chatMessageTopic.in());
    checkStatus(status, "DDS::DomainParticipant::delete_topic (chatMessageTopic)");

    /* De-allocate the type-names. */
    DDS::string_free(namedMessageTypeName);
    DDS::string_free(nameServiceTypeName);
    DDS::string_free(chatMessageTypeName);

    /* Remove the DomainParticipant. */
    status = dpf->delete_participant(participant.in());
    checkStatus(status, "DDS::DomainParticipantFactory::delete_participant");

    return 0;
}
int run_test_instance(DDS::DomainParticipant_ptr dp)
{
  using namespace DDS;
  using namespace OpenDDS::DCPS;
  using namespace Messenger;
  WaitSet_var ws = new WaitSet;
  MessageTypeSupport_var ts = new MessageTypeSupportImpl;
  ts->register_type(dp, "");
  CORBA::String_var type_name = ts->get_type_name();
  Topic_var topic = dp->create_topic("MyTopic", type_name,
    TOPIC_QOS_DEFAULT, 0, ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  Publisher_var pub = dp->create_publisher(PUBLISHER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
  DataWriter_var dw = pub->create_datawriter(topic, DATAWRITER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  Subscriber_var sub = dp->create_subscriber(SUBSCRIBER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);
  DataReader_var dr = sub->create_datareader(topic, DATAREADER_QOS_DEFAULT, 0,
    ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  StatusCondition_var dw_sc = dw->get_statuscondition();
  dw_sc->set_enabled_statuses(PUBLICATION_MATCHED_STATUS);
  ws->attach_condition(dw_sc);
  Duration_t infinite = {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC};
  ConditionSeq active;

  ReturnCode_t ret = ws->wait(active, infinite);
  if (ret != RETCODE_OK) return ret;

  ret = ws->detach_condition(dw_sc);
  if (ret != RETCODE_OK) return ret;

  MessageDataWriter_var mdw = MessageDataWriter::_narrow(dw);
  Message msg = {0};
  for (int i(0); i < 12; ++i) {
    ++msg.subject_id;
    ret = mdw->write(msg, HANDLE_NIL);
    if (ret != RETCODE_OK) return ret;
  }

  ReadCondition_var dr_rc = dr->create_readcondition(NOT_READ_SAMPLE_STATE,
    NEW_VIEW_STATE, ALIVE_INSTANCE_STATE);
  ReadCondition_var dr_rc2 = dr->create_readcondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, NOT_ALIVE_DISPOSED_INSTANCE_STATE);
  ws->attach_condition(dr_rc);
  ws->attach_condition(dr_rc2);
  MessageDataReader_var mdr = MessageDataReader::_narrow(dr);
  bool passed = true, done = false;
  while (!done) {
    ret = ws->wait(active, infinite);
    if (ret != RETCODE_OK) {
      passed = false;
      break;
    }
    cout << "wait returned" << endl;
    for (CORBA::ULong i(0); i < active.length(); ++i) {
      if (active[i] == dr_rc) {
        // To test both take_w_condition and
        // take_next_instance_w_condition, we'll limit the "take" to 3
        // samples and then use take_next_instance_w_condition.
        MessageSeq data;
        SampleInfoSeq info;
        ret = mdr->take_w_condition(data, info, 3, dr_rc);
        if (ret == RETCODE_NO_DATA) break;
        if (ret != RETCODE_OK) {
          cout << "ERROR: take_w_condition returned " << ret << endl;
          passed = false;
          done = true;
        }
        InstanceHandle_t handle = HANDLE_NIL;
        received_data(data, mdw, msg);
        handle = info[info.length() - 1].instance_handle;
        if (handle == HANDLE_NIL) {
          cout << "ERROR: instance handle is nil" << endl;
          passed = false;
          done = true;
          break;
        }
        cout << "testing take_instance_w_condition" << endl;
        while (true) {
          ret = mdr->take_instance_w_condition(data, info, 1,
                                               handle, dr_rc);
          if (ret == RETCODE_NO_DATA) break;
          if (ret != RETCODE_OK) {
            cout << "ERROR: take_instance_w_condition returned "
                 << ret << endl;
            passed = false;
            done = true;
            break;
          }
          received_data(data, mdw, msg);
        }
      } else if (active[i] == dr_rc2) {
        cout << "an instance has been disposed, exiting" << endl;
        done = true;
      }
    }
  }
  ws->detach_condition(dr_rc);
  ws->detach_condition(dr_rc2);

  dp->delete_contained_entities();
  return passed ? 0 : 1;
}
int OSPL_MAIN (int argc, char *argv[])
{
  os_time delay_20ms =  { 0, 20000000 };
  os_time delay_200ms = { 0, 200000000 };
  MsgSeq msgList;
  SampleInfoSeq infoSeq;

 // create domain participant
  char partition_name[] = "Lifecycle example";

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

  DDSEntityManager mgr;

  // create domain participant
  mgr.createParticipant(partition_name);

  //create type
  MsgTypeSupport_var mt = new MsgTypeSupport();
  mgr.registerType(mt.in());

  //create Topic
  char topic_name[] = "Lifecycle_Msg";
  mgr.createTopic(topic_name);

  //create Subscriber
  mgr.createSubscriber();

  // create DataReader
  mgr.createReader();

  DataReader_var dreader = mgr.getReader();
  MsgDataReader_var LifecycleReader = MsgDataReader::_narrow(dreader.in());
  checkHandle(LifecycleReader.in(), "MsgDataReader::_narrow");

  cout << "=== [Subscriber] Ready ..." << endl;

  bool closed = false;
  ReturnCode_t status;
  int nbIter = 1;
  int nbIterMax = 100;
  while ((closed == false) && (nbIter < nbIterMax))
  {
      status = LifecycleReader->read(msgList, infoSeq, LENGTH_UNLIMITED,
        ANY_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE);
      checkStatus(status, "msgDataReader::read");
      for (DDS::ULong j = 0; j < msgList.length(); j++)
      {
        cout << endl << " Message        : " <<  msgList[j].message.in() << endl;
        cout << " writerStates   : " <<  msgList[j].writerStates.in() << endl;
        cout << " valid_data     : " << (int)infoSeq[j].valid_data  << endl;
        cout << "sample_state:" << sSampleState[index(infoSeq[j].sample_state)] << "-view_state:" << sViewState[index(infoSeq[j].view_state)] << "-instance_state:" << sInstanceState[index(infoSeq[j].instance_state)] << endl;
        os_nanoSleep(delay_200ms);
	closed = (strcmp(msgList[j].writerStates.in(), "STOPPING_SUBSCRIBER") == 0);
      }
      status = LifecycleReader->return_loan(msgList, infoSeq);
      checkStatus(status, "MsgDataReader::return_loan");
      os_nanoSleep(delay_20ms);
      nbIter++;
  }
  cout << "=== [Subscriber] stopping after "<< nbIter << " iterations - closed=" << closed << endl;
  if (nbIter == nbIterMax)  cout << "*** Error : max " << nbIterMax <<   "iterations reached" << endl;
  //cleanup
  // Lifecycle topic
  mgr.deleteReader(LifecycleReader.in ());
  mgr.deleteSubscriber();
  mgr.deleteTopic();
  mgr.deleteParticipant();
  return 0;
}
int OSPL_MAIN (int argc, char *argv[])
{
  // usage : ContentFilteredTopicDataSubscriber <subscription_string>
  const char *ContentFilteredTopicDataToSubscribe;
  os_time delay_200ms = { 0, 200000000 };
  char buf[MAX_MSG_LEN];

  if (argc > 1)
  {
    ContentFilteredTopicDataToSubscribe = argv[1];
  }
  else
  {
    cerr <<
      "*** [ContentFilteredTopicDataSubscriber] Subscription string not specified" <<
      endl;
    cerr << "*** usage : ContentFilteredTopicDataSubscriber <subscription_string>" <<
      endl;
    return  - 1;
  }

  StockSeq msgList;
  SampleInfoSeq infoSeq;

  DDSEntityManager mgr;

  // create domain participant
  char partition_name[] = "ContentFilteredTopic example";
  mgr.createParticipant(partition_name);

  //create type
  StockTypeSupport_var st = new StockTypeSupport();
  mgr.registerType(st.in());

  //create Topic
  char topic_name[] = "StockTrackerExclusive";
  mgr.createTopic(topic_name);

  //create Subscriber
  mgr.createSubscriber();

  char sTopicName[] = "MyStockTopic";
  // create subscription filter
  snprintf(buf, MAX_MSG_LEN, "ticker = '%s'", ContentFilteredTopicDataToSubscribe);
  DDS::String_var sFilter = DDS::string_dup(buf);
  // Filter expr
  StringSeq sSeqExpr;
  sSeqExpr.length(0);
  // create topic
  mgr.createContentFilteredTopic(sTopicName, sFilter.in(), sSeqExpr);
  // create Filtered DataReader
  cout << "=== [ContentFilteredTopicDataSubscriber] Subscription filter : " << sFilter
    << endl;
  mgr.createReader(true);

  DataReader_var dreader = mgr.getReader();
  StockDataReader_var ContentFilteredTopicDataReader = StockDataReader::_narrow(dreader.in());
  checkHandle(ContentFilteredTopicDataReader.in(), "StockDataReader::_narrow");

  cout << "=== [ContentFilteredTopicDataSubscriber] Ready ..." << endl;

  bool closed = false;
  ReturnCode_t status =  - 1;
  int count = 0;
  while (!closed && count < 1500) // We dont want the example to run indefinitely
  {
    status = ContentFilteredTopicDataReader->take(msgList, infoSeq, LENGTH_UNLIMITED,
      ANY_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE);
    checkStatus(status, "ContentFilteredTopicDataDataReader::take");
    for (DDS::ULong i = 0; i < msgList.length(); i++)
    {
        if(infoSeq[i].valid_data)
        {
           if (msgList[i].price ==  - 1.0f)
           {
              closed = true;
              break;
           }
        }
     cout << "=== [ContentFilteredTopicDataSubscriber] receives stockQuote :  ("<< msgList[i].ticker << ", " << msgList[i].price << ')'<< endl;
    }

    status = ContentFilteredTopicDataReader->return_loan(msgList, infoSeq);
    checkStatus(status, "StockDataReader::return_loan");
    os_nanoSleep(delay_200ms);
    ++count;
  }

  cout << "=== [ContentFilteredTopicDataSubscriber] Market Closed" << endl;

  //cleanup
  mgr.deleteReader(ContentFilteredTopicDataReader.in ());
  mgr.deleteSubscriber();
  mgr.deleteFilteredTopic();
  mgr.deleteTopic();
  mgr.deleteParticipant();

  return 0;
}
Beispiel #10
0
bool run_test(DomainParticipant_var& dp_sub,
              DomainParticipant_var& dp_pub)
{
  OpenDDS::DCPS::RepoId sub_repo_id, pub_repo_id;

  {
    OpenDDS::DCPS::DomainParticipantImpl* dp_impl =
      dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(dp_sub.in());
    sub_repo_id = dp_impl->get_id ();
    OpenDDS::DCPS::GuidConverter converter(sub_repo_id);
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT("%P ")
                ACE_TEXT("Sub Domain Participant GUID=%C\n"),
                std::string(converter).c_str()));
  }

  {
    OpenDDS::DCPS::DomainParticipantImpl* dp_impl =
      dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(dp_pub.in());
    pub_repo_id = dp_impl->get_id ();
    OpenDDS::DCPS::GuidConverter converter(pub_repo_id);
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT("%P ")
                ACE_TEXT("Pub Domain Participant GUID=%C\n"),
                std::string(converter).c_str()));
  }

  // If we are running with an rtps_udp transport, it can't be shared between
  // participants.
  TransportConfig_rch cfg = TheTransportRegistry->get_config("dp1");
  if (!cfg.is_nil()) {
    TheTransportRegistry->bind_config(cfg, dp_sub);
  }
  cfg = TheTransportRegistry->get_config("dp2");
  if (!cfg.is_nil()) {
    TheTransportRegistry->bind_config(cfg, dp_pub);
  }

  Subscriber_var bit_sub = dp_sub->get_builtin_subscriber();

  if (!read_participant_bit(bit_sub, dp_sub, pub_repo_id, TestConfig::PARTICIPANT_USER_DATA())) {
    return false;
  }

  // Each domain participant's handle to the other
  InstanceHandle_t dp_sub_ih, dp_pub_ih;
  InstanceHandle_t pub_ih, sub_ih, ig_ih;

  if (!(check_discovered_participants(dp_sub, dp_pub_ih) &&
        check_discovered_participants(dp_pub, dp_sub_ih)))
  {
    return false;
  }

  DataWriter_var dw = create_data_writer(dp_pub);
  if (!dw) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not create Data Writer (participant 2)\n"));
    return false;
  }

  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, pub_ih, TestConfig::DATA_WRITER_USER_DATA(), TestConfig::TOPIC_DATA(), 1, 1)) {
    return false;
  }

  DataReader_var dr = create_data_reader(dp_sub);
  if (!dr) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not create Data Reader (participant 1)\n"));
    return false;
  }
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, sub_ih, TestConfig::DATA_READER_USER_DATA(), TestConfig::TOPIC_DATA())) {
    return false;
  }

  // Wait for the reader to associate with the writer.
  WriterSync::wait_match(dw);

  // Remove the writer and its topic, then re-create them.  The writer's
  // participant should still have discovery info about the reader so that
  // the association between the new writer and old reader can be established.
  recreate_data_writer_and_topic(dw, dr);

  // Wait for the reader to associate with the writer.
  WriterSync::wait_match(dw);

  // The new writer is associated with the reader, but the reader may still
  // also be associated with the old writer.
  wait_match(dr, 1);

  // Get the new instance handle as pub_ih
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, pub_ih, TestConfig::DATA_WRITER_USER_DATA(), TestConfig::TOPIC_DATA(), 1, 2)) {
    return false;
  }

  TestMsgDataWriter_var tmdw = TestMsgDataWriter::_narrow(dw);
  const TestMsg msg = {42};
  tmdw->write(msg, HANDLE_NIL);

  ReadCondition_var rc = dr->create_readcondition(ANY_SAMPLE_STATE,
                                                  ANY_VIEW_STATE,
                                                  ALIVE_INSTANCE_STATE);
  WaitSet_var waiter = new WaitSet;
  waiter->attach_condition(rc);
  ConditionSeq activeConditions;
  const Duration_t timeout = { 90, 0 };
  ReturnCode_t result = waiter->wait(activeConditions, timeout);
  waiter->detach_condition(rc);
  if (result != RETCODE_OK) {
    ACE_DEBUG((LM_ERROR,
      "ERROR: %P TestMsg reader could not wait for condition: %d\n", result));
    return false;
  }

  TestMsgDataReader_var tmdr = TestMsgDataReader::_narrow(dr);

  TestMsgSeq data;
  SampleInfoSeq infos;
  ReturnCode_t ret = tmdr->read_w_condition(data, infos, LENGTH_UNLIMITED, rc);
  if (ret != RETCODE_OK) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read TestMsg: %d\n", ret));
    return false;
  }

  bool ok = false;
  for (CORBA::ULong i = 0; i < data.length(); ++i) {
    if (infos[i].valid_data) {
      ok = true;
      ACE_DEBUG((LM_DEBUG, "%P Read data sample: %d\n", data[i].value));
    }
  }

  if (!ok) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P no valid data from TestMsg data reader\n"));
  }

  // Change dp qos
  {
    DomainParticipantQos dp_qos;
    dp_pub->get_qos(dp_qos);
    set_qos(dp_qos.user_data.value, TestConfig::PARTICIPANT_USER_DATA2());
    dp_pub->set_qos(dp_qos);
  }
  // Change dw qos
  {
    DataWriterQos dw_qos;
    dw->get_qos(dw_qos);
    set_qos(dw_qos.user_data.value, TestConfig::DATA_WRITER_USER_DATA2());
    dw->set_qos(dw_qos);
  }
  // Change dr qos
  {
    DataReaderQos dr_qos;
    dr->get_qos(dr_qos);
    set_qos(dr_qos.user_data.value, TestConfig::DATA_READER_USER_DATA2());
    dr->set_qos(dr_qos);
  }
  // Wait for propagation
  ACE_OS::sleep(3);
  if (!read_participant_bit(bit_sub, dp_sub, pub_repo_id, TestConfig::PARTICIPANT_USER_DATA2())) {
    return false;
  }
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, ig_ih, TestConfig::DATA_WRITER_USER_DATA2(), TestConfig::TOPIC_DATA(), 1, 1)) {
    return false;
  }
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, ig_ih, TestConfig::DATA_READER_USER_DATA2(), TestConfig::TOPIC_DATA())) {
    return false;
  }

  // Set dw topic qos
  Topic_var topic = dw->get_topic();
  TopicQos topic_qos;
  topic->get_qos(topic_qos);
  set_qos(topic_qos.topic_data.value, TestConfig::TOPIC_DATA2());
  topic->set_qos(topic_qos);

  // Set dr topic qos
  TopicDescription_var topic_desc = dr->get_topicdescription();
  topic = Topic::_narrow(topic_desc);
  topic->get_qos(topic_qos);
  set_qos(topic_qos.topic_data.value, TestConfig::TOPIC_DATA2());
  topic->set_qos(topic_qos);

  // Wait for propagation
  ACE_OS::sleep(3);
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, ig_ih, TestConfig::DATA_WRITER_USER_DATA2(), TestConfig::TOPIC_DATA2(), 1, 1)) {
    return false;
  }
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, ig_ih, TestConfig::DATA_READER_USER_DATA2(), TestConfig::TOPIC_DATA2())) {
    return false;
  }

  // Test ignore
  dp_sub->ignore_publication(pub_ih);
  if (!read_publication_bit(bit_sub, dp_sub, pub_repo_id, pub_ih, TestConfig::DATA_WRITER_USER_DATA2(), TestConfig::TOPIC_DATA2(), 0, 0)) {
    ACE_ERROR_RETURN((LM_ERROR,
                     ACE_TEXT("ERROR: %P Could not ignore publication\n")), false);
  }

  dp_pub->ignore_subscription(sub_ih);
  if (!read_subscription_bit(dp_pub->get_builtin_subscriber(), dp_pub, sub_repo_id, sub_ih, TestConfig::DATA_READER_USER_DATA2(), TestConfig::TOPIC_DATA2(), true)) {
    ACE_ERROR_RETURN((LM_ERROR,
                     ACE_TEXT("ERROR: %P Could not ignore subscription\n")), false);
  }

  dp_sub->ignore_participant(dp_pub_ih);
  InstanceHandleSeq handles;
  dp_sub->get_discovered_participants(handles);
  // Check that the handle is no longer in the sequence.
  for (CORBA::ULong i = 0; i < handles.length (); ++i) {
    if (handles[i] == dp_pub_ih) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("ERROR: %P Could not ignore participant\n")), false);

    }
  }

  return ok;
}
Beispiel #11
0
bool read_subscription_bit(const Subscriber_var& bit_sub,
                           const DomainParticipant_var& publisher,
                           const OpenDDS::DCPS::RepoId& subscriber_repo_id,
                           InstanceHandle_t& handle,
                           int user_data,
                           int topic_data,
                           bool ignored_subscription = false)
{
  OpenDDS::DCPS::Discovery_rch disc =
    TheServiceParticipant->get_discovery(publisher->get_domain_id());
  OpenDDS::DCPS::DomainParticipantImpl* publisher_impl =
    dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(publisher.in());

  DataReader_var dr = bit_sub->lookup_datareader(BUILT_IN_SUBSCRIPTION_TOPIC);
  if (!ignored_subscription) {
    ReadCondition_var rc = dr->create_readcondition(ANY_SAMPLE_STATE,
                                                    ANY_VIEW_STATE,
                                                    ALIVE_INSTANCE_STATE);
    WaitSet_var waiter = new WaitSet;
    waiter->attach_condition(rc);
    ConditionSeq activeConditions;
    Duration_t forever = { DURATION_INFINITE_SEC,
                           DURATION_INFINITE_NSEC };
    ReturnCode_t result = waiter->wait(activeConditions, forever);
    waiter->detach_condition(rc);
    if (result != RETCODE_OK) {
      ACE_DEBUG((LM_ERROR,
        "ERROR: %P (subscription BIT) could not wait for condition: %d\n", result));
      return false;
    }
  } else {
    ACE_OS::sleep(1);
  }
  SubscriptionBuiltinTopicDataDataReader_var pub_bit =
    SubscriptionBuiltinTopicDataDataReader::_narrow(dr);

  SubscriptionBuiltinTopicDataSeq data;
  SampleInfoSeq infos;
  ReturnCode_t ret =
    pub_bit->read(data, infos, LENGTH_UNLIMITED,
                  ANY_SAMPLE_STATE, ANY_VIEW_STATE, ALIVE_INSTANCE_STATE);
  if (ignored_subscription && (ret != RETCODE_NO_DATA)) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read ignored subscription BIT: %d\n",
               ret));
    return false;
  } else if (ret != RETCODE_OK && ret != RETCODE_NO_DATA) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read subscription BIT: %d\n", ret));
    return false;
  }

  int num_valid = 0;
  bool found_subscriber = false;
  for (CORBA::ULong i = 0; i < data.length(); ++i) {
    if (infos[i].valid_data) {
      ++num_valid;

      OpenDDS::DCPS::RepoId repo_id =
        disc->bit_key_to_repo_id(publisher_impl,
                                 OpenDDS::DCPS::BUILT_IN_PARTICIPANT_TOPIC,
                                 data[i].participant_key);

      OpenDDS::DCPS::GuidConverter converter(repo_id);

      ACE_DEBUG((LM_DEBUG,
                 "%P Read Subscription BIT with key: %x %x %x and handle %d\n"
                 "\tParticipant's GUID=%C\n\tTopic: %C\tType: %C\n",
                 data[i].key.value[0], data[i].key.value[1],
                 data[i].key.value[2], infos[i].instance_handle,
                 std::string(converter).c_str (), data[i].topic_name.in(),
                 data[i].type_name.in()));
      if (repo_id == subscriber_repo_id) {
        found_subscriber = true;
        if (data[i].user_data.value.length() != 1) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] user data length %d "
                            "not expected length of 1\n",
                            i,
                            data[i].user_data.value.length()),
                           false);
        }
        if (data[i].topic_data.value.length() != 1) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] topic data length %d "
                            "not expected length of 1\n",
                            i,
                            data[i].topic_data.value.length()),
                           false);
        }
        if (data[i].user_data.value[0] != user_data) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] user data value %d "
                            "not expected value %d\n",
                            i,
                            data[i].user_data.value[0],
                            user_data),
                           false);
        }
        if (data[i].topic_data.value[0] != topic_data) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P subscription [%d] topic data value %d "
                            "not expected value %d\n",
                            i,
                            data[i].topic_data.value[0],
                            topic_data),
                           false);
        }
      }
      handle = infos[i].instance_handle;
    }
  }
  if (ignored_subscription) {
    if (num_valid != 0) {
      ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P expected 0 discovered "
                        "subscriptions, found %d\n",
                        num_valid), false);
    }
  }
  else {
    if (num_valid != 1) {
      ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P expected 1 discovered "
                        "subscriptions, found %d\n",
                        num_valid), false);
    }
    if (!found_subscriber) {
      ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P did not find expected subscription\n"), false);
    }
  }

  return true;
}
Beispiel #12
0
bool read_participant_bit(const Subscriber_var& bit_sub,
                          const DomainParticipant_var& dp,
                          const OpenDDS::DCPS::RepoId& other_dp_repo_id,
                          int user_data)
{
  OpenDDS::DCPS::Discovery_rch disc =
    TheServiceParticipant->get_discovery(dp->get_domain_id());
  OpenDDS::DCPS::DomainParticipantImpl* dp_impl =
    dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(dp.in());

  DataReader_var dr = bit_sub->lookup_datareader(BUILT_IN_PARTICIPANT_TOPIC);
  ReadCondition_var rc = dr->create_readcondition(ANY_SAMPLE_STATE,
                                                  ANY_VIEW_STATE,
                                                  ALIVE_INSTANCE_STATE);
  WaitSet_var waiter = new WaitSet;
  waiter->attach_condition(rc);
  ConditionSeq activeConditions;
  Duration_t forever = { DURATION_INFINITE_SEC,
                         DURATION_INFINITE_NSEC };
  ReturnCode_t result = waiter->wait(activeConditions, forever);
  waiter->detach_condition(rc);
  if (result != RETCODE_OK) {
    ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P could not wait for condition: %d\n", result), false);
  }

  ParticipantBuiltinTopicDataDataReader_var part_bit =
    ParticipantBuiltinTopicDataDataReader::_narrow(dr);

  ParticipantBuiltinTopicDataSeq data;
  SampleInfoSeq infos;
  ReturnCode_t ret =
    part_bit->read_w_condition(data, infos, LENGTH_UNLIMITED, rc);
  if (ret != RETCODE_OK) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P could not read participant BIT: %d\n", ret));
    return false;
  }

  bool found_other_dp = false;
  int num_valid = 0;

  for (CORBA::ULong i = 0; i < data.length(); ++i) {
    if (infos[i].valid_data) {
      ++num_valid;
      OpenDDS::DCPS::RepoId repo_id =
        disc->bit_key_to_repo_id(dp_impl,
                                 OpenDDS::DCPS::BUILT_IN_PARTICIPANT_TOPIC,
                                 data[i].key);

      OpenDDS::DCPS::GuidConverter converter(repo_id);
      ACE_DEBUG((LM_DEBUG,
                 ACE_TEXT("%P ")
                 ACE_TEXT("Read Participant BIT GUID=%C handle=%d\n"),
                 std::string(converter).c_str(), infos[i].instance_handle));

      if (repo_id == other_dp_repo_id) {
        if (data[i].user_data.value.length() != 1) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P participant[%d] user data length %d "
                            "not expected length of 1\n",
                            i,
                            data[i].user_data.value.length()),
                           false);
        }

        if (data[i].user_data.value[0] != user_data) {
          ACE_ERROR_RETURN((LM_ERROR,
                            "ERROR: %P participant[%d] user data value %d "
                            "not expected value %d\n",
                            i,
                            data[i].user_data.value[0],
                            user_data),
                           false);
        }

        found_other_dp = true;
      }
    }
  }

  if (num_valid != 1) {
    ACE_DEBUG((LM_ERROR, "ERROR: %P expected to discover 1 other participant, found %d\n", data.length ()));
  }

  part_bit->return_loan(data, infos);

  if (!found_other_dp) {
    ACE_ERROR_RETURN((LM_ERROR, "ERROR: %P did not find expected participant\n"), false);
  }

  return true;
}
Beispiel #13
0
int NodeBtHandler (int argc, char *argv[])
{
  // DDS değişkenleri
  DDSEntityManager                    mgrBtPub;
  DDSEntityManager                    mgrReqSub;
  ReturnCode_t                        status;
  SampleInfoSeq_var                   infoSeq = new SampleInfoSeq();
  BtSeq*                              btSeqInstance = new BtSeq();
  ServerReqSeq                        serverReqSeq;

  // Zaman ile alakalı değişkenler
  long int                            messageIDCount = 0;
  Time_t                              tsBeforeTheScan = { 0, 0 };
  Time_t                              tsAfterTheScan = { 0, 0 };
  //Time_t                              tsWifiPub = { 0, 0 };
  struct timeval                      tsConverter;
  DDS::Duration_t                     waitAckTime = { 0, 800000000 }; //800ms
  int                                 refreshRate = 60;

  // Veri tutucular (data structures)
  vector<string>                      btMacHolder;
  vector<int>                         btRssiHolder;
  string                              btFileContenHolder;

  // Bluetooth tarama sonuçlarının yazdırıldığı dosyadan okuma yapacak
  // olan değişken
  boost::filesystem::ifstream         fIn;

  // Bluetooth tarama sıklığı ayarlayan değişken
  int                                 refreshRateCounter = -1;

  char                                hostName[1024];
  gethostname(hostName, 1024);


  // !!! Bluetooth tarama mesajlarını Publish edecek Topic yaratılıyor
  // ve o Topic'e ait konfigürasyon ayarları yapılıyor.

  // Domain participant yaratılıyor
  mgrBtPub.createParticipant ("KonSens_BtSeq_Participant");

  // BtSeq tipi yaratılıyor
  BtSeqTypeSupport_var btSeqTs = new BtSeqTypeSupport();
  mgrBtPub.registerType(btSeqTs.in());

  // Topic yaratılıyor
  char btPubTopicName[] = "KonSensData_BtSeq_Topic";
  mgrBtPub.createTopic(btPubTopicName);

  // Publisher yaratılıyor
  mgrBtPub.createPublisher();

  // DataWriter yaratılıyor
  bool autodispose_unregistered_instances = false;
  mgrBtPub.createWriter(autodispose_unregistered_instances,
                        KEEP_ALL_HISTORY_QOS,
                        BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS);

  // Yaratılan DataWriter, BtSeq tipi için özelleştiriliyor
  DataWriter_var dWriter = mgrBtPub.getWriter ();
  BtSeqDataWriter_var btSeqWriter = BtSeqDataWriter::_narrow(dWriter.in());

  // Düğüm numarasını atanıyor
  btSeqInstance->userID = 13;

  // Publish edilecek olan mesajlara zaman etiketi takabilmek için
  // btSeqInstance değişkeni register ediliyor
  //userHandle = btSeqWriter->register_instance_w_timestamp(*btSeqInstance,
  //                                                        tsWifiPub);

  cout << "=== [Publisher of KonSensData_BtSeq_Topic] Ready ..." << endl;


  // !!! Sunucudan gelen komutlara Subscribe olacak olan Topic yaratılıyor
  // ve o Topic için gerekli konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrReqSub.createParticipant(
        "KonSensData_ServerReq_Participant_Server_to_Node");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrSubscriberTS = new ServerReqTypeSupport();
  mgrReqSub.registerType(mgrSubscriberTS.in());

  // Topic yaratılıyor
  char reqSubTopicName[] = "KonSensData_ServerReq_Topic_Server_to_Node";
  mgrReqSub.createTopic(reqSubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Subscriber yaratılıyor
  mgrReqSub.createSubscriber();

  // DataReader yaratılıyor
  mgrReqSub.createReader(KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataReader_var dReaderSub = mgrReqSub.getReader();
  ServerReqDataReader_var serverReqReader =
      ServerReqDataReader::_narrow(dReaderSub.in());
  checkHandle(serverReqReader.in(), "ServerReqDataReader::_narrow");

  cout << "=== [Subscriber KonSensData_ServerReq_Topic_Server_to_Node]"
          " Ready ..." << endl;


  // Bluetooth aktif hale getiriliyor.
  system("sudo hciconfig -a hci0 up");
  stringstream ssBtName;
  ssBtName << "sudo bt-adapter -a hci0 --set Name \"" << hostName << "\"";
  system(ssBtName.str().c_str());
  system("sudo bt-adapter -a hci0 --set Discoverable 1");

  // Yenileme sıklığını belirleyecek olan 'timelimit' değişkeni yaratılıyor.
  Timeout timelimit(std::chrono::milliseconds(refreshRate*1000));


  while (true)
  {
    if (timelimit.isExpired() || refreshRateCounter == -1)
    {

      // BT mesajını Publish etmek için hazırlık yapılıyor.

      cout << "-----------------------------------" << endl;

      btSeqInstance->messageID = messageIDCount;

      // Tarama öncesi alınan zaman etiketi (timestamp[0])
      gettimeofday(&tsConverter, NULL);
      tsBeforeTheScan.sec = tsConverter.tv_sec;
      tsBeforeTheScan.nanosec = (tsConverter.tv_usec * 1000);
      cout << " timestamp[0] (before the scan) = " << tsBeforeTheScan.sec
           << '.';
      cout << setfill('0') << setw(9) << (tsBeforeTheScan.nanosec)
           << endl;

      // BT taraması yapılıyor ve ardından tarama sonuçları 'bt_rssi'
      // dosyasına yazdırılıyor.
      system("sudo hciconfig hci0 reset");
      FakeDelay();
      system("sudo bt-adapter -a hci0 -d >> bt_rssi.txt");
      FakeDelay();

      cout << "Bluetooth message is publishing..." << endl;

      try
      {
        // BT tarama dosyası okunuyor
        fIn.open ("bt_rssi.txt", ios::in);
        stringstream ssBt;
        ssBt << fIn.rdbuf();
        btFileContenHolder = ssBt.str();
        system("rm bt_rssi.txt");

        // Okunan dosya boost kütüphane yardımıyla ayrıştırılıyor
        boost::regex expAd( "Address: ([0-9A-F:]{17})" ) ;
        boost::regex expBt( "RSSI:.*?([0-9]+)") ;
        boost::match_results<string::const_iterator> whatAd;

        string::const_iterator startAd = btFileContenHolder.begin();
        string::const_iterator finishAd = btFileContenHolder.end();

        while (boost::regex_search(startAd, finishAd, whatAd, expAd))
        {
          btMacHolder.push_back(whatAd[1]);
          startAd = whatAd[0].second ;
        }

        boost::match_results<string::const_iterator> whatBt;
        startAd = btFileContenHolder.begin() ;
        finishAd = btFileContenHolder.end() ;

        while (boost::regex_search(startAd, finishAd, whatBt, expBt))
        {
          string foundRssi(whatBt[1]);
          btRssiHolder.push_back(atoi(foundRssi.c_str()));
          startAd = whatBt[0].second ;
        }

        cout << "Number of BT connection that has been found: "
             << btRssiHolder.size() << endl;
        cout << "MessageID: " << btSeqInstance->messageID << endl;

        // Tarama sonrası alınan zaman etiketi (timestamp[1])
        gettimeofday(&tsConverter, NULL);
        tsAfterTheScan.sec = tsConverter.tv_sec;
        tsAfterTheScan.nanosec =( tsConverter.tv_usec * 1000);
        cout << " timestamp[1] (after the scan) = "
             << tsAfterTheScan.sec << '.';
        cout << setfill('0') << setw(9) << (tsAfterTheScan.nanosec)
             << endl;


        // Ayrıştırılan BT tarama dosyası ve alınan zaman etiketleri,
        // Publish edilecek olan mesaj değişkenlerine kaydediliyor.
        btSeqInstance->timestamp[0][0] = tsBeforeTheScan.nanosec;
        btSeqInstance->timestamp[0][1] = tsBeforeTheScan.sec;
        btSeqInstance->timestamp[1][0] = tsAfterTheScan.nanosec;
        btSeqInstance->timestamp[1][1] = tsAfterTheScan.sec;

        btSeqInstance->messages.length(btMacHolder.size());
        for(int i = 0; i < btMacHolder.size(); i++)
        {
          Msg msg;
          msg.devID = DDS::string_dup(btMacHolder[i].c_str());
          msg.hostName = DDS::string_dup(hostName);
          msg.dbm = -btRssiHolder[i];
          btSeqInstance->messages[i] = msg;
        }

        // Publish edilmeden önce, bir önceki mesajın acknowlegde mesajı
        // bekleniyor
        btSeqWriter->wait_for_acknowledgments(waitAckTime);

        status = btSeqWriter->write(*btSeqInstance,
                                    DDS::HANDLE_NIL);
        checkStatus(status, "BtSeqDataWriter::write");
        messageIDCount++;
      }

      catch ( boost::bad_expression & ex )
      {
        std::cout << ex.what() ;
        break;
      }

      btMacHolder.clear();
      btRssiHolder.clear();
      fIn.close();

      cout << "-----------------------------------" << endl;

      // Tarama sıklığını belirleyen değişken sıfırlanıyor
      timelimit.setTimerToZero();
      refreshRateCounter = 0;
      cout << refreshRateCounter << endl;

    } // BT Publisher kısmının sonu


    // Sunucu tarafından gönderilen Matlab komutlarına Subscribe olunuyor
    else
    {
      status = serverReqReader->take(serverReqSeq,
                                     infoSeq,
                                     LENGTH_UNLIMITED,
                                     ANY_SAMPLE_STATE,
                                     ANY_VIEW_STATE,
                                     ANY_INSTANCE_STATE);
      checkStatus(status, "severReqDataReader::read");

      for (DDS::ULong j = 0; j < serverReqSeq.length(); j++)
      {
        if(infoSeq[j].valid_data)
        {
          cout << "=== [Subscriber] message received :" << endl;
          cout << "    Received Request Message  : "
               << serverReqSeq[j].request << endl;
          cout << "    Received RequestID : \""
               << serverReqSeq[j].requestID << "\"" << endl;

          // Rapidjson yapılandırıcısı yaratılıyor
          Document d;
          if(d.Parse(serverReqSeq[j].request).HasParseError())
            cout << " Parsing Error!" << endl;

          StringBuffer nodeIdBuffer;
          Writer<StringBuffer> nodeIdWriter(nodeIdBuffer);
          d["NodeID"].Accept(nodeIdWriter);

          string tempNodeId = nodeIdBuffer.GetString();

          // Subscribe olunan mesajın düğüme ait olup olmadığı kontrol ediliyor
          if (tempNodeId == "\"SensDug13\"")
          {
            StringBuffer buffer;

            Value::ConstMemberIterator itr = d.FindMember("SetRefreshRate");
            // Ref Rate komutunun gelip gelmediği kontrol ediliyor
            if(itr != d.MemberEnd())
            {
              string refreshRateString;
              int refreshRateInt;

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d["SetRefreshRate"].Accept(writer);
              refreshRateString = buffer.GetString();

              // Gelen mesajda fazladan çift tırnak ile bulunuyor
              // Örneğin, ""15""
              // Bu yüzden ilk son karakterler kırpılıyor
              refreshRateString =
                  refreshRateString.substr(1, refreshRateString.size()-1);
              // Refresh rate değeri stringden integera çevriliyor
              refreshRateInt = atoi(refreshRateString.c_str());

              refreshRate = refreshRateInt;
              timelimit.setMaxDuration(std::chrono::milliseconds
                                       (refreshRate*1000));

            }
          }
          else
            cout << "Invalid NodeID!" << endl;
        }
      }

      status = serverReqReader->return_loan(serverReqSeq, infoSeq);
      checkStatus(status, "ServerReqDataReader::return_loan");

      refreshRateCounter++;
      cout << refreshRateCounter << endl;

    } // Matlab komutuna Subscribe olma kısmının sonu

    // Terminalde akacak olan çıktıları dah gözle görülebilir bir şekilde
    // yazdırmak için koyulmuştur
    FakeDelay();
  }

  // Hafıza temizle işlemleri gerçekleştiriliyor

  mgrBtPub.deleteWriter();
  mgrBtPub.deletePublisher();
  mgrBtPub.deleteTopic();
  mgrBtPub.deleteParticipant();

  mgrReqSub.deleteReader();
  mgrReqSub.deleteSubscriber();
  mgrReqSub.deleteTopic();
  mgrReqSub.deleteParticipant();

  return 0;
}
bool run_change_parameter_test(const DomainParticipant_var& dp,
  const MessageTypeSupport_var& ts, const Publisher_var& pub,
  const Subscriber_var& sub)
{
  DataWriter_var dw;
  DataReader_var dr;
  test_setup(dp, ts, pub, sub, "MyTopic3", dw, dr);

  MessageDataWriter_var mdw = MessageDataWriter::_narrow(dw);
  Message sample;
  sample.key = 3;
  ReturnCode_t ret = mdw->write(sample, HANDLE_NIL);
  if (ret != RETCODE_OK) return false;
  if (!waitForSample(dr)) return false;

  DDS::StringSeq params(1);
  params.length(1);
  params[0] = "2";
  ReadCondition_var dr_qc = dr->create_querycondition(ANY_SAMPLE_STATE,
    ANY_VIEW_STATE, ALIVE_INSTANCE_STATE, "key = %0", params);
  if (!dr_qc.in()) {
    cout << "ERROR: failed to create QueryCondition" << endl;
    return false;
  }

  QueryCondition_var query_cond = QueryCondition::_narrow(dr_qc);
  CORBA::String_var expr = query_cond->get_query_expression();
  if (std::string("key = %0") != expr.in()) {
    cout << "ERROR: get_query_expression() query expression should match " << endl;
    return false;
  }

  params = DDS::StringSeq();
  ret = query_cond->get_query_parameters(params);
  if (ret != RETCODE_OK) {
    cout << "ERROR: get_query_parameters() failed " << endl;
    return false;
  } else if (params.length() != 1 || std::string(params[0]) != "2") {
    cout << "ERROR: get_query_parameters() query parameters doesn't match " << endl;
    return false;
  }

  WaitSet_var ws = new WaitSet;
  ws->attach_condition(dr_qc);
  ConditionSeq active;
  Duration_t three_sec = {3, 0};
  ret = ws->wait(active, three_sec);
  // expect a timeout because the sample doesn't match the query string
  if (ret != RETCODE_TIMEOUT) {
    cout << "ERROR: wait(qc) should have timed out" << endl;
    return false;
  }
  ws->detach_condition(dr_qc);

  MessageDataReader_var mdr = MessageDataReader::_narrow(dr);
  MessageSeq data;
  SampleInfoSeq infoseq;
  ret = mdr->take_w_condition(data, infoseq, LENGTH_UNLIMITED, dr_qc);
  if (ret != RETCODE_NO_DATA) {
    cout << "ERROR: take_w_condition(qc) shouldn't have returned data" << endl;
    return false;
  }

  params = DDS::StringSeq(1);
  params.length(1);
  params[0] = "3";
  ret = query_cond->set_query_parameters(params);

  params = DDS::StringSeq();
  ret = query_cond->get_query_parameters(params);
  if (ret != RETCODE_OK) {
    cout << "ERROR: get_query_parameters() failed " << endl;
    return false;
  } else if (params.length() != 1 || std::string(params[0]) != "3") {
    cout << "ERROR: get_query_parameters() query parameters doesn't match " << endl;
    return false;
  }

  ws->attach_condition(dr_qc);
  ret = ws->wait(active, three_sec);
  if (ret != RETCODE_OK) {
    cout << "ERROR: wait(qc) should not time out" << endl;
    return false;
  }
  ws->detach_condition(dr_qc);

  ret = mdr->take_w_condition(data, infoseq, LENGTH_UNLIMITED, dr_qc);
  if (ret != RETCODE_OK) {
    cout << "ERROR: take_w_condition(qc) should have returned data" << endl;
    return false;
  }

  dr->delete_readcondition(dr_qc);
  return true;
}
int OSPL_MAIN (int argc, char *argv[])
{
  MsgSeq msgList;
  SampleInfoSeq infoSeq;
  Duration_t timeout = { 0, 200000000 };
  int count = 0;

  DDSEntityManager mgr;

   // create domain participant
  char partition_name[] = "Listener example";
  mgr.createParticipant(partition_name);

  //create type
  MsgTypeSupport_var st = new MsgTypeSupport();
  mgr.registerType(st.in());

  //create Topic
  char topic_name[] = "ListenerData_Msg";
  mgr.createTopic(topic_name);

  //create Subscriber
  mgr.createSubscriber();

  // create DataReader
  mgr.createReader();

  DataReader_var dreader = mgr.getReader();
  ListenerDataListener *myListener = new ListenerDataListener();
  myListener->m_MsgReader = MsgDataReader::_narrow(dreader.in());
  checkHandle(myListener->m_MsgReader.in(), "MsgDataReader::_narrow");

  cout << "=== [ListenerDataSubscriber] set_listener" << endl;
  DDS::StatusMask mask =
           DDS::DATA_AVAILABLE_STATUS | DDS::REQUESTED_DEADLINE_MISSED_STATUS;
  myListener->m_MsgReader->set_listener(myListener, mask);
  cout << "=== [ListenerDataSubscriber] Ready ..." << endl;
  myListener->m_closed = false;

  // waitset used to avoid spinning in the loop below
  DDS::WaitSet_var ws = new DDS::WaitSet();
  ws->attach_condition(myListener->m_guardCond);
  DDS::ConditionSeq condSeq;
  while (!myListener->m_closed && count < 1500 ){
    // To avoid spinning here. We can either use a sleep or better a WaitSet.
    ws->wait(condSeq, timeout);
    myListener->m_guardCond->set_trigger_value(false);
    ++count;
 }

  cout << "===[ListenerDataSubscriber] Market Closed" << endl;

  //cleanup
  mgr.deleteReader(myListener->m_MsgReader.in ());
  mgr.deleteSubscriber();
  mgr.deleteTopic();
  mgr.deleteParticipant();
  delete myListener;
  cout << "Completed Listener example." << endl;
  return 0;
}
Beispiel #16
0
bool DDSBroker::createReader(std::string topicName, const ros::SubscribeQoSOptions& qos_ops)
{
  DDS::ReturnCode_t status;

  if (CORBA::is_nil(subscriber))
  {
    SubscriberQos sub_qos;
    //create a default subscriber
    status = participant->get_default_subscriber_qos(sub_qos);
    if (status != DDS::RETCODE_OK)
    {
      ROS_ERROR("[DDS] Failed to get the default DDS subscriber qos (%s).", RETCODE_DESC(status));
      return false;
    }

    sub_qos.partition.name.length(1);
    sub_qos.partition.name[0] = PARTITION_NAME;
    subscriber = participant->create_subscriber(sub_qos, NULL, STATUS_MASK_NONE);
    if (!subscriber.in())
    {
      ROS_ERROR("[DDS] Failed to create DDS subscriber.");
      return false;
    }
  }

  std::string ddsTopicName = ros2ddsName(topicName);
  Topic_var topic = getTopic(ddsTopicName);
  if (!topic.in())
  {
    ROS_ERROR("[DDS] Failed to get DDS topic %s while creating a reader.", topicName.c_str());
    return false;
  }

  DataReader_var reader;
  std::map<std::string, DataReader_var>::iterator iterReaderMap;

  iterReaderMap = reader_map.find(topicName);
  if (iterReaderMap != reader_map.end())
  {
    reader = iterReaderMap->second;
    return reader;
  }

  {
    boost::mutex::scoped_lock lock(reader_map_mutex);
    iterReaderMap = reader_map.find(ddsTopicName);
    if (iterReaderMap != reader_map.end())
      reader = iterReaderMap->second;
    else
    {
      DataReaderQos dr_qos;

      status = subscriber->get_default_datareader_qos(dr_qos);

      if (status != DDS::RETCODE_OK)
      {
        ROS_ERROR("[DDS] Failed to get the default DDS data reader qos.");
        return false;
      }

      if (qos_ops.using_best_effort_protocol)
        dr_qos.reliability.kind = BEST_EFFORT_RELIABILITY_QOS;
      else
        dr_qos.reliability.kind = RELIABLE_RELIABILITY_QOS;

      if (qos_ops.data_centric_update)
        dr_qos.history.kind = KEEP_LAST_HISTORY_QOS;
      else
        dr_qos.history.kind = KEEP_ALL_HISTORY_QOS;

      if (qos_ops.ordered_by_sending_timestamp)
        dr_qos.destination_order.kind = BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS;
      else
        dr_qos.destination_order.kind = BY_RECEPTION_TIMESTAMP_DESTINATIONORDER_QOS;
        

      if (qos_ops.time_filter_duration != ros::DURATION_MIN)
      {
        dr_qos.time_based_filter.minimum_separation.sec = qos_ops.time_filter_duration.sec;
        dr_qos.time_based_filter.minimum_separation.nanosec = qos_ops.time_filter_duration.nsec;
      }

      // we have to set VOLATILE_DURABILITY_QOS because of the RxO policy compatibility
      dr_qos.durability.kind = VOLATILE_DURABILITY_QOS;

      reader = subscriber->create_datareader(topic.in(), dr_qos, NULL, STATUS_MASK_NONE);
      if (!reader.in())
      {
        ROS_ERROR("[DDS] Failed to create reader on topic %s.", topicName.c_str());
        return false;
      }

      reader_map.insert(std::pair<std::string, DataReader_var>(ddsTopicName, reader));
    }
  }

  return reader;
}
Beispiel #17
0
int read (int expect_success)
{
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) read begins. \n")));

  try
  {
    ::Xyz::FooDataReader_var foo_dr
      = ::Xyz::FooDataReader::_narrow(datareader.in ());
    if (CORBA::is_nil (foo_dr.in ()))
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                 ACE_TEXT("(%P|%t) ::Xyz::FooDataReader::_narrow failed.\n")),
                 -1);
    }

    ::Xyz::FooDataReaderImpl* dr_servant =
      dynamic_cast< ::Xyz::FooDataReaderImpl*> (foo_dr.in ());

    int num_reads = 0;
    int num_received = 0;

    bool init_val = false;
    ACE_Array<bool> messages(num_writes, init_val);

    while ( num_reads < num_writes)
    {

      ::Xyz::Foo foo;
      ::DDS::SampleInfo si ;

      DDS::ReturnCode_t status = dr_servant->read_next_sample(foo, si) ;
      num_reads ++;

      if (status == ::DDS::RETCODE_OK)
      {
        if (!expect_success)
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT("(%P|%t) ERROR: received an unexpected sample!\n"))
                             , -1);

        }
        num_received++;

        if (default_key != foo.key)
        {
          ACE_ERROR ((LM_ERROR,
            ACE_TEXT("(%P|%t) ERROR: reader received incorrect key!\n")
                      ));
        }
        int msg_num = (int) foo.x;
        if ((0 <= msg_num) && (msg_num< num_writes))
        {
          messages[msg_num] = true;
        }
        else
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: reader received unexpected message number %d!\n"),
                      msg_num));
        }

        ACE_OS::fprintf(stderr, "foo.x = %f foo.y = %f, foo.key = %d\n",
                        foo.x, foo.y, foo.key);
      }
      else if (status == ::DDS::RETCODE_NO_DATA)
      {
        if (expect_success)
        {
          ACE_ERROR ((LM_ERROR,
            ACE_TEXT("(%P|%t) ERROR: read returned ::DDS::RETCODE_NO_DATA!\n")));
          ACE_OS::sleep(1);
        }
      }
      else
      {
        ACE_ERROR ((LM_ERROR,
          ACE_TEXT("(%P|%t) ERROR: read returned error %d\n"), status));
      }
    }

    int num_expected = num_writes;
    if (ignore_kind != DONT_IGNORE)
    {
       num_expected = 0;
    }

    if (num_received == num_expected)
    {
      for (int k = 0; k < num_expected; k ++)
      {
        if ( !messages[k] )
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT("(%P|%t) ERROR: reader did not receive message %d!\n"),
                             k), -1);
        }
      }
    }
    else
    {
       ACE_ERROR_RETURN ((LM_ERROR,
                          ACE_TEXT("(%P|%t) ERROR: reader received %d messages expected %d ")
                          ACE_TEXT("messages!\n"), num_received, num_expected),
                          -1);
    }
  }
  catch (...)
  {
    ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t) Exception caught in read."), -1);
  }

  ACE_DEBUG((LM_DEBUG,
              ACE_TEXT("(%P|%t) read done.\n")));

  return 0;
}
Beispiel #18
0
int NodeWifiHandler (int argc, char *argv[])
{

  // DDS değişkenleri
  ReturnCode_t                        status;
  InstanceHandle_t                    userHandle;
  DDSEntityManager                    mgrReqSub;
  DDSEntityManager                    mgrReqPub;
  DDSEntityManager                    mgrWifiPub;
  WifiSeq                             *wifiSeqInstance = new WifiSeq();;
  ServerReqSeq                        serverReqSeq;
  ServerReq                           *serverReq = new ServerReq();
  SampleInfoSeq_var                   infoSeq = new SampleInfoSeq();

  // Zaman ile alakalı değişkenler
  DDS::Duration_t                     waitAckTime = { 0, 800000000 }; //800ms
  int                                 refreshRate = 60;
  long int                            messageIDCount = 0;
  Time_t                              tsBeforeTheScan = { 0, 0 };
  Time_t                              tsAfterTheScan = { 0, 0 };
  struct timeval                      tsConverter;

  // Veri tutucular (data structures)
  vector<string>                      modemIdHolder;
  vector<int>                         dbmHolder;
  string                              wifiFileContenHolder;
  string                              ifconfigFileContentHolder;


  // Wifi tarama sonuçlarının yazdırıldığı dosyadan okuma yapacak
  // olan değişken
  boost::filesystem::ifstream         fInWifiScan, fInIfconfig;

  // Matlab komutları ayrıştırılmasında kullanılacak olan değişkenler
  string                              ip, subnet, gateway, dns, nodeName;

  char                                hostName[1024];
  gethostname(hostName, 1024);

  // Bluetooth tarama sıklığı ayarlayan değişken
  int refreshRateCounter = -1;


  // !!! Wifi tarama mesajlarını Publish edecek Topic yaratılıyor
  // ve o Topic'e ait konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrWifiPub.createParticipant("KonSensData_WifiSeq_Participant");

  // WifiSeq tipi yaratılıyor
  WifiSeqTypeSupport_var wifiSeqTS = new WifiSeqTypeSupport();
  mgrWifiPub.registerType(wifiSeqTS.in());

  // Topic yaratılıyor
  char wifiPubTopicName[] = "KonSensData_WifiSeq_Topic";
  mgrWifiPub.createTopic(wifiPubTopicName);

  // Publisher yaratılıyor
  mgrWifiPub.createPublisher();

  // DataWriter yaratılıyor
  bool autodisposeUnregisteredInstances = false;
  mgrWifiPub.createWriter(autodisposeUnregisteredInstances,
                          KEEP_ALL_HISTORY_QOS,
                          BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS);

  // Yaratılan DataWriter, WifiSeq tipi için özelleştiriliyor
  DataWriter_var dWriterWifPub = mgrWifiPub.getWriter();
  WifiSeqDataWriter_var wifiSeqWriter =
      WifiSeqDataWriter::_narrow(dWriterWifPub.in());

  // Düğüm numarası atanıyor
  wifiSeqInstance->userID = 13;

  cout << "=== [Publisher of KonSensData_WifiSeq_Topic] Ready ..." << endl;


  // !!! Sunucudan gelen komutlara Subscribe olacak olan Topic yaratılıyor
  // ve o Topic için gerekli konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrReqSub.createParticipant(
        "KonSensData_ServerReq_Participant_Server_to_Node");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrSubscriberTS = new ServerReqTypeSupport();
  mgrReqSub.registerType(mgrSubscriberTS.in());

  // Topic yaratılıyor
  char reqSubTopicName[] = "KonSensData_ServerReq_Topic_Server_to_Node";
  mgrReqSub.createTopic(reqSubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Subscriber yaratılıyor
  mgrReqSub.createSubscriber();

  // DataReader yaratılıyor
  mgrReqSub.createReader(KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataReader_var dReadeSub = mgrReqSub.getReader();
  ServerReqDataReader_var serverReqReader =
      ServerReqDataReader::_narrow(dReadeSub.in());
  checkHandle(serverReqReader.in(), "ServerReqDataReader::_narrow");

  cout << "=== [Subscriber of KonSensData_ServerReq_Topic_Server_to_Node]"
          " Ready ..." << endl;


  // !!! Sunucudan gelen komutlar ayrıştırılıp işlendikten sonra Response
  // mesajını Publish edecek olan Topic yaratılıyor

  // Domain participant yaratılıyor
  mgrReqPub.createParticipant(
        "KonSensData_ServerReq_Participant_Node_to_Server");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrPublisherTS = new ServerReqTypeSupport();
  mgrReqPub.registerType(mgrPublisherTS.in());

  // Topic yaratılıyor
  char reqPubTopicName[] = "KonSensData_ServerReq_Topic_Node_to_Server";
  mgrReqPub.createTopic(reqPubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Publisher yaratılıyor
  mgrReqPub.createPublisher();

  // DataWriter yaratılıyor
  // Not: Kullanılan autodisposeUnregisteredInstances değişkeni
  // WifiSeqDataWriter yaratılırken ki kullananla aynıdır
  mgrReqPub.createWriter(autodisposeUnregisteredInstances,
                         KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataWriter_var dWriterPub = mgrReqPub.getWriter();
  ServerReqDataWriter_var serverReqWriter =
      ServerReqDataWriter::_narrow(dWriterPub.in());

  cout << "=== [Publisher of KonSensData_ServerReq_Topic_Node_to_Server] "
          "Ready ..." << endl;

  // Yenileme sıklığını belirleyecek olan 'timelimit' değişkeni yaratılıyor.
  Timeout timeLimit(std::chrono::milliseconds(refreshRate*1000));

  while(true)
  {
    if (timeLimit.isExpired() || refreshRateCounter == -1)
    {

      // Wifi mesajını Publish etmek için hazırlık yapılıyor.
      cout << "-----------------------------------" << endl;

      wifiSeqInstance->messageID = messageIDCount;

      // Tarama öncesi alınan zaman etiketi (timestamp[0])
      gettimeofday(&tsConverter, NULL);
      tsBeforeTheScan.sec = tsConverter.tv_sec;
      tsBeforeTheScan.nanosec = (tsConverter.tv_usec * 1000);
      cout << " timestamp[0] (before the scan) = " << tsBeforeTheScan.sec
           << '.';
      cout << setfill('0') << setw(9) << (tsBeforeTheScan.nanosec)
           << endl;

      // Wifi taraması yapılıyor ve ardından tarama sonuçları 'wifi_rssi'
      // dosyasına yazdırılıyor.
      system("sudo iwlist wlan0 scanning >> wifi_rssi.txt");

      // Wifi bağlantısı kapatılıyor
      system("sudo ifconfig wlan0 down");

      // Wifi tarama dosyası okunuyor
      fInWifiScan.open("wifi_rssi.txt",ios::in);

      stringstream ssWifi;
      ssWifi << fInWifiScan.rdbuf();
      wifiFileContenHolder = ssWifi.str();
      system("rm wifi_rssi.txt");
      try
      {
        // Okunan dosya boost kütüphane yardımıyla ayrıştırılıyor
        boost::regex exp( "Signal level=.*?([0-9]+)") ;
        boost::regex expAd( "Address: ([0-9A-F:]{17})" ) ;
        boost::match_results<string::const_iterator> whatAd;
        string::const_iterator startAd =
            wifiFileContenHolder.begin() ;
        string::const_iterator finishAd =
            wifiFileContenHolder.end() ;

        while (boost::regex_search(startAd, finishAd,
                                   whatAd, expAd))
        {
          modemIdHolder.push_back(whatAd[1]);
          startAd = whatAd[0].second ;
        }

        boost::match_results<string::const_iterator> what;

        string::const_iterator start = wifiFileContenHolder.begin();
        string::const_iterator finish = wifiFileContenHolder.end();

        while (boost::regex_search(start, finish, what, exp))
        {
          string foundDbm(what[1]);
          dbmHolder.push_back(atoi(foundDbm.c_str()));
          start = what[0].second ;
        }

        cout << " Number of Wifi Network that has been founded: "
             << dbmHolder.size() << endl;

        // Tarama sonrası alınan zaman etiketi (timestamp[1])
        gettimeofday(&tsConverter, NULL);
        tsAfterTheScan.sec = tsConverter.tv_sec;
        tsAfterTheScan.nanosec = (tsConverter.tv_usec * 1000);
        cout << " timestamp[1] (after the scan) = "
             << tsAfterTheScan.sec << '.';
        cout << setfill('0') << setw(9) << (tsAfterTheScan.nanosec)
             << endl;

        // Ayrıştırılan Wifi tarama dosyası ve alınan zaman etiketleri,
        // Publish edilecek olan mesaj değişkenlerine kaydediliyor
        wifiSeqInstance->timestamp[0][0] = tsBeforeTheScan.nanosec;
        wifiSeqInstance->timestamp[0][1] = tsBeforeTheScan.sec;
        wifiSeqInstance->timestamp[1][0] = tsAfterTheScan.nanosec;
        wifiSeqInstance->timestamp[1][1] = tsAfterTheScan.sec;

        wifiSeqInstance->messages.length(modemIdHolder.size());
        cout << " MessageID: " << wifiSeqInstance->messageID << endl;
        for(int i = 0; i < modemIdHolder.size(); i++)
        {
          Msg msg;
          msg.devID = DDS::string_dup(modemIdHolder[i].c_str());
          msg.hostName = DDS::string_dup(hostName);
          msg.dbm = -dbmHolder[i];
          wifiSeqInstance->messages[i] = msg;

        }

        // Publish edilmeden önce, bir önceki mesajın acknowlegde mesajı
        // bekleniyor
        wifiSeqWriter->wait_for_acknowledgments(waitAckTime);
        status = wifiSeqWriter->write(*wifiSeqInstance,DDS::HANDLE_NIL);

        checkStatus(status, "konsensSensDugWifiSeqTopic::"
                            "WifiSeqDataWriter::write_w_timestamp");

        // Wifi bağlantısı tekrar açılıyor
        system("sudo ifconfig wlan0 up");

        messageIDCount++;
      }

      catch ( boost::bad_expression & ex )
      {
        cout << ex.what() ;
      }

      modemIdHolder.clear();
      dbmHolder.clear();
      wifiFileContenHolder.clear();
      fInWifiScan.close();

      cout << "-----------------------------------" << endl;

      timeLimit.setTimerToZero();

      // Tarama sıklığını belirleyen değişken sıfırlanıyor
      refreshRateCounter = 0;
      cout << refreshRateCounter << endl;

    } // Wifi Publisher kısmının sonu


    // Sunucu tarafından gönderilen Matlab komutlarına Subscribe olunuyor
    else
    {
      status = serverReqReader->take(serverReqSeq,
                                     infoSeq,
                                     LENGTH_UNLIMITED,
                                     ANY_SAMPLE_STATE,
                                     ANY_VIEW_STATE,
                                     ANY_INSTANCE_STATE);
      checkStatus(status, "severReqDataReader::take");

      // isDataReceived değişkeni bir kontrol değişkeni olup, Matlab komut
      // bilgisini içeren mesaja Subscribe olunduysa true, olunmadıysa false
      // değerini tutar
      bool isDataReceived = false;

      for (DDS::ULong j = 0; j < serverReqSeq.length(); j++)
      {

        if(infoSeq[j].valid_data)
        {
          cout << "=== [Subscriber] message received :" << endl;
          cout << "    Received Request Message  : "
               << serverReqSeq[j].request << endl;
          cout << "    Received RequestID : \""
               << serverReqSeq[j].requestID << "\"" << endl;

          // Rapidjson yapılandırıcısı yaratılıyor
          Document d;
          if(d.Parse(serverReqSeq[j].request).HasParseError())
            cout << " Parsing Error!" << endl;
          StringBuffer nodeIdBuffer;
          Writer<StringBuffer> nodeIdWriter(nodeIdBuffer);
          d["NodeID"].Accept(nodeIdWriter);
          string tempNodeId = nodeIdBuffer.GetString();

          // Subscribe olunan mesajın düğüme ait olup olmadığı kontrol ediliyor
          if (tempNodeId == "\"SensDug13\"")
          {
            StringBuffer buffer;

            // Reset komutunun gelip gelmediği kontrol ediliyor.
            Value::ConstMemberIterator itr = d.FindMember("Reset");
            if(itr != d.MemberEnd())
            {
              // Resetin değeri falsedan trueya çevriliyor
              Value& s = d["Reset"];
              s.SetBool(true);

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d.Accept(writer);

              cout << "    Request Message is modified to  : "
                   << buffer.GetString() << endl;

              // Publish edilecek Response mesajı hazırlanıyor
              string str = buffer.GetString();
              str.append("\n");
              serverReq->request = DDS::string_dup(str.c_str());
              serverReq->requestID = serverReqSeq[j].requestID;

              if(!isDataReceived && status == DDS::RETCODE_OK)
              {
                // Response mesajı gönderiliyor
                ReturnCode_t tempStatus = serverReqWriter->write(
                      *serverReq, DDS::HANDLE_NIL);
                checkStatus(tempStatus, "severReqDataReader::write");
                isDataReceived = true;

                cout << "    Response Request Message is sent : "
                     << serverReq->request << endl;
                cout << "    Response RequestID is sent : \""
                     << serverReq->requestID << "\"" << endl;

              }

              // Sistem yeniden başlatılıyor !!!
              cout << "reboot" << endl;
              system("sudo reboot");
            }

            // GetRefreshRate ve SetRefreshRate komutundan herhangi birinin
            // gelip gelmediği kontrol ediliyor
            itr = d.FindMember("SetRefreshRate");
            if(itr != d.MemberEnd())
            {
              string refreshRateString;
              int refreshRateInt;

              // Status değeri falsedan trueya çevriliyor
              Value& s = d["Status"];
              s.SetBool(true);

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d["SetRefreshRate"].Accept(writer);
              refreshRateString = buffer.GetString();

              // Gelen mesajda fazladan çift tırnak ile bulunuyor
              // Örneğin, ""15""
              // Bu yüzden ilk son karakterler kırpılıyor
              refreshRateString =
                  refreshRateString.substr(1, refreshRateString.size()-1);
              // Refresh rate değeri stringden integera çevriliyor
              refreshRateInt = atoi(refreshRateString.c_str());

              // Refresh rate değişkeni güncelleniyor
              refreshRate = refreshRateInt;
              timeLimit.setMaxDuration(std::chrono::milliseconds
                                       (refreshRate*1000));

            }

            itr = d.FindMember("GetRefreshRate");
            if(itr != d.MemberEnd())
            {
              // Status değeri falsedan trueya çevriliyor
              Value& s = d["Status"];
              s.SetBool(true);

              Value& tempRefreshRate = d["GetRefreshRate"];

              // Güncel refresh rate değişken bilgisi alınıyor
              string str = to_string(refreshRate);
              tempRefreshRate.SetString(str.c_str(), str.length());
            }

            // GetAliveStatus komutunun gönderilip gönderilmediği kontrol
            // ediliyor.
            itr = d.FindMember("Alive");
            if(itr != d.MemberEnd())
            {
              // Alive değeri truedan false çevriliyor
              Value& s = d["Alive"];
              s.SetBool(true);

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d.Accept(writer);
            }

            // GetNetStatus komutunun gelip gelmediği kontrol ediliyor
            itr = d.FindMember("IP");
            if(itr != d.MemberEnd())
            {
              cout << "-----------------------------------" << endl;

              // Ağ durum bilgisi ifconfig.txt dosyasına yazdırılıyor
              system("cat /etc/network/interfaces >> ifconfig.txt");
              system("cat /etc/resolv.conf >> ifconfig.txt");
              system("echo -n hostname >> ifconfig.txt && hostname "
                     ">> ifconfig.txt");

              // ifconfig.txt dosyası açılıyor
              fInIfconfig.open("ifconfig.txt",ios::in);
              stringstream ssIfconfig;
              ssIfconfig << fInIfconfig.rdbuf();
              ifconfigFileContentHolder = ssIfconfig.str();
              system("rm ifconfig.txt");

              // Dosya içeriği ayrıştırılıyor
              try
              {
                boost::regex expIp
                    ("address (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expSubnet
                    ("netmask (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expGateway
                    ("gateway (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expDns
                    ("nameserver (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expNoneName
                    ("hostname.*");

                string::const_iterator startAd =
                    ifconfigFileContentHolder.begin() ;
                string::const_iterator finishAd =
                    ifconfigFileContentHolder.end() ;

                boost::match_results<string::const_iterator> whatIp;
                if ( boost::regex_search(startAd, finishAd,
                                         whatIp, expIp) )
                {
                  ip = whatIp[0];
                  cout << ip << endl;
                  string chopped_str = "address ";
                  string::size_type i = ip.find(chopped_str);
                  if (i != string::npos)
                    ip.erase(i, chopped_str.length());

                  Value& tempIp = d["IP"];
                  tempIp.SetString(ip.c_str(), ip.length());
                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;

                boost::match_results<string::const_iterator> whatSubnet;
                if ( boost::regex_search(startAd, finishAd,
                                         whatSubnet, expSubnet) )
                {
                  subnet = whatSubnet[0];
                  cout << subnet << endl;
                  string chopped_str = "netmask ";
                  string::size_type i = subnet.find(chopped_str);
                  if (i != string::npos)
                    subnet.erase(i, chopped_str.length());

                  Value& tempSubnet = d["Subnet"];
                  tempSubnet.SetString(subnet.c_str(),
                                       subnet.length());

                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;
                boost::match_results<string::const_iterator> whatGateway;

                if ( boost::regex_search(startAd, finishAd,
                                         whatGateway, expGateway) )
                {
                  gateway = whatGateway[0];
                  cout << gateway << endl;
                  string chopped_str = "gateway ";
                  string::size_type i = gateway.find(chopped_str);
                  if (i != string::npos)
                    gateway.erase(i, chopped_str.length());

                  Value& tempGateway = d["Gateway"];
                  tempGateway.SetString(gateway.c_str(),
                                        gateway.length());


                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;
                boost::match_results<string::const_iterator> whatDns;

                if ( boost::regex_search(startAd, finishAd,
                                         whatDns, expDns) )
                {
                  dns = whatDns[0];
                  cout << dns << endl;
                  string chopped_str = "nameserver ";
                  string::size_type i = dns.find(chopped_str);
                  if (i != string::npos)
                    dns.erase(i, chopped_str.length());

                  Value& tempDns = d["DNS"];
                  tempDns.SetString(dns.c_str(), dns.length());
                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;
                boost::match_results<string::const_iterator> whatNodeName;

                if ( boost::regex_search(startAd, finishAd,
                                         whatNodeName, expNoneName) )
                {
                  nodeName = whatNodeName[0];
                  cout << nodeName << endl;
                  string chopped_str = "hostname";
                  string::size_type i = nodeName.find(chopped_str);
                  if (i != string::npos)
                    nodeName.erase(i, chopped_str.length());
                  nodeName.erase(remove(nodeName.begin(),
                                        nodeName.end(),
                                        '\n'),
                                 nodeName.end());

                  Value& tempNodeName = d["Name"];
                  tempNodeName.SetString(nodeName.c_str(),
                                         nodeName.length());
                }

                cout << ip << endl;
                cout << subnet << endl;
                cout << dns << endl;
                cout << nodeName << endl;
              } // Dosya ayrıştırma işlemi bitti

              catch ( boost::bad_expression & ex )
              {
                cout << ex.what() ;
              }

              ifconfigFileContentHolder.clear();
              fInIfconfig.close();

              cout << "-----------------------------------" << endl;

              // GetNetStatus komutuna ait status değeri falsedan trueya
              // çevriliyor.
              Value& s = d["Status"];
              s.SetBool(true);
            }

            // Matlab'dan gelen mesaj içeriğinin ayrıştırılıp düzenlenme işlemi
            // tamamlandı ve sunucuya Response mesajını Publish etmek için
            // aşağıdaki adımlar gerçekleştiriliyor

            // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
            StringBuffer responseBuffer;
            Writer<StringBuffer> writer(responseBuffer);
            d.Accept(writer);

            cout << "    Request Message is modified to  : "
                 << responseBuffer.GetString() << endl;

            // Response mesajı hazırlanıyor
            string str = responseBuffer.GetString();
            str.append("\n");
            serverReq->request = DDS::string_dup(str.c_str());
            //serverReq->request = DDS::string_dup("Hello World\n");
            serverReq->requestID = serverReqSeq[j].requestID;

            if(!isDataReceived && status == DDS::RETCODE_OK)
            {
              // Response mesajı Publish ediliyor
              ReturnCode_t tempStatus = serverReqWriter->write(
                    *serverReq, DDS::HANDLE_NIL);
              checkStatus(tempStatus, "severReqDataReader::write");
              isDataReceived = true;

              cout << "    Response Request Message is sent : "
                   << serverReq->request << endl;
              cout << "    Response RequestID is sent : \""
                   << serverReq->requestID << "\"" << endl;
            }
          }

          else
            cout << "Invalid NodeID!" << endl;
        }

      }

      status = serverReqReader->return_loan(serverReqSeq, infoSeq);
      checkStatus(status, "MsgDataReader::return_loan");

      refreshRateCounter++;
      cout << refreshRateCounter << endl;

    } // Matlab komutuna Subscribe olma kısmının sonu

    // Terminalde akacak olan çıktıları dah gözle görülebilir bir şekilde
    // yazdırmak için koyulmuştur
    fake_delay();
  }

  // Hafıza temizle işlemleri gerçekleştiriliyor

  status = wifiSeqWriter->dispose(*wifiSeqInstance, userHandle);
  checkStatus(status, "WifiSeqDataWriter::dispose");
  status = wifiSeqWriter->unregister_instance(*wifiSeqInstance, userHandle);
  checkStatus(status, "WifiSeqDataWriter::unregister_instance");

  delete wifiSeqInstance;
  delete serverReq;

  mgrWifiPub.deleteWriter();
  mgrWifiPub.deletePublisher();
  mgrWifiPub.deleteTopic();
  mgrWifiPub.deleteParticipant();

  mgrReqSub.deleteReader();
  mgrReqSub.deleteSubscriber();
  mgrReqSub.deleteTopic();
  mgrReqSub.deleteParticipant();

  mgrReqPub.deletePublisher();
  mgrReqPub.deleteWriter();
  mgrReqPub.deleteTopic();
  mgrReqPub.deleteParticipant();

  return 0;
}