Example #1
0
int
main( int argc, char** argv)
{
  OpenDDS::DCPS::set_DCPS_debug_level( 0);
  int status = 0;
  try {
    Subscriber subscriber( argc, argv, 0);
    subscriber.run();

  } catch (const CORBA::Exception& ex) {
    ex._tao_print_exception ("%T (%P|%t) FATAL: Subscriber - CORBA problem detected.\n");
    status = -1;

  } catch (const std::exception& ex) {
    ACE_ERROR ((LM_ERROR,
      ACE_TEXT("%T (%P|%t) FATAL: Subscriber - ")
      ACE_TEXT("%s exception caught in main().\n"),
      ex.what()
    ));
    status = -2;

  } catch(...) {
    ACE_ERROR ((LM_ERROR,
      ACE_TEXT("%T (%P|%t) FATAL: Subscriber - ")
      ACE_TEXT("Unspecified exception caught in main() - panic.\n")
    ));
    status = -3;

  }

  return status;
}
int main(int argc, char* argv[])
{
	Config* config = Config::getConfig();
	ArgumentParser argParser;
	if(!argParser.parseArgs(argc, argv))
	{
		argParser.printUsage();
		return 1;
	}
	if(config->rtPrio)
	{
		PrioritySwitcher prioSwitcher(config->fifoScheduling);
		if(prioSwitcher.switchToRealtimePriority() != 0)
		{
			Logger::ERROR("Switching to realtime priority failed, maybe not running as root?");
			return 1;
		}
	}
	ros::init(argc, argv, "communication_tests_subscriber");
	config->nodeHandle = new ros::NodeHandle();
	Subscriber subscriber("communication_tests");
	subscriber.startMeasurement();
	subscriber.printMeasurementResults();
	subscriber.saveGnuplotData();
	return 0;
}
Example #3
0
int main(int argc, char* argv[]) {

  zmq::context_t context(1);

  zmq::socket_t subscriber(context, ZMQ_SUB);
  subscriber.connect("tcp://localhost:5561");
  subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);

  zmq::socket_t syncclient(context, ZMQ_REQ);
  syncclient.connect("tcp://localhost:5562");

  s_send(syncclient, "");

  s_recv(syncclient);
  std::cout << "Connected to subscriber" << std::endl;
  
  int update_nbr = 0;
  while(1) {
    if (s_recv(subscriber).compare("END") == 0) {
      std::cout << "FINE" << std::endl;
      break;
    }

    update_nbr++;
  }

  std::cout << "Received " << update_nbr << "updates" << std::endl;

  return 0;
}
int main(int argc, char * argv[])
{
  Miro::Log::init(argc, argv);
  kn::DdsSupport::init(argc, argv);

  kn::DdsEntitiesFactorySvc ddsEntities;
  ddsEntities.init(argc, argv);

  Miro::ShutdownHandler shutdownHander;
  {
    kn::DdsTypedSupplier<HelloWorld> publisher("Example HelloWorld");
    HelloWorldPrinter printer;
    kn::DdsTypedConnector<HelloWorld, HelloWorldPrinter>
      subscriber(&printer, "Example HelloWorld");
    
    for (unsigned int i = 0; i < 10000; ++i) {
      /* Modify the data to be sent here */
      sprintf(publisher.event().msg, "Hello World! (%d)", i);
      publisher.sendEvent();
      kn::this_thread::sleep_for(kn::microseconds(10000));
      if (shutdownHander.isShutdown()) {
	break;
      }
    }
  }

  ddsEntities.fini();
  return 0;
}
Example #5
0
    void run()
    {
        zeroeq::Subscriber subscriber(test::buildURI("127.0.0.1", *_publisher));

        BOOST_CHECK(subscriber.subscribe(
            test::Echo::IDENTIFIER(),
            zeroeq::EventPayloadFunc([&](const void* data, const size_t size) {
                test::onEchoEvent(data, size);
                received = true;
            })));

        // Using the connection broker in place of zeroconf
        BrokerPtr broker = createBroker(subscriber);
        BOOST_REQUIRE(broker.get());
        if (!broker)
            return;

        _broker = broker->getAddress();
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _state = STATE_STARTED;
            _condition.notify_all();
        }

        // test receive of data for echo event
        for (size_t i = 0; i < 10; ++i)
        {
            subscriber.receive(100);
            if (received)
                return;
        }
        BOOST_CHECK(!"reachable");
    }
// -----------------------------------------------------------------------------
// CUpnpEventQueueManagerBase::PrepareTransactionAndStartSendingL
// -----------------------------------------------------------------------------
// 
void CUpnpEventQueueManagerBase::PrepareTransactionAndStartSendingL( TInt aSubscriberNo )
    {
    if (  aSubscriberNo >= iSubscriberLibrary->SubscriberLibrary().Count()
       || aSubscriberNo < 0 )
        {
        User::Leave( KErrNotFound );
        }
        
    CUpnpSubscriberLibraryElement* subscriber( NULL );
    subscriber = iSubscriberLibrary->SubscriberLibrary()[aSubscriberNo];
    
    CUpnpHttpMessage* message = reinterpret_cast<CUpnpHttpMessage*>(
                        RUpnpGenaMessageFactory::EventingLC(
                          subscriber->CallbackPath(), 
                          subscriber->CallbackAddress(), 
                          subscriber->Sid(), 
                          subscriber->Seq() ) );

    message->SetTcpTimeout( KMessageTimeout );
    message->SetBodyL( *iBody );        

    CleanupStack::Pop( message ); //ownership passed to "transcation"
    CUpnpHttpTransaction* transaction = CreateTransactionL( message );
    
    iEventController.SendTransactionL( transaction );
       
    subscriber->IncreaseSeq();  
    }
void FramerateEqualizer::_init()
{
    const Compound* compound = getCompound();

    if( _nSamples > 0 || !compound )
        return;

    _nSamples = 1;

    // Subscribe to child channel load events
    const Compounds& children = compound->getChildren();
    
    EQASSERT( _loadListeners.empty( ));
    _loadListeners.resize( children.size( ));
    
    for( size_t i = 0; i < children.size(); ++i )
    {
        Compound*      child        = children[i];
        const uint32_t period       = child->getInheritPeriod();
        LoadListener&  loadListener = _loadListeners[i];
        
        loadListener.parent = this;
        loadListener.period = period;
        
        LoadSubscriber subscriber( &loadListener );
        child->accept( subscriber );
        
        _nSamples = EQ_MAX( _nSamples, period );
    }

    _nSamples = EQ_MIN( _nSamples, 100 );
}
Example #8
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv);

      if (parse_args (argc, argv) != 0)
        return 1;

      CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA");

      if (CORBA::is_nil (poa_object.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           " (%P|%t) Unable to initialize the POA.\n"),
                          1);

      PortableServer::POA_var root_poa = PortableServer::POA::_narrow (
      poa_object.in ());
      PortableServer::POAManager_var poa_manager =
      root_poa->the_POAManager();

      Subscriber_impl subscriber(orb.in ());
      PortableServer::ObjectId_var id =
      root_poa->activate_object (&subscriber);

      CORBA::Object_var object = root_poa->id_to_reference (id.in ());

      Subscriber_var subscriber_var = Subscriber::_narrow (object.in ());

      object = orb->string_to_object(ior);
      Publisher_var publisher = Publisher::_narrow(object.in());

      publisher->subscribe(subscriber_var.in());

      poa_manager->activate();

      ThreadPool pool (orb.in ());
      if (pool.activate(THR_NEW_LWP | THR_JOINABLE, 5) != 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot activate client threads\n"),
                          1);

      pool.thr_mgr ()->wait ();

      ACE_DEBUG ((LM_DEBUG, "event loop finished\n"));
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught:");
      return 1;
    }

    return 0;
}
void
Transceiver::set_qos()
{
  // set writer Qos

  ReturnCode_t retcode = publisher()->get_default_datawriter_qos(m_writer_qos);
  publisher().check(retcode,
		    "Publisher::get_default_datawriter_qos");

  TopicQos topic_qos;
  retcode = m_topic->get_qos(topic_qos);
  m_topic.check(retcode,
		"Topic::get_qos");

  retcode = publisher()->copy_from_topic_qos(m_writer_qos,
					     topic_qos);
  publisher().check(retcode,
		    "Publisher::copy_from_topic_qos");

  m_writer_qos.latency_budget.duration.sec = m_qos.writer_qos.latency_budget.duration.sec;
  m_writer_qos.latency_budget.duration.nanosec = m_qos.writer_qos.latency_budget.duration.nanosec;
  m_writer_qos.transport_priority.value = m_qos.writer_qos.transport_priority.value;

  // set reader Qos
  
  retcode = subscriber()->get_default_datareader_qos(m_reader_qos);
  subscriber().check(retcode,
		     "Subscriber::get_default_datareader_qos");

  retcode = m_echo_topic->get_qos(topic_qos);
  m_echo_topic.check(retcode,
		     "Topic::get_qos");

  retcode = subscriber()->copy_from_topic_qos(m_reader_qos,
					      topic_qos);
  subscriber().check(retcode,
		     "Subscriber::copy_from_topic_qos");

  m_reader_qos.history.depth = m_qos.reader_qos.history.depth;
  m_reader_qos.latency_budget.duration.sec = m_qos.reader_qos.latency_budget.duration.sec;
  m_reader_qos.latency_budget.duration.nanosec = m_qos.reader_qos.latency_budget.duration.nanosec;
}
Example #10
0
HttpData & NodeToVnfmEvent::
Receive(NodeData & a_rNodeData, DashBoard & a_board)
{
    gLog->DEBUG("%-24s| Receive",
        "NodeToVnfmEvent");

    if(a_rNodeData.IsError())
    {
        gLog->DEBUG("%-24s| Received Msg is Error, message is going to discard",
            "NodeToVnfmEvent");
        m_sHttpData.Clear();
    }

    // PRA -> VNF 는 모두 Response  입니다.
    switch(a_rNodeData.GetCommand())
    {
    case CMD_VNF_PRA_READY:
        ready(a_rNodeData,      a_board);
        break;
    case CMD_VNF_PRA_START:
        started(a_rNodeData,    a_board);
        break;
    case CMD_VNF_PRA_STOP:
        stopped(a_rNodeData,    a_board);
        break;
    case CMD_VNF_SUBSCRIBER:
        subscriber(a_rNodeData, a_board);
        break;
    case CMD_VNF_EVENT:
        event(a_rNodeData,      a_board);
        break;
    case CMD_RSA_PERF_REPORT:
        perf(a_rNodeData,       a_board);
        break;
    // From EventAPI - SendTps()
    case CMD_VNF_PERF_TPS:
        perfTps(a_rNodeData,    a_board);
        break;
    case CMD_REGISTER_PROVIDER:
        m_pResourceAndTpsProvider->Register(a_rNodeData.GetBody());
        break;
    case CMD_VNF_PRA_INSTALL:
        break;
    default:
        unknown(a_rNodeData,    a_board);
        break;
    }

    return m_sHttpData;
}
int main(int argc, char **argv)
{
    rclcpp::init(argc,argv);
    node = std::make_shared<rclcpp::Node>("simpleLoggerEcho");

    INIT_LOGGER(node);
    simpleLoggerSubscriber subscriber(node);
    rclcpp::WallRate loop_rate(20);
    while(rclcpp::ok())
    {
        rclcpp::spin_some(node);
        loop_rate.sleep();
    }

}
Example #12
0
  /**
   * @brief A subscriber operation
   * This operation can be bound to a subscriber
   * Bind this operation to a subscriber in the JSON configuration
   */     
  void Component_1::subscriber_function() {
    boost::random::mt19937 rng;
    boost::random::uniform_int_distribution<> loop_iteration_random(700000 * 0.6, 700000);
    int loop_max = loop_iteration_random(rng);  
  
    // Business Logic for Name_Subscriber_operation
    for(int i=0; i < loop_max; i++) {
      double result = 0.0;
      double x = 41865185131.214415;
      double y = 562056205.1515;
      result = x*y;
    }
    std::string received_message = subscriber("Name_Subscriber")->message();
    std::cout << "Component 1 : Subscriber : Received message: " 
	      << received_message << std::endl;
  }    
Example #13
0
 void _setupSubscribers()
 {
     SubscriberPtr subscriber(
                 new ::zeq::Subscriber( servus::URI( "hbp://" )));
     subscribers.push_back( subscriber );
     if( _config.getApplicationParameters().syncCamera )
     {
         subscriber->registerHandler( ::zeq::hbp::EVENT_CAMERA,
                                      std::bind( &Impl::onHBPCamera,
                                              this, std::placeholders::_1 ));
     }
     subscriber->registerHandler( ::zeq::hbp::EVENT_LOOKUPTABLE1D,
                                  std::bind( &Impl::onLookupTable1D,
                                             this, std::placeholders::_1 ));
     subscriber->registerHandler( ::zeq::hbp::EVENT_FRAME,
                                  std::bind( &Impl::onFrame,
                                              this, std::placeholders::_1 ));
 }
Example #14
0
int main () {
    //  Prepare our context and subscriber
    zmq::context_t context(1);
    zmq::socket_t subscriber (context, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5563");
    subscriber.setsockopt( ZMQ_SUBSCRIBE, "B", 1);

    while (1) {
 
		//  Read envelope with address
		std::string address = s_recv (subscriber);
		//  Read message contents
		std::string contents = s_recv (subscriber);
		
        std::cout << "[" << address << "] " << contents << std::endl;
    }
    return 0;
}
Example #15
0
void Servo::Client()
{
	std::string host = "tcp://";
	while (!lservAddr.try_lock())
		std::this_thread::sleep_for(std::chrono::milliseconds(50));
	if (!servAddr.empty())
		host.append(servAddr);
	else
		host.append("localhost");
	lservAddr.unlock();
	host.append(":56556");
	zmq::socket_t subscriber(zContext, ZMQ_SUB);
	subscriber.connect(host.c_str());
	subscriber.setsockopt(ZMQ_SUBSCRIBE, me.c_str(), me.size());
	subscriber.setsockopt(ZMQ_SUBSCRIBE, "::", 2);
	connected = true;
	
	while (connected)
	{
		zmq::message_t update;

		while (subscriber.recv(&update, ZMQ_DONTWAIT) == false)
		{
			if (connected)
				std::this_thread::sleep_for(std::chrono::milliseconds(20));
			else
				break;
		}
		
		std::string s(static_cast<char*>(update.data()));
		if (!s.empty())
		{
			while (!lock.try_lock())
				std::this_thread::sleep_for(std::chrono::milliseconds(50));
			buffer.push_back(s);
			lock.unlock();
		}
			
		std::this_thread::sleep_for(std::chrono::milliseconds(20));
	}
	subscriber.close();
}
Example #16
0
void
worker::run () {
    try {
        assert(_context != NULL);
        assert(_connectAddr.c_str() != NULL);
        fprintf(stdout, "worker: connect address: %s\n",  _connectAddr.c_str());
        fprintf(stdout, "worker: stop requested: %d\n", _stopRequested);
        zmq::socket_t subscriber(*_context, ZMQ_SUB);
        subscriber.connect(_connectAddr.c_str());
        const char* filter = "";
        subscriber.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
        //capkproto::instrument_bbo bbo;
        
        _inproc = new zmq::socket_t(*_context, ZMQ_PUB);
        assert(_inproc);
        _inproc->connect(_inprocAddr.c_str());
        
        zmq::message_t msg;
        while (1 && _stopRequested == false) {
            subscriber.recv(&msg);
#ifdef DEBUG
            boost::posix_time::ptime time_start(boost::posix_time::microsec_clock::local_time());
#endif

			int64_t more;
			size_t more_size;
			more_size = sizeof(more);
			subscriber.getsockopt(ZMQ_RCVMORE, &more, &more_size);
            // send to orderbook on inproc socket - no locks needed according to zmq
            _inproc->send(msg, more ? ZMQ_SNDMORE : 0);

#ifdef DEBUG
            boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());
            boost::posix_time::time_duration duration(time_end - time_start);
            fprintf(stderr, "Inbound from md interface time to receive and parse: %s\n", to_simple_string(duration).c_str()); 
#endif
        }
    } 
    catch (std::exception& e) {
        std::cerr << "EXCEPTION: " << __FILE__ << __LINE__ << e.what();
    }
}
Example #17
0
File: achtest.c Project: golems/ach
int test_multi() {

    ach_status_t r = ach_unlink(opt_channel_name);
    if( ! ach_status_match(r, ACH_MASK_OK | ACH_MASK_ENOENT) ) {
        fprintf(stderr, "ach_unlink failed\n: %s",
                ach_result_to_string(r));
        return -1;
    }

    r = ach_create(opt_channel_name, 32ul, 64ul, NULL );


    /* pid_t sub_pid[opt_n_sub]; */
    /* pid_t pub_pid[opt_n_pub]; */
    int i;

    /* create subscribers */
    for( i = 0; i < opt_n_sub; i++ ) {
        pid_t p = fork();
        if( p < 0 ) exit(-1);
        else if( 0 == p ) return subscriber(i);
        /* else sub_pid[i] = p; */
    }

    /* create publishers */
    for( i = 0; i < opt_n_pub; i++ ) {
        pid_t p = fork();
        if( p < 0 ) exit(-1);
        else if( 0 == p ) return publisher(i);
        /* else pub_pid[i] = p; */
    }

    /* wait */
    for( i = 0; i < opt_n_sub+opt_n_pub; i++ ) {
        int s;
        pid_t pid = wait(&s);
        (void)pid;
        if( 0 != s ) return -1;
    }
    return 0;
}
Example #18
0
void Listbox::OnMousePress(vec2 mousePos, int button, bool down) {
	if (down)
		lastScrollUpdate = OS::Now();
	else {
		lastScrollUpdate = 0;
		lastScrollPos = vec2(-1,-1);
		//Mouse up, check if they selected something
		//Use the hovering over calculation stolen from the draw phase
		int hoveringOver = (int)((lastMousePos.y-scrollPosition-3)/entryHeight);

		//Check that the cursor is not in the scroll bar
		bool scrollBarNeeded = (entryHeight*entries.size() > position.Height-6);
		if (scrollBarNeeded) {
			if (lastMousePos.x >= calculatedPosition.Width-3-scrollButtonWidth)
				hoveringOver = -1;
		}

		if ((hoveringOver < 0) || (hoveringOver >= (int)entries.size()))
			return;
		else {
			if (selected == hoveringOver) {
				if ((OS::Now() - selectedAt) < .35) {
					//Double clicked list item
					EventSelectionDoubleClicked.Fire([this](function<void(Listbox*,int)> subscriber) {
						subscriber(this,this->selected);
					});
				}
				selectedAt = OS::Now();
			}
			else {
				selectedAt = OS::Now();
				selected = hoveringOver;
				OnListSelected();
			}

		}
			
	}
		
}
Example #19
0
void
ConfigFile::process(bool isDryRun, const std::string& filename) const
{
  BOOST_ASSERT(!filename.empty());

  if (m_global.begin() == m_global.end()) {
    std::string msg = "Error processing configuration file: ";
    msg += filename;
    msg += " no data";
    BOOST_THROW_EXCEPTION(Error(msg));
  }

  for (const auto& i : m_global) {
    try {
      const ConfigSectionHandler& subscriber = m_subscriptions.at(i.first);
      subscriber(i.second, isDryRun, filename);
    }
    catch (const std::out_of_range&) {
      m_unknownSectionCallback(filename, i.first, i.second, isDryRun);
    }
  }
}
Example #20
0
int main(int, char **)
{
    boost::asio::ip::address address = boost::asio::ip::address::from_string("127.0.0.1");
    const unsigned short port = 6379;

    boost::asio::io_service ioService;
    RedisAsyncClient publisher(ioService);
    RedisAsyncClient subscriber(ioService);


    publisher.asyncConnect(address, port, [&](bool status, const std::string &err)
    {
        if( !status )
        {
            std::cerr << "Can't connect to to redis" << err << std::endl;
        }
        else
        {
            subscriber.asyncConnect(address, port, [&](bool status, const std::string &err)
            {
                if( !status )
                {
                    std::cerr << "Can't connect to to redis" << err << std::endl;
                }
                else
                {
                    subscriber.subscribe(channelName,
                            boost::bind(&subscribeHandler, boost::ref(ioService), _1),
                            boost::bind(&publishHandler, boost::ref(publisher), _1));
                }
            });
        }
    });

    ioService.run();

    return 0;
}
Transceiver::Transceiver(Partition& partition)
  : m_partition(partition),
    m_qos_query(qos_reader()),
    m_dispatcher(*this),
    m_topic(participant()),
    m_writer(publisher(),
	     m_topic),
    m_echo_topic(participant()),
    m_reader(subscriber(),
	     m_echo_topic),
    m_reader_condition(m_reader),
    m_reader_attachment(m_dispatcher,
			m_reader_condition),
    m_writer_thread(*this),
    m_reader_thread(*this),
    m_report_thread(*this),
    m_writer_active(false),
    m_reader_active(false),
    m_report_active(false),
    m_config_number(0)
{
  // cout << "Transceiver::Transceiver(" << partition_id() << ")" << endl;
}
Example #22
0
   void ThreadNotificationListener(boost::shared_ptr<notification::CNotificationCenter> center, int* notifReceivedCount)
   {
      try
      {
         auto waitActionCustomNotif(boost::make_shared<notification::action::CWaitAction<CCustomNotif> >());

         //create the acquisition observer
         auto observer(boost::make_shared<notification::basic::CObserver<CCustomNotif> >(waitActionCustomNotif));

         //regsiter the observer
         notification::CHelpers::CCustomSubscriber subscriber(observer, center);


         auto waitActionInt(boost::make_shared<notification::action::CWaitAction<CIntNotif> >());

         //create the acquisition observer
         auto observerInt(boost::make_shared<notification::basic::CObserver<CIntNotif> >(waitActionInt));

         //regsiter the observer
         notification::CHelpers::CCustomSubscriber subscriberInt(observerInt, center);

         boost::shared_ptr<CCustomNotif> notifCustom = waitActionCustomNotif->wait(boost::posix_time::seconds(5000));
         if (notifCustom && notifCustom->m_integer == 42 && boost::iequals(notifCustom->m_string, "a custom notif"))
         {
            (*notifReceivedCount)++;
         }

         boost::shared_ptr<CIntNotif> notifInt = waitActionInt->wait(boost::posix_time::seconds(5000));
         if (notifInt && notifInt->m_integer == 666)
         {
            (*notifReceivedCount)++;
         }
      }
      catch (...)
      {
      }
   }
Example #23
0
int main (int argc, char *argv[])
{
   zmq::context_t context(1);

    //  First, connect our subscriber socket
    zmq::socket_t subscriber (context, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5561");
    subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);

    //  Second, synchronize with publisher
    zmq::socket_t syncclient (context, ZMQ_REQ);
    syncclient.connect("tcp://localhost:5562");

    //  - send a synchronization request
    s_send (syncclient, "");

    //  - wait for synchronization reply
    std::string *string = s_recv (syncclient);
    delete (string);

    //  Third, get our updates and report how many we got
    int update_nbr = 0;
    while (1) {
    	
        std::string *string = s_recv (subscriber);
        if (string->compare("END") == 0) {
            delete (string);
            break;
        }
        delete (string);

        update_nbr++;
    }
    std::cout << "Received " << update_nbr << " updates" << std::endl;

    return 0;
}
Example #24
0
int main (int argc, char *argv[])
{

    int major, minor, patch;
    zmq_version (&major, &minor, &patch);
    std::cout << "当前ZMQ版本号为" << major << "." << minor << "." << patch << std::endl;

    zmq::context_t context (1);

    //  Socket to talk to server
    std::cout << "Collecting updates from weather server...\n" << std::endl;
    zmq::socket_t subscriber (context, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5556");

    //  Subscribe to zipcode, default is NYC, 10001
	const char *filter = (argc > 1)? argv [1]: "10001";
    subscriber.setsockopt(ZMQ_SUBSCRIBE, filter, strlen (filter));


    //  Process 100 updates
    while(true) {

        int zipcode = 0; 
        int temperature = 0;

        zmq::message_t update;
        subscriber.recv(&update);

        std::istringstream iss(static_cast<char*>(update.data()));
		iss >> zipcode >> temperature;

        std::cout   << "Temperature for zipcode '"<< filter
                    <<"' was "<<(int) (temperature) <<"F"
                    << std::endl;
    }
    return 0;
}
Example #25
0
int main(int argc, char **argv){
    init_options();
    parse_options(argc, argv);

    if (GlobalArgs.helpflag || !GlobalArgs.index_name || !GlobalArgs.server_address){
	tableserver_usage();
	return 0;
    }

    /* init daemon */ 
    init_process();
 
    if (init_index() < 0){
	syslog(LOG_CRIT,"MAIN ERR: unable to init index");
	exit(1);
    }
    
    void *ctx = zmq_init(1);
    if (!ctx){
	syslog(LOG_CRIT,"MAIN ERR: unable to init zmq ctx");
	exit(1);
    }

    /* save to global variable to be used in signal handler */
    main_ctx = ctx;

    if (init_server(ctx) < 0){
	syslog(LOG_CRIT,"MAIN ERR: unable to init server");
	exit(1);
    }

    subscriber(ctx);
    
    zmq_term(ctx);
    return 0;
}
int 
main(int argc, char** argv)
{

    zmq::context_t context(1);
    int rc;
    std::cout << "Connecting to server...\n";
    zmq::socket_t subscriber(context, ZMQ_SUB);
    subscriber.connect("tcp://127.0.0.1:9000");
    //subscriber.connect("tcp://127.0.0.1:5271");
    //subscriber.connect("tcp://127.0.0.1:5272");
    //subscriber.connect("tcp://127.0.0.1:5273");
    //const char filter[]  = {10};
    const char* filter = "";
    subscriber.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    capkproto::instrument_bbo bbo;

    while (1) {
        zmq::message_t msg;
        rc = subscriber.recv(&msg);
        assert(rc);
        bbo.ParseFromArray(msg.data(), msg.size());
    //    std::cout << bbo.DebugString() << "\n";
        std::cout << "Symbol   : " << bbo.symbol() << "\n";
        std::cout << "BB MIC   : " << bbo.bb_mic() << "\n";
        std::cout << "BB Price : " << (double)bbo.bb_price() << "\n";
        std::cout << "BB Size  : " << (double)bbo.bb_size() << "\n";

        std::cout << "BA MIC   : " << bbo.ba_mic() << "\n";
        std::cout << "BA Price : " << (double)bbo.ba_price() << "\n";
        std::cout << "BA Size  : " << (double)bbo.ba_size() << "\n";
    }
    google::protobuf::ShutdownProtobufLibrary();

}
Example #27
0
int main(int argc, char **argv) {
    asio::io_service ios;

    // Register signal handler to stop the io_service
    asio::signal_set signals(ios, SIGINT, SIGTERM);
    signals.async_wait([&](const boost::system::error_code &, int) { ios.stop(); });

    // Connect to task ventilator
    aziomq::socket receiver(ios, ZMQ_PULL);
    receiver.connect("tcp://localhost:5556");

    // schedule receiver socket
    std::array<char, 4096> task;
    receiver.async_receive(asio::buffer(task), [&](const boost::system::error_code & ec,
                                                   size_t bytes_transferred) {
            if (!ec) {
                // process task
            }
    });

    // Connect to weather server
    aziomq::socket subscriber(ios, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5556");
    subscriber.set_option(aziomq::socket::subscribe("10001 "));

    // schedule weather updates
    std::array<char, 4096> update;
    subscriber.async_receive(asio::buffer(task), [&](const boost::system::error_code & ec,
                                                     size_t bytes_transferred) {
            if (!ec) {
                // process weather update
            }
    });
    ios.run();
    return 0;
}
Example #28
0
void ViewEqualizer::Listener::update(Compound* compound)
{
    LBASSERT(_taskIDs.empty());
    LoadSubscriber subscriber(this, _taskIDs);
    compound->accept(subscriber);
}
Example #29
0
void Listbox::OnListSelected() {
	EventSelectionChanged.Fire([this](function<void(Listbox*,int)> subscriber) {
		subscriber(this,this->selected);
	});
}
Example #30
0
//Update the position based off the most recent movement and direction vectors
bool ActorPlayer::Update()
{
	// If the weapon is null, don't do shit
	if(currentWeapon == NULL)
		return PhysicsActor::Update();

	// Get the movement vector from the first person controller
	vec2 moveVector = Game()->FirstPerson->GetMoveVector();

	// Calculate the direction we are facing
	facingDirection = atan2(moveVector.y, moveVector.x);

	// Calculate the magnitude of the movement vector (are we sprinting)
	float magnitude = glm::length(moveVector);

	// Check if we should switch weapons
	if(Game()->FirstPerson->GetSwitchWeaponRequested()) {
		//switch weapons to the next weapon which has been purchased
		for (int i = (currentWeaponId+1) % weapons.size(); i != currentWeaponId; i = (i+1) % weapons.size()) {
			//A damage factor of <= 0 indicates the weapon is currently locked
			if (weapons[i]->Modifiers.DamageFactor > 0) {
				setWeapon(i);
				break;
			}
		}

	}


	// Update the weapon
	currentWeapon->Update(Game()->FirstPerson->GetLookVector(), weaponPos);

	// Forward whether or not we want to shoot to the player's weapon animation controller
	bool r = currentWeapon->HoldingTrigger(Game()->FirstPerson->GetTriggerPulled());
	model->Controller()->SetBoolean("firing", r);


	// if we fired the weapon, update the state machine
	//but only if its not the pulseLaser, no idea why
	if(r && (currentWeaponId == 0))
		model->Update(SIMULATION_DELTA, Game()->Now());

	// Forward the weapon mode to the controller
	model->Controller()->SetBoolean("mode", (currentWeaponId == 0) ? true : false);

	// Forward the movement speed to the player's weapon animation controller
	model->Controller()->SetFloat("speed", OnGround() ? magnitude : 0.0f);

	// Use the movement vector to set the velocity of the player's physics object
	Velocity.x = moveVector.x * movementSpeed;
	Velocity.y = moveVector.y * movementSpeed;

	// Have we walked more than 200 units?
	if(deltaPosition > 200 && OnGround())
	{
		// Fire the actor walked event
		Game()->Actors.ActorWalked.Fire([this](function<void(ActorPlayer*)> subscriber)
		{
			subscriber(this);
		});

		//cout << "Player Position: " << Position.x << "," << Position.y << "," << Position.z << endl;
		deltaPosition -=200;
	}

	// If we haven't, check if we should add more distance to our odometer
	else
	{
		if(OnGround())
		{
			deltaPosition+= sqrt(pow(Velocity.x,2)+pow(Velocity.y,2));
		}
	}

	// Lets check if the controller wants us to jump
	if(Game()->FirstPerson->GetJumpRequested())
	{
		// Check that the user is on the ground
		//and does not have any velocity upwards
		if (OnGround() && (Velocity.z < .025))
		{
			// Apply upwards velocity
			Velocity.z += jumpVelocity;

			// First the event that we'e
			Game()->Actors.ActorJumped.Fire([this](function<void(ActorPlayer*)> subscriber)
			{
				subscriber(this);
			});
		}
	}
	//Run autojump?
	if (VoxEngine::SavedDeviceData.GameOptions.Autojump > 0) {
		//Autojump
		if (glm::length(moveVector) > .15) {
			//Only jump if you're touching ground
			bool touchingGround = (OnGround() && Velocity.z < .2);
			//Check if you've got terrain (cliff/hill) directly in front of you
			//Check just a bit above your feet
			float feetHeight = Position.z-Size.z/2.0f;
			float checkHeight = feetHeight+.5f;
			float rayLength;
			vec3 surfaceNormal;
			vec3 traceDirection = vec3(moveVector,0);
			if (Game()->Voxels.RaytraceToTerrain(vec3(Position.x,Position.y,checkHeight),traceDirection,rayLength,surfaceNormal)) {
				if (rayLength < 1.5) {
					//Check the height of the given location
					//add .15 to go pas the surface and onto the voxel itself
					vec3 upcomingTerrain = vec3(Position.x,Position.y,checkHeight) + traceDirection*(rayLength+.15f);
					float upcomingHeight = Game()->Voxels.GetPositionHeight(vec2(upcomingTerrain));
					//Now check if you're too low
					if (feetHeight+.15 < upcomingHeight) {
						if (touchingGround) {
							//Ok lets jump up
							//Playing some kind of jump animation would be A+
							Velocity.z += min(15*(upcomingHeight-feetHeight),20.0f);
							//jump!
						}

					}
				}
			}
		}
	}

	// Return the result of the update of the super class
	return PhysicsActor::Update();
}