Exemple #1
0
std::vector<topic> generate_time_of_day_topics(const bool /*sort_generated*/)
{
	std::vector<topic> topics;
	std::stringstream toplevel;

	if (! resources::tod_manager) {
		toplevel << N_("Only available during a scenario.");
		topics.push_back( topic("Time of Day Schedule", "..schedule", toplevel.str()) );
		return topics;
	}
	const std::vector<time_of_day>& times = resources::tod_manager->times();
	BOOST_FOREACH(const time_of_day& time, times)
	{
		const std::string id = "time_of_day_" + time.id;
		const std::string image = "<img>src='" + time.image + "'</img>";
		std::stringstream text;

		toplevel << make_link(time.name.str(), id) << jump_to(160) <<
				image << jump(30) << time.lawful_bonus << '\n';

		text << image << '\n' <<
				time.description.str() << '\n' <<
				"Lawful Bonus: " << time.lawful_bonus << '\n' <<
				'\n' << make_link(N_("Schedule"), "..schedule");

		topics.push_back( topic(time.name.str(), id, text.str()) );
	}

	topics.push_back( topic("Time of Day Schedule", "..schedule", toplevel.str()) );
	return topics;
}
Exemple #2
0
void CoreIrcChannel::setEncrypted(bool e)
{
    if (!Cipher::neededFeaturesAvailable())
        return;

    if (e) {
        if (topic().isEmpty())
            return;

        QByteArray decrypted = cipher()->decryptTopic(topic().toAscii());
        setTopic(decodeString(decrypted));
    }
}
Exemple #3
0
QString ChannelBufferItem::toolTip(int column) const
{
    Q_UNUSED(column);
    QStringList toolTip;

    toolTip.append(tr("<b>Channel %1</b>").arg(Qt::escape(bufferName())));
    if (isActive()) {
        //TODO: add channel modes
        toolTip.append(tr("<b>Users:</b> %1").arg(nickCount()));
        if (_ircChannel) {
            QString channelMode = _ircChannel->channelModeString(); // channelModeString is compiled on the fly -> thus cache the result
            if (!channelMode.isEmpty())
                toolTip.append(tr("<b>Mode:</b> %1").arg(channelMode));
        }

        ItemViewSettings s;
        bool showTopic = s.displayTopicInTooltip();
        if (showTopic) {
            QString _topic = topic();
            if (_topic != "") {
                _topic = stripFormatCodes(_topic);
                _topic = Qt::escape(_topic);
                toolTip.append(QString("<font size='-2'>&nbsp;</font>"));
                toolTip.append(tr("<b>Topic:</b> %1").arg(_topic));
            }
        }
    }
    else {
        toolTip.append(tr("Not active <br /> Double-click to join"));
    }

    return tr("<p> %1 </p>").arg(toolTip.join("<br />"));
}
Exemple #4
0
//	////////////////////////////////////////////////////////////////////////////
LbmSrc::LbmSrc(LbmContext &context, const std::string &topic_name)
	:LbmObjectBase<lbm_src_t>()
{
	LbmTopicSrc topic(context, topic_name);

	Initialize(context, topic, NULL, NULL, NULL);
}
Exemple #5
0
void CSkypeProto::OnLoadChats(const NETLIBHTTPREQUEST *response)
{
	if (response == NULL)
		return;

	JSONNode root = JSONNode::parse(response->pData);
	if (!root)
		return;

	const JSONNode &metadata = root["_metadata"];
	const JSONNode &conversations = root["conversations"].as_array();

	int totalCount = metadata["totalCount"].as_int();
	std::string syncState = metadata["syncState"].as_string();

	if (totalCount >= 99 || conversations.size() >= 99)
		PushRequest(new SyncHistoryFirstRequest(syncState.c_str(), (char*)m_szRegToken), &CSkypeProto::OnSyncHistory);

	for (size_t i = 0; i < conversations.size(); i++)
	{
		const JSONNode &conversation = conversations.at(i);
		const JSONNode &lastMessage = conversation["lastMessage"];
		const JSONNode &threadProperties = conversation["threadProperties"];
		if (!lastMessage)
			continue;

		std::string conversationLink = lastMessage["conversationLink"].as_string();
		if (conversationLink.find("/19:") != -1)
		{
			CMStringA skypename(ChatUrlToName(conversationLink.c_str()));
			CMString topic(threadProperties["topic"].as_mstring());
			SendRequest(new GetChatInfoRequest(m_szRegToken, skypename, m_szServer), &CSkypeProto::OnGetChatInfo, topic.Detach());
		}
	}
}
Exemple #6
0
WWidget *EventsDemo::wKeyEvent()
{
  WContainerWidget *result = new WContainerWidget();

  topic("WKeyEvent", result);
  addText(tr("events-WKeyEvent-1"), result);
  WLineEdit *l = new WLineEdit(result);
  l->setTextSize(50);
  l->keyWentUp().connect(this, &EventsDemo::showKeyWentUp);
  l->keyWentDown().connect(this, &EventsDemo::showKeyWentDown);
  
  addText(tr("events-WKeyEvent-2"), result);
  l = new WLineEdit(result);
  l->setTextSize(50);
  l->keyPressed().connect(this, &EventsDemo::showKeyPressed);
  
  addText(tr("events-WKeyEvent-3"), result);
  l = new WLineEdit(result);
  l->setTextSize(50);
  l->enterPressed().connect(this, &EventsDemo::showEnterPressed);
  l->escapePressed().connect(this, &EventsDemo::showEscapePressed);
  new WBreak(result);
  addText("Last event: ", result);
  keyEventType_ = new WText(result);
  new WBreak(result);
  keyEventDescription_ = new WText(result);

  return result;
}
/**  \brief Initializes motor trace publisher
 */
bool MotorModel::initialize(const ethercat_hardware::ActuatorInfo &actuator_info, 
                            const ethercat_hardware::BoardInfo &board_info)
{
  std::string topic("motor_trace");
  if (!actuator_info.name.empty())
    topic = topic + "/" + actuator_info.name;
  publisher_ = new realtime_tools::RealtimePublisher<ethercat_hardware::MotorTrace>(ros::NodeHandle(), topic, 1, true);
  if (publisher_ == NULL) 
    return false;

  actuator_info_ = actuator_info;
  board_info_ = board_info;

  if (actuator_info_.speed_constant > 0.0) {
    backemf_constant_ = 1.0 / (actuator_info_.speed_constant * 2.0 * M_PI * 1.0/60.0);
  } else {
    ROS_ERROR("Invalid speed constant of %f for %s", actuator_info_.speed_constant, actuator_info_.name.c_str());
    return false;
  }

  current_error_limit_ = board_info_.hw_max_current * 0.30;

  {
    ethercat_hardware::MotorTrace &msg(publisher_->msg_);
    msg.actuator_info = actuator_info;  
    msg.board_info = board_info;
    msg.samples.reserve(trace_size_);
  } 

  return true;
}
Exemple #8
0
DDEconversation::DDEconversation(const char *_server, const char *_topic)
        : hConv(NULL)
{
    DDEstring server(_server);
    DDEstring topic(_topic);
    hConv = DdeConnect(*DDEbase::base, server, topic, NULL);
}
Exemple #9
0
void
dds::topic::detail::Topic<T>::listener_notify(
        ObjectDelegate::ref_type source,
        uint32_t                 triggerMask,
        void                    *eventData,
        void                    *l)
{
    /* The EntityDelegate takes care of the thread safety and always
     * provides a listener and source. */
    dds::topic::TopicListener<T>* listener =
            reinterpret_cast<dds::topic::TopicListener<T>*>(l);
    assert(listener);

    /* Get Topic wrapper from given source EntityDelegate. */
    typename Topic::ref_type ref =
            OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<Topic<T> >(source);
    dds::topic::Topic<T, dds::topic::detail::Topic> topic(ref->wrapper());

    if (triggerMask & V_EVENT_INCONSISTENT_TOPIC) {
        dds::core::status::InconsistentTopicStatus status;
        status.delegate().v_status(v_topicStatus(eventData)->inconsistentTopic);
        listener->on_inconsistent_topic(topic, status);
    }

    if (triggerMask & V_EVENT_ALL_DATA_DISPOSED ) {
        org::opensplice::topic::TopicListener<T>* extListener =
                  dynamic_cast<org::opensplice::topic::TopicListener<T>*>(listener);
        if (extListener) {
            org::opensplice::core::status::AllDataDisposedTopicStatus status;
            status.delegate().v_status(v_topicStatus(eventData)->allDataDisposed);
            extListener->on_all_data_disposed(topic, status);
        }
    }
}
Exemple #10
0
/**
 * This function performs the publisher role in this example.
 * @return 0 if a sample is successfully written, 1 otherwise.
 */
int publisher(int argc, char *argv[])
{
    int result = 0;
    try
    {
        /** A dds::domain::DomainParticipant is created for the default domain. */
        dds::domain::DomainParticipant dp(org::opensplice::domain::default_id());

        /** The Durability::Transient policy is specified as a dds::topic::qos::TopicQos
         * so that even if the subscriber does not join until after the sample is written
         * then the DDS will still retain the sample for it. The Reliability::Reliable
         * policy is also specified to guarantee delivery. */
        dds::topic::qos::TopicQos topicQos
             = dp.default_topic_qos()
                << dds::core::policy::Durability::Transient()
                << dds::core::policy::Reliability::Reliable();

        /** A dds::topic::Topic is created for our sample type on the domain participant. */
        dds::topic::Topic<HelloWorldData::Msg> topic(dp, "HelloWorldData_Msg", topicQos);

        /** A dds::pub::Publisher is created on the domain participant. */
        std::string name = "HelloWorld example";
        dds::pub::qos::PublisherQos pubQos
            = dp.default_publisher_qos()
                << dds::core::policy::Partition(name);
        dds::pub::Publisher pub(dp, pubQos);

        /** The dds::pub::qos::DataWriterQos is derived from the topic qos and the
         * WriterDataLifecycle::ManuallyDisposeUnregisteredInstances policy is
         * specified as an addition. This is so the publisher can optionally be run (and
         * exit) before the subscriber. It prevents the middleware default 'clean up' of
         * the topic instance after the writer deletion, this deletion implicitly performs
         * DataWriter::unregister_instance */
        dds::pub::qos::DataWriterQos dwqos = topic.qos();
        dwqos << dds::core::policy::WriterDataLifecycle::ManuallyDisposeUnregisteredInstances();

        /** A dds::pub::DataWriter is created on the Publisher & Topic with the modififed Qos. */
        dds::pub::DataWriter<HelloWorldData::Msg> dw(pub, topic, dwqos);

        /** A sample is created and then written. */
        HelloWorldData::Msg msgInstance(1, "Hello World");
        dw << msgInstance;

        std::cout << "=== [Publisher] written a message containing :" << std::endl;
        std::cout << "    userID  : " << msgInstance.userID() << std::endl;
        std::cout << "    Message : \"" << msgInstance.message() << "\"" << std::endl;

        /* A short sleep ensures time is allowed for the sample to be written to the network.
        If the example is running in *Single Process Mode* exiting immediately might
        otherwise shutdown the domain services before this could occur */
        exampleSleepMilliseconds(1000);
    }
    catch (const dds::core::Exception& e)
    {
        std::cerr << "ERROR: Exception: " << e.what() << std::endl;
        result = 1;
    }
    return result;
}
Exemple #11
0
int LuaLobby::ChangeTopic(lua_State *L)
{
	LuaLobby* lob = toLuaLobby(L, 1);
	std::string channame(luaL_checkstring(L, 2));
	std::string topic(luaL_checkstring(L, 3));
	lob->ChangeTopic(channame, topic);
	return 0;
}
Exemple #12
0
std::vector<topic> generate_weapon_special_topics(const bool sort_generated)
{
	std::vector<topic> topics;

	std::map<t_string, std::string> special_description;
	std::map<t_string, std::set<std::string, string_less> > special_units;

	BOOST_FOREACH(const unit_type_data::unit_type_map::value_type &i, unit_types.types())
	{
		const unit_type &type = i.second;
		// Only show the weapon special if we find it on a unit that
		// detailed description should be shown about.
		if (description_type(type) != FULL_DESCRIPTION)
		 	continue;

		std::vector<attack_type> attacks = type.attacks();
		for (std::vector<attack_type>::const_iterator it = attacks.begin();
					it != attacks.end(); ++it) {

			std::vector<std::pair<t_string, t_string> > specials = it->special_tooltips();
			for ( size_t i = 0; i != specials.size(); ++i )
			{
				special_description.insert(std::make_pair(specials[i].first, specials[i].second));

				if (!type.hide_help()) {
					//add a link in the list of units having this special
					std::string type_name = type.type_name();
					//check for variations (walking corpse/soulless etc)
					const std::string section_prefix = type.show_variations_in_help() ? ".." : "";
					std::string ref_id = section_prefix + unit_prefix + type.id();
					//we put the translated name at the beginning of the hyperlink,
					//so the automatic alphabetic sorting of std::set can use it
					std::string link = make_link(type_name, ref_id);
					special_units[specials[i].first].insert(link);
				}
			}
		}
	}

	for (std::map<t_string, std::string>::iterator s = special_description.begin();
			s != special_description.end(); ++s) {
		// use untranslated name to have universal topic id
		std::string id = "weaponspecial_" + s->first.base_str();
		std::stringstream text;
		text << s->second;
		text << "\n\n" << _("<header>text='Units having this special attack'</header>") << "\n";
		std::set<std::string, string_less> &units = special_units[s->first];
		for (std::set<std::string, string_less>::iterator u = units.begin(); u != units.end(); ++u) {
			text << (*u) << "\n";
		}

		topics.push_back( topic(s->first, id, text.str()) );
	}

	if (sort_generated)
		std::sort(topics.begin(), topics.end(), title_less());
	return topics;
}
Exemple #13
0
/**
 * Runs the subscriber role of this example.
 * @return 0 if a sample was successfully read by the listener and the listener
 * received a notification of deadline expiration successfully, 1 otherwise.
 */
int subscriber(int argc, char *argv[])
{
    int result = 0;
    try
    {
        /** A domain participant, topic, and subscriber are created with matching QoS to
         the ::publisher */
        dds::domain::DomainParticipant dp(org::opensplice::domain::default_id());
        dds::topic::qos::TopicQos topicQos = dp.default_topic_qos()
                                                    << dds::core::policy::Durability::Transient()
                                                    << dds::core::policy::Reliability::Reliable()
                                                    << dds::core::policy::Deadline(dds::core::Duration(1, 0));
        dds::topic::Topic<ListenerData::Msg> topic(dp, "ListenerData_Msg", topicQos);
        dp.default_topic_qos(topicQos);
        std::string name = "Listener example";
        dds::sub::qos::SubscriberQos subQos
            = dp.default_subscriber_qos()
                << dds::core::policy::Partition(name);
        dds::sub::Subscriber sub(dp, subQos);
        dds::sub::qos::DataReaderQos drqos = topic.qos();

        /** An ExampleDataReaderListener and dds::core::status::StatusMask for the events
         * StatusMask::requested_deadline_missed() and StatusMask::data_available() are
         * both created and then specified when creating the dds::sub::DataReader */
        ExampleDataReaderListener listener;
        dds::core::status::StatusMask mask;
        mask << dds::core::status::StatusMask::data_available()
             << dds::core::status::StatusMask::requested_deadline_missed();
        std::cout << "=== [ListenerDataSubscriber] Set listener" << std::endl;
        dds::sub::DataReader<ListenerData::Msg> dr(sub, topic, drqos, &listener, mask);
        std::cout << "=== [ListenerDataSubscriber] Ready ..." << std::endl;

        /** The main thread then pauses until the listener thread has received a notification
         * that the deadline has expired (i.e. no more messages have been received for at least
         * 1 second) */
        int count = 0;
        while(! listener.deadline_expired_ && count < 20)
        {
            exampleSleepMilliseconds(1000);
            count++;
        }

        result = ! (listener.deadline_expired_ && listener.data_received_);

        /** Remove the ExampleDataReaderListener from the DataReader */
        dr.listener(0, dds::core::status::StatusMask::none());

        std::cout << "=== [ListenerDataSubscriber] Closed" << std::endl;
    }
    catch (const dds::core::Exception& e)
    {
        std::cerr << "ERROR: Exception: " << e.what() << std::endl;
        result = 1;
    }

    return result;
}
Exemple #14
0
//	////////////////////////////////////////////////////////////////////////////
LbmRcv::LbmRcv(LbmContext &context, const std::string &topic_name,
	lbm_rcv_cb_proc call_back, void *user_data_ptr,
	lbm_event_queue_t *event_queue)
	:LbmObjectBase<lbm_rcv_t>()
{
	LbmTopicRcv topic(context, topic_name);

	Initialize(context, topic, call_back, user_data_ptr, event_queue);
}
Exemple #15
0
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) {
    (void)mosq;
    QMosquitto *qmosq = (QMosquitto*)obj;

    QString topic(msg->topic);
    QString message((char*)msg->payload);

    qmosq->onReceived(topic, message);
}
Exemple #16
0
/*
// Name: make_action
// In: tag, the tag of the message.
//	   command, the command that was send.
//	   message, the trailing message (arguments).
//	   c, the client that sent the message.
//	   msg_is_quoted, wheater or no teh message contains quotes.
//	   clients, all connected clients.
//	   curr_topic, the current topic.
// Out: The action that the client want to do in it's connection.
// Purpose: Parses the command and does the proper action.
*/
int make_action(char* tag, char* command, char* message, 
				clientconn_t *c, char msg_is_quoted, 
				hash *clients, char *curr_topic) {
	if(strlen(tag)==0) {
		return 0;
	}
	if(strcmp(tag, "\r\n")==0) {
		client_write(c, "BAD No tag.\r\n", 13);
		return 0;
	}
	if(strlen(command)==0) {
		client_write(c, tag, strlen(tag));
		client_write(c, " BAD No command.\r\n", 18);
		return 0;
	}
	if(msg_is_quoted && !msg_is_correctly_quoted(message, msg_is_quoted) &&
		strcmp(command, "PRIVATE")) {
		return badly_formed(c, tag);
	}
	if(strcmp(command, "CAPABILITY")==0) {
		return capability(c, tag);
	}
	if(strcmp(command, "JOIN")==0) {
		return join(c, tag, clients);
	}
	if(strcmp(command, "NICK")==0) {
		return nick(c, tag, message, msg_is_quoted, clients);
	}
	if(strcmp(command,"QUIT")==0) {
		return quit(c, tag, clients);
	}
	if(!c->joined) {
		return not_joined(c, tag);
	}
	if(strcmp(command, "LEAVE")==0) {
		return leave(c, tag, clients);
	}
	if(strcmp(command, "TALK")==0) {
		return talk(c, tag, message, clients);
	}
	if(strcmp(command, "NAMES")==0) {
		return names(c, tag, clients);
	}
	if(strcmp(command, "TOPIC")==0) {
		return topic(c, tag, message, clients, curr_topic);
	}
	if(strcmp(command, "PRIVATE")==0) {
		return private(c, tag, message, clients);
	}
	if(strcmp(command, "WHOIS")==0) {
		return whois(c, tag, message, clients);
	}
	client_write(c, tag, strlen(tag));
	client_write(c, " BAD Unkown command.\r\n", 22);
	return 0;

}
int main(int argc, char **argv)
{
  if(argc!=4)
  {
    std::cerr << "usage: " << argv[0] << " <uri> <topic> <message_count>" << std::endl;
    return -1;
  }

  std::string uri(argv[1]);
  std::string topic(argv[2]);
  MESSAGES = stoul(std::string(argv[3]));
  times = new uint64_t[MESSAGES];
  memset(times,0,MESSAGES*sizeof(uint64_t));

  try
  {
    std::stringstream str;
    str<< "q_subscriber-" << getpid() ;
    AMPS::Client client(str.str());
    client.connect(uri);
    client.logon();
    client.setAckBatchSize(80);
    signal(SIGUSR1,&handler);
    signal(SIGUSR2,&usr2Handler);

    client.executeAsync(AMPS::Command("subscribe").setTopic(topic).setOptions("max_backlog=100"),
        AMPS::MessageHandler(messageHandler,NULL));
    int retryCount = 0;
    while(!running)
    {
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    while(receivedCount < MESSAGES)
    {
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    auto end = std::chrono::high_resolution_clock::now();
    client.flushAcks();
    client.disconnect();
    std::chrono::duration<double,std::milli> elapsed = end-s_start;
    std::cout << "Consumed " << MESSAGES << " in " << elapsed.count() << "ms (" << (MESSAGES*1000/elapsed.count()) << "/s)" << std::endl;
    char fname_buf[256];
    sprintf(fname_buf,"consumer-%d.out", getpid());
    FILE* fp = fopen(fname_buf,"w");
    for(int i = 0; i < MESSAGES; ++i)
    {
      fprintf(fp,"%lu\n",times[i]);
    }
    fclose(fp);

  } catch(std::exception &ex)
  {
    std::cerr << "error: " << ex.what() << std::endl;
    return -1;
  }
}
Exemple #18
0
void SopoMygga::on_message(const mosquitto_message *message)
{
    QString topic(message->topic);
    QString data=QString::fromLocal8Bit((char *)message->payload, message->payloadlen);

    emit msg(topic, data);

    if (m_topics.contains(topic))
        emit topicMatch(m_topics.value(topic));
}
Exemple #19
0
dds::topic::Topic<T, dds::topic::detail::Topic>
dds::topic::detail::Topic<T>::wrapper()
{

    typename Topic::ref_type ref =
            OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<Topic<T> >(this->get_strong_ref());
    dds::topic::Topic<T, dds::topic::detail::Topic> topic(ref);

    return topic;
}
void CoreIrcChannel::setEncrypted(bool e) {
  if(!Cipher::neededFeaturesAvailable())
    return;

  if(e) {
    if(topic().isEmpty())
      return;

    QByteArray key = qobject_cast<CoreNetwork *>(network())->cipherKey(name());
    if(key.isEmpty())
      return;

    if(!cipher()->setKey(key))
      return;

    QByteArray decrypted = cipher()->decryptTopic(topic().toAscii());
    setTopic(decodeString(decrypted));
  }
}
Exemple #21
0
WWidget *EventsDemo::wDropEvent()
{
  WContainerWidget *result = new WContainerWidget();

  topic("WDropEvent", result);
  addText(tr("events-WDropEvent"), result);
  new DragExample(result);

  return result;
}
bool
GPUProcessManager::NotifyGpuObservers(const char* aTopic)
{
  if (!EnsureGPUReady()) {
    return false;
  }
  nsCString topic(aTopic);
  mGPUChild->SendNotifyGpuObservers(topic);
  return true;
}
void ctkEAPluginEventAdapter::pluginChanged(const ctkPluginEvent& event)
{
  ctkDictionary properties;
  properties.insert(ctkEventConstants::EVENT, QVariant::fromValue(event));
  properties.insert("plugin.id", QVariant::fromValue<long>(event.getPlugin()->getPluginId()));

  const QString symbolicName = event.getPlugin()->getSymbolicName();

  if (!symbolicName.isEmpty())
  {
    properties.insert(ctkEventConstants::PLUGIN_SYMBOLICNAME,
                      symbolicName);
  }

  properties.insert("plugin", QVariant::fromValue(event.getPlugin()));

  QString topic("org/commontk/PluginEvent/");

  switch (event.getType())
  {
  case ctkPluginEvent::INSTALLED:
    topic.append("INSTALLED");
    break;
  case ctkPluginEvent::STARTED:
    topic.append("STARTED");
    break;
  case ctkPluginEvent::STOPPED:
    topic.append("STOPPED");
    break;
  case ctkPluginEvent::UPDATED:
    topic.append("UPDATED");
    break;
  case ctkPluginEvent::UNINSTALLED:
    topic.append("UNINSTALLED");
    break;
  case ctkPluginEvent::RESOLVED:
    topic.append("RESOLVED");
    break;
  case ctkPluginEvent::UNRESOLVED:
    topic.append("UNRESOLVED");
    break;
  default:
    return; // IGNORE EVENT
  };

  try
  {
    getEventAdmin()->postEvent(ctkEvent(topic, properties));
  }
  catch (const std::logic_error& )
  {
    // This is o.k. - indicates that we are stopped.
  }
}
Exemple #24
0
int
main(int argc, char* argv[]) 
{
    if (argc < 2) {
        std::cout << "USAGE:\n\t qppub <sensor-id>" << std::endl;
        return -1;
    }

    int sid = atoi(argv[1]);
    const int N = 100;

   /*segment1-start*/
   dds::core::QosProvider qp("file://defaults.xml", "DDS DefaultQosProfile");

  // create a Domain Participant, -1 defaults to value defined in configuration file
   dds::domain::DomainParticipant dp(-1);

   dds::topic::qos::TopicQos topicQos = qp.topic_qos();

   dds::topic::Topic<tutorial::TempSensorType> topic(dp, "TempSensor", topicQos);

   dds::pub::qos::PublisherQos pubQos = qp.publisher_qos();
   dds::pub::Publisher pub(dp, pubQos);

   dds::pub::qos::DataWriterQos dwqos = qp.datawriter_qos();
   dds::pub::DataWriter<tutorial::TempSensorType> dw(pub, topic, dwqos);  
   /*segment1-end*/
 
    const float avgT = 25;
    const float avgH = 0.6;
    const float deltaT = 5;
    const float deltaH = 0.15;
    // Initialize random number generation with a seed
    srandom(clock());
    
    // Write some temperature randomly changing around a set point
    float temp = avgT + ((random()*deltaT)/RAND_MAX);
    float hum  = avgH + ((random()*deltaH)/RAND_MAX);

    tutorial::TempSensorType sensor( sid, temp, hum, tutorial::CELSIUS );

    // Write the data
    for (unsigned int i = 0; i < N; ++i) {
        dw.write(sensor);
        std::cout << "DW << " << sensor << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        temp = avgT + ((random()*deltaT)/RAND_MAX);
        sensor.temp(temp); 
        hum = avgH + ((random()*deltaH)/RAND_MAX);
        sensor.hum(hum);
    }
  
   return 0;
}
Exemple #25
0
int main(int argc, char* argv[]) {
  try {
    DomainParticipant dp(0);
    Topic<ShapeType> topic(dp, "Circle");
    Subscriber sub(dp);
    DataReader<ShapeType> dr(sub, topic);

    uint32_t sleepTime = 100000;

    while (true) {
      // If you can use C++11 then the "auto" keywork and "lambda"
      // function can make this code even nicer.

       /*
        * This assignement has move semantics. Also assignements
        * between LoanedSamples have move semantics a la C++11.
        * We should also add a member function to do:
        *
        * LoanedSamples<ShapeType> s1 = ...;
        * LoanedSamples<ShapeType> s2;
        *
        * s2 = move(s1); // LoanedSamples<T> move(LoanedSamples<T>& s)
        *                // This will call the copy ctor under the hood.
        * s2 = s1; // error!
        */
       ShapeType s = {"BLUE", 0, 0, 0};
       dds::core::InstanceHandle handle = dr.lookup_instance(s);

       /*
        * Make available older style API
        * (essentially make public as opposed to private)
        */
      LoanedSamples<ShapeType> samples =
            dr.selector()
               .instance(handle)
               .filter_state(DataState::any_data())
            .read();

      /* Ex1:
       *
       * SharedSample<ShapeType> ss = samples.share();
       * auto ss2 = ss; // This create "ref-counted alias" and does
       * not use the move semantics.
       */
      std::cout << "--------------------------------------------" << std::endl;
      std::for_each(samples.data().begin(), samples.data().end(), demo::ishapes::printShape);
      usleep(sleepTime);
    }
  } catch (const dds::core::Exception& e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}
int main(int argc, char **argv) {

	ros::init(argc, argv, "setVehiclePose");
	ros::NodeHandle nh;

	if (argc!=8) {
		std::cerr << "USAGE: " << argv[0] << " <topic> <x> <y> <z> <roll> <pitch> <yaw>" << std::endl;
		std::cerr << "units are in meters and radians." << std::endl;
		return 0;
	}	

	std::string topic(argv[1]);
	double x=atof(argv[2]);
	double y=atof(argv[3]);
	double z=atof(argv[4]);
	double roll=atof(argv[5]);
	double pitch=atof(argv[6]);
	double yaw=atof(argv[7]);

	ros::Publisher position_pub;
	position_pub=nh.advertise<geometry_msgs::Pose>(topic,1);


	osg::Matrixd T, Rx, Ry, Rz, transform;
	T.makeTranslate(x,y,z);
	Rx.makeRotate(roll,1,0,0);
	Ry.makeRotate(pitch,0,1,0);
	Rz.makeRotate(yaw,0,0,1);
	transform=Rz*Ry*Rx*T;
	osg::Vec3d trans=transform.getTrans();
	osg::Quat rot=transform.getRotate();


	ros::Rate r(25);
	while (ros::ok()) {
		geometry_msgs::Pose pose;

		pose.position.x=trans.x();
		pose.position.y=trans.y();
		pose.position.z=trans.z();
		pose.orientation.x=rot.x();
		pose.orientation.y=rot.y();
		pose.orientation.z=rot.z();
		pose.orientation.w=rot.w();
		
		position_pub.publish(pose);

		ros::spinOnce();
		r.sleep();
	}

	return 0;
}
Exemple #27
0
void Window::tabSelected()
{
    QList<QTreeWidgetItem*> selectedItems = tabTree->selectedItems();

    if (selectedItems.size() != 1) {
        return;
    }

    if (!selectedItems.at(0)->parent()) {
        /*server tab*/
        userDock->hide();
        topicDock->hide();
        pages->setCurrentIndex(0);
        serverPage->clearTabIndication();
        inputLine->setFocus();
        return;
    }

    QString tabName = getSelectedTabName();
    if (channelPages.contains(tabName)) {
        /*channel tab*/
        showNicksFor(tabName);
        ChannelPage* channelPage = channelPages[tabName];
        if (channelPage->isDisabled()) {
            topicLine->setText(QString());
        } else {
            QString topic(ircClient->getChannel(tabName).getTopicText());
            BasicPage::eraseControlCharacters(topic);
            topicLine->setText(topic);
        }
        userDock->show();
        topicDock->show();
        channelPages[tabName]->clearTabIndication();
    } else if (privatePages.contains(tabName)){
        /*user tab*/
        userDock->hide();
        topicDock->hide();
        privatePages[tabName]->clearTabIndication();
    }

    for (int i = 1; i < pages->count(); i ++) {
        const BasicPage* page = static_cast<BasicPage*>(pages->widget(i));
        if (!tabName.compare(page->getName())) {
            pages->setCurrentIndex(i);
            break;
        }
    }
    inputLine->setFocus();
}
  bool OnInit()
  {
    std::cout << "Init" << std::endl;
    if (this->argc != 3) { std::cout << " please provide path to bag file and a topic name!" << std::endl; exit(0); }
    std::string bag_file(wxString(this->argv[1]).mb_str());
    std::string topic(wxString(this->argv[2]).mb_str());

    char* av = "bag_gui";
    ros::init(argc, &av, "bag_gui");
    nh = new ros::NodeHandle();
    one_.setOutputLabels(labels_);
    one_.setPixelSearchRadius(8,2,2);
    one_.setSkipDistantPointThreshold(8);

    seg_.setNormalCloudIn(normals_);
    seg_.setLabelCloudInOut(labels_);
    seg_.setClusterGraphOut(graph_);


    p_bag = new rosbag::Bag();
    p_view = new rosbag::View();
    try { p_bag->open(bag_file, rosbag::bagmode::Read); }
    catch (rosbag::BagException) { std::cerr << "Error opening file " << bag_file << std::endl; return false; }
    p_view->addQuery(*p_bag, rosbag::TopicQuery(topic));

    rosbag::View::iterator vit = p_view->begin();
    while(vit!=p_view->end()) { timeline.push_back(vit); ++vit; }
    tl_it = timeline.begin();

    sensor_msgs::PointCloud2::ConstPtr last_msg = (*tl_it)->instantiate<sensor_msgs::PointCloud2>();
    pcl::fromROSMsg<PT>(*last_msg, *pc_);
    compute();

    r_rgb_ = Gui::Core::rMan()->create<PC>("r_rgb", pc_);
    r_seg_ = Gui::Core::rMan()->create<PC>("r_seg", segmented_);
    v_rgb_ = r_rgb_->createView<Col>("v_rgb");
    v_seg_ = r_seg_->createView<Col>("v_seg");

    boost::function<void (wxMouseEvent&, Gui::Resource<PC>*)> f = boost::bind(&MainApp::mouseShowNext, this, _1, _2);
    v_seg_ ->registerMouseCallback(f);
    boost::function<void (wxKeyEvent&, Gui::Resource<PC>*)> k = boost::bind(&MainApp::keyShowNext, this, _1, _2);
    v_seg_ ->registerKeyCallback(k);

    v_seg_->show();
    v_rgb_->show();

    std::cout<<"Done Init"<<std::endl;
    return true;
  }
Exemple #29
0
void cServerDC::AfterUserLogin(cConnDC *conn)
{
	ostringstream os;
	if(conn->Log(3))
		conn->LogStream() << "Entered the hub." << endl;
	mCo->mTriggers->TriggerAll(eTF_MOTD, conn);

	// The user has to change password
	if(conn->mRegInfo && conn->mRegInfo->mPwdChange) {

		os << _("You must set your password now using +passwd command.");
		DCPrivateHS(os.str(), conn);
		DCPublicHS(os.str(), conn);
		conn->SetTimeOut(eTO_SETPASS, mC.timeout_length[eTO_SETPASS], this->mTime);
		os.str("");
	}

	// send the hub topic
	if (!mC.hub_topic.empty()) {
		string topic("$HubTopic ");
		topic += mC.hub_topic + "|";
		conn->Send(topic, false);
	}

	if (mC.send_user_info) {
		os << _("Your information") << ":\r\n";
		conn->mpUser->DisplayInfo(os, eUC_OPERATOR);
		DCPublicHS(os.str(), conn);
	}

	if(mUserList.Size() > mUsersPeak)
		mUsersPeak = mUserList.Size();
	#ifndef WITHOUT_PLUGINS
	if (!mCallBacks.mOnUserLogin.CallAll(conn->mpUser)) {
		conn->CloseNow();
		return;
	}
	#endif

	if ((conn->mpUser->mClass >= eUC_NORMUSER) && (conn->mpUser->mClass <= eUC_MASTER)) {
		if (mC.msg_welcome[conn->mpUser->mClass].size()) {
			string ToSend;
			ReplaceVarInString(mC.msg_welcome[conn->mpUser->mClass], "nick", ToSend, conn->mpUser->mNick);
			ReplaceVarInString(ToSend, "CC", ToSend, conn->mCC);
			DCPublicHSToAll(ToSend);
		}
	}
}
int
main(int argc, char* argv[]) {
  const int duration = 60; // sec
  dds::domain::DomainParticipant dp(0);
  dds::topic::Topic<tutorial::TempSensorType> topic(dp, "TTempSensor");
  dds::sub::Subscriber sub(dp);
  
  dds::sub::DataReader<tutorial::TempSensorType> dr(sub, topic); 

  TempSensorListener listener;
  dr.listener(&listener, dds::core::status::StatusMask::data_available());
  std::this_thread::sleep_for(std::chrono::seconds(duration));
  dr.listener(nullptr, dds::core::status::StatusMask::none());

  return 0;
}