repo_id stringlengths 19 138 | file_path stringlengths 32 200 | content stringlengths 1 12.9M | __index_level_0__ int64 0 0 |
|---|---|---|---|
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/node_handle.cpp | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/node_handle.h"
#include "ros/this_node.h"
#include "ros/service.h"
#include "ros/callback_queue.h"
#include "ros/timer_manager.h"
#include "ros/time.h"
#include "ros/rate.h"
#include "ros/xmlrpc_manager.h"
#include "ros/topic_manager.h"
#include "ros/service_manager.h"
#include "ros/master.h"
#include "ros/param.h"
#include "ros/names.h"
#include "ros/init.h"
#include "ros/this_node.h"
#include "XmlRpc.h"
#include <boost/thread.hpp>
namespace ros
{
boost::mutex g_nh_refcount_mutex;
int32_t g_nh_refcount = 0;
bool g_node_started_by_nh = false;
class NodeHandleBackingCollection
{
public:
typedef std::vector<Publisher::ImplWPtr> V_PubImpl;
typedef std::vector<ServiceServer::ImplWPtr> V_SrvImpl;
typedef std::vector<Subscriber::ImplWPtr> V_SubImpl;
typedef std::vector<ServiceClient::ImplWPtr> V_SrvCImpl;
V_PubImpl pubs_;
V_SrvImpl srvs_;
V_SubImpl subs_;
V_SrvCImpl srv_cs_;
boost::mutex mutex_;
};
NodeHandle::NodeHandle(const std::string& ns, const M_string& remappings)
: namespace_(this_node::getNamespace())
, callback_queue_(0)
, collection_(0)
{
std::string tilde_resolved_ns;
if (!ns.empty() && ns[0] == '~')// starts with tilde
tilde_resolved_ns = names::resolve(ns);
else
tilde_resolved_ns = ns;
construct(tilde_resolved_ns, true);
initRemappings(remappings);
}
NodeHandle::NodeHandle(const NodeHandle& parent, const std::string& ns)
: collection_(0)
{
namespace_ = parent.getNamespace();
callback_queue_ = parent.callback_queue_;
remappings_ = parent.remappings_;
unresolved_remappings_ = parent.unresolved_remappings_;
construct(ns, false);
}
NodeHandle::NodeHandle(const NodeHandle& parent, const std::string& ns, const M_string& remappings)
: collection_(0)
{
namespace_ = parent.getNamespace();
callback_queue_ = parent.callback_queue_;
remappings_ = parent.remappings_;
unresolved_remappings_ = parent.unresolved_remappings_;
construct(ns, false);
initRemappings(remappings);
}
NodeHandle::NodeHandle(const NodeHandle& rhs)
: collection_(0)
{
callback_queue_ = rhs.callback_queue_;
remappings_ = rhs.remappings_;
unresolved_remappings_ = rhs.unresolved_remappings_;
construct(rhs.namespace_, true);
unresolved_namespace_ = rhs.unresolved_namespace_;
}
NodeHandle::~NodeHandle()
{
destruct();
}
NodeHandle& NodeHandle::operator=(const NodeHandle& rhs)
{
ROS_ASSERT(collection_);
namespace_ = rhs.namespace_;
callback_queue_ = rhs.callback_queue_;
remappings_ = rhs.remappings_;
unresolved_remappings_ = rhs.unresolved_remappings_;
return *this;
}
void spinThread()
{
ros::spin();
}
void NodeHandle::construct(const std::string& ns, bool validate_name)
{
if (!ros::isInitialized())
{
ROS_FATAL("You must call ros::init() before creating the first NodeHandle");
ROS_BREAK();
}
collection_ = new NodeHandleBackingCollection;
unresolved_namespace_ = ns;
// if callback_queue_ is nonnull, we are in a non-nullary constructor
if (validate_name)
namespace_ = resolveName(ns, true);
else
{
namespace_ = resolveName(ns, true, no_validate());
// FIXME validate namespace_ now
}
ok_ = true;
boost::mutex::scoped_lock lock(g_nh_refcount_mutex);
if (g_nh_refcount == 0 && !ros::isStarted())
{
g_node_started_by_nh = true;
ros::start();
}
++g_nh_refcount;
}
void NodeHandle::destruct()
{
delete collection_;
boost::mutex::scoped_lock lock(g_nh_refcount_mutex);
--g_nh_refcount;
if (g_nh_refcount == 0 && g_node_started_by_nh)
{
ros::shutdown();
}
}
void NodeHandle::initRemappings(const M_string& remappings)
{
{
M_string::const_iterator it = remappings.begin();
M_string::const_iterator end = remappings.end();
for (; it != end; ++it)
{
const std::string& from = it->first;
const std::string& to = it->second;
remappings_.insert(std::make_pair(resolveName(from, false), resolveName(to, false)));
unresolved_remappings_.insert(std::make_pair(from, to));
}
}
}
void NodeHandle::setCallbackQueue(CallbackQueueInterface* queue)
{
callback_queue_ = queue;
}
std::string NodeHandle::remapName(const std::string& name) const
{
std::string resolved = resolveName(name, false);
// First search any remappings that were passed in specifically for this NodeHandle
M_string::const_iterator it = remappings_.find(resolved);
if (it != remappings_.end())
{
// ROSCPP_LOG_DEBUG("found 'local' remapping: %s", it->second.c_str());
return it->second;
}
// If not in our local remappings, perhaps in the global ones
return names::remap(resolved);
}
std::string NodeHandle::resolveName(const std::string& name, bool remap) const
{
// ROSCPP_LOG_DEBUG("resolveName(%s, %s)", name.c_str(), remap ? "true" : "false");
std::string error;
if (!names::validate(name, error))
{
throw InvalidNameException(error);
}
return resolveName(name, remap, no_validate());
}
std::string NodeHandle::resolveName(const std::string& name, bool remap, no_validate) const
{
if (name.empty())
{
return namespace_;
}
std::string final = name;
if (final[0] == '~')
{
std::stringstream ss;
ss << "Using ~ names with NodeHandle methods is not allowed. If you want to use private names with the NodeHandle ";
ss << "interface, construct a NodeHandle using a private name as its namespace. e.g. ";
ss << "ros::NodeHandle nh(\"~\"); ";
ss << "nh.getParam(\"my_private_name\");";
ss << " (name = [" << name << "])";
throw InvalidNameException(ss.str());
}
else if (final[0] == '/')
{
// do nothing
}
else if (!namespace_.empty())
{
// ROSCPP_LOG_DEBUG("Appending namespace_ (%s)", namespace_.c_str());
final = names::append(namespace_, final);
}
// ROSCPP_LOG_DEBUG("resolveName, pre-clean: %s", final.c_str());
final = names::clean(final);
// ROSCPP_LOG_DEBUG("resolveName, post-clean: %s", final.c_str());
if (remap)
{
final = remapName(final);
// ROSCPP_LOG_DEBUG("resolveName, remapped: %s", final.c_str());
}
return names::resolve(final, false);
}
Publisher NodeHandle::advertise(AdvertiseOptions& ops)
{
ops.topic = resolveName(ops.topic);
if (ops.callback_queue == 0)
{
if (callback_queue_)
{
ops.callback_queue = callback_queue_;
}
else
{
ops.callback_queue = getGlobalCallbackQueue();
}
}
SubscriberCallbacksPtr callbacks(boost::make_shared<SubscriberCallbacks>(ops.connect_cb, ops.disconnect_cb,
ops.tracked_object, ops.callback_queue));
if (TopicManager::instance()->advertise(ops, callbacks))
{
Publisher pub(ops.topic, ops.md5sum, ops.datatype, ops.message_definition, *this, callbacks, ops.queue_size);
{
boost::mutex::scoped_lock lock(collection_->mutex_);
collection_->pubs_.push_back(pub.impl_);
}
return pub;
}
return Publisher();
}
Subscriber NodeHandle::subscribe(SubscribeOptions& ops)
{
ops.topic = resolveName(ops.topic);
if (ops.callback_queue == 0)
{
if (callback_queue_)
{
ops.callback_queue = callback_queue_;
}
else
{
ops.callback_queue = getGlobalCallbackQueue();
}
}
if (TopicManager::instance()->subscribe(ops))
{
Subscriber sub(ops.topic, *this, ops.helper);
{
boost::mutex::scoped_lock lock(collection_->mutex_);
collection_->subs_.push_back(sub.impl_);
}
return sub;
}
return Subscriber();
}
ServiceServer NodeHandle::advertiseService(AdvertiseServiceOptions& ops)
{
ops.service = resolveName(ops.service);
if (ops.callback_queue == 0)
{
if (callback_queue_)
{
ops.callback_queue = callback_queue_;
}
else
{
ops.callback_queue = getGlobalCallbackQueue();
}
}
if (ServiceManager::instance()->advertiseService(ops))
{
ServiceServer srv(ops.service, *this);
{
boost::mutex::scoped_lock lock(collection_->mutex_);
collection_->srvs_.push_back(srv.impl_);
}
return srv;
}
return ServiceServer();
}
ServiceClient NodeHandle::serviceClient(ServiceClientOptions& ops)
{
ops.service = resolveName(ops.service);
ServiceClient client(ops.service, ops.persistent, ops.header, ops.md5sum);
if (client)
{
boost::mutex::scoped_lock lock(collection_->mutex_);
collection_->srv_cs_.push_back(client.impl_);
}
return client;
}
Timer NodeHandle::createTimer(Duration period, const TimerCallback& callback,
bool oneshot, bool autostart) const
{
TimerOptions ops;
ops.period = period;
ops.callback = callback;
ops.oneshot = oneshot;
ops.autostart = autostart;
return createTimer(ops);
}
Timer NodeHandle::createTimer(TimerOptions& ops) const
{
if (ops.callback_queue == 0)
{
if (callback_queue_)
{
ops.callback_queue = callback_queue_;
}
else
{
ops.callback_queue = getGlobalCallbackQueue();
}
}
Timer timer(ops);
if (ops.autostart)
timer.start();
return timer;
}
WallTimer NodeHandle::createWallTimer(WallDuration period, const WallTimerCallback& callback,
bool oneshot, bool autostart) const
{
WallTimerOptions ops;
ops.period = period;
ops.callback = callback;
ops.oneshot = oneshot;
ops.autostart = autostart;
return createWallTimer(ops);
}
WallTimer NodeHandle::createWallTimer(WallTimerOptions& ops) const
{
if (ops.callback_queue == 0)
{
if (callback_queue_)
{
ops.callback_queue = callback_queue_;
}
else
{
ops.callback_queue = getGlobalCallbackQueue();
}
}
WallTimer timer(ops);
if (ops.autostart)
timer.start();
return timer;
}
void NodeHandle::shutdown()
{
{
NodeHandleBackingCollection::V_SubImpl::iterator it = collection_->subs_.begin();
NodeHandleBackingCollection::V_SubImpl::iterator end = collection_->subs_.end();
for (; it != end; ++it)
{
Subscriber::ImplPtr impl = it->lock();
if (impl)
{
impl->unsubscribe();
}
}
}
{
NodeHandleBackingCollection::V_PubImpl::iterator it = collection_->pubs_.begin();
NodeHandleBackingCollection::V_PubImpl::iterator end = collection_->pubs_.end();
for (; it != end; ++it)
{
Publisher::ImplPtr impl = it->lock();
if (impl)
{
impl->unadvertise();
}
}
}
{
NodeHandleBackingCollection::V_SrvImpl::iterator it = collection_->srvs_.begin();
NodeHandleBackingCollection::V_SrvImpl::iterator end = collection_->srvs_.end();
for (; it != end; ++it)
{
ServiceServer::ImplPtr impl = it->lock();
if (impl)
{
impl->unadvertise();
}
}
}
{
NodeHandleBackingCollection::V_SrvCImpl::iterator it = collection_->srv_cs_.begin();
NodeHandleBackingCollection::V_SrvCImpl::iterator end = collection_->srv_cs_.end();
for (; it != end; ++it)
{
ServiceClient::ImplPtr impl = it->lock();
if (impl)
{
impl->shutdown();
}
}
}
ok_ = false;
}
void NodeHandle::setParam(const std::string& key, const XmlRpc::XmlRpcValue& v) const
{
return param::set(resolveName(key), v);
}
void NodeHandle::setParam(const std::string& key, const std::string& s) const
{
return param::set(resolveName(key), s);
}
void NodeHandle::setParam(const std::string& key, const char* s) const
{
return param::set(resolveName(key), s);
}
void NodeHandle::setParam(const std::string& key, double d) const
{
return param::set(resolveName(key), d);
}
void NodeHandle::setParam(const std::string& key, int i) const
{
return param::set(resolveName(key), i);
}
void NodeHandle::setParam(const std::string& key, bool b) const
{
return param::set(resolveName(key), b);
}
void NodeHandle::setParam(const std::string& key, const std::vector<std::string>& vec) const
{
return param::set(resolveName(key), vec);
}
void NodeHandle::setParam(const std::string& key, const std::vector<double>& vec) const
{
return param::set(resolveName(key), vec);
}
void NodeHandle::setParam(const std::string& key, const std::vector<float>& vec) const
{
return param::set(resolveName(key), vec);
}
void NodeHandle::setParam(const std::string& key, const std::vector<int>& vec) const
{
return param::set(resolveName(key), vec);
}
void NodeHandle::setParam(const std::string& key, const std::vector<bool>& vec) const
{
return param::set(resolveName(key), vec);
}
void NodeHandle::setParam(const std::string& key, const std::map<std::string, std::string>& map) const
{
return param::set(resolveName(key), map);
}
void NodeHandle::setParam(const std::string& key, const std::map<std::string, double>& map) const
{
return param::set(resolveName(key), map);
}
void NodeHandle::setParam(const std::string& key, const std::map<std::string, float>& map) const
{
return param::set(resolveName(key), map);
}
void NodeHandle::setParam(const std::string& key, const std::map<std::string, int>& map) const
{
return param::set(resolveName(key), map);
}
void NodeHandle::setParam(const std::string& key, const std::map<std::string, bool>& map) const
{
return param::set(resolveName(key), map);
}
bool NodeHandle::hasParam(const std::string& key) const
{
return param::has(resolveName(key));
}
bool NodeHandle::deleteParam(const std::string& key) const
{
return param::del(resolveName(key));
}
bool NodeHandle::getParamNames(std::vector<std::string>& keys) const
{
return param::getParamNames(keys);
}
bool NodeHandle::getParam(const std::string& key, XmlRpc::XmlRpcValue& v) const
{
return param::get(resolveName(key), v);
}
bool NodeHandle::getParam(const std::string& key, std::string& s) const
{
return param::get(resolveName(key), s);
}
bool NodeHandle::getParam(const std::string& key, double& d) const
{
return param::get(resolveName(key), d);
}
bool NodeHandle::getParam(const std::string& key, float& f) const
{
return param::get(resolveName(key), f);
}
bool NodeHandle::getParam(const std::string& key, int& i) const
{
return param::get(resolveName(key), i);
}
bool NodeHandle::getParam(const std::string& key, bool& b) const
{
return param::get(resolveName(key), b);
}
bool NodeHandle::getParam(const std::string& key, std::vector<std::string>& vec) const
{
return param::get(resolveName(key), vec);
}
bool NodeHandle::getParam(const std::string& key, std::vector<double>& vec) const
{
return param::get(resolveName(key), vec);
}
bool NodeHandle::getParam(const std::string& key, std::vector<float>& vec) const
{
return param::get(resolveName(key), vec);
}
bool NodeHandle::getParam(const std::string& key, std::vector<int>& vec) const
{
return param::get(resolveName(key), vec);
}
bool NodeHandle::getParam(const std::string& key, std::vector<bool>& vec) const
{
return param::get(resolveName(key), vec);
}
bool NodeHandle::getParam(const std::string& key, std::map<std::string, std::string>& map) const
{
return param::get(resolveName(key), map);
}
bool NodeHandle::getParam(const std::string& key, std::map<std::string, double>& map) const
{
return param::get(resolveName(key), map);
}
bool NodeHandle::getParam(const std::string& key, std::map<std::string, float>& map) const
{
return param::get(resolveName(key), map);
}
bool NodeHandle::getParam(const std::string& key, std::map<std::string, int>& map) const
{
return param::get(resolveName(key), map);
}
bool NodeHandle::getParam(const std::string& key, std::map<std::string, bool>& map) const
{
return param::get(resolveName(key), map);
}
bool NodeHandle::getParamCached(const std::string& key, XmlRpc::XmlRpcValue& v) const
{
return param::getCached(resolveName(key), v);
}
bool NodeHandle::getParamCached(const std::string& key, std::string& s) const
{
return param::getCached(resolveName(key), s);
}
bool NodeHandle::getParamCached(const std::string& key, double& d) const
{
return param::getCached(resolveName(key), d);
}
bool NodeHandle::getParamCached(const std::string& key, float& f) const
{
return param::getCached(resolveName(key), f);
}
bool NodeHandle::getParamCached(const std::string& key, int& i) const
{
return param::getCached(resolveName(key), i);
}
bool NodeHandle::getParamCached(const std::string& key, bool& b) const
{
return param::getCached(resolveName(key), b);
}
bool NodeHandle::getParamCached(const std::string& key, std::vector<std::string>& vec) const
{
return param::getCached(resolveName(key), vec);
}
bool NodeHandle::getParamCached(const std::string& key, std::vector<double>& vec) const
{
return param::getCached(resolveName(key), vec);
}
bool NodeHandle::getParamCached(const std::string& key, std::vector<float>& vec) const
{
return param::getCached(resolveName(key), vec);
}
bool NodeHandle::getParamCached(const std::string& key, std::vector<int>& vec) const
{
return param::getCached(resolveName(key), vec);
}
bool NodeHandle::getParamCached(const std::string& key, std::vector<bool>& vec) const
{
return param::getCached(resolveName(key), vec);
}
bool NodeHandle::getParamCached(const std::string& key, std::map<std::string, std::string>& map) const
{
return param::getCached(resolveName(key), map);
}
bool NodeHandle::getParamCached(const std::string& key, std::map<std::string, double>& map) const
{
return param::getCached(resolveName(key), map);
}
bool NodeHandle::getParamCached(const std::string& key, std::map<std::string, float>& map) const
{
return param::getCached(resolveName(key), map);
}
bool NodeHandle::getParamCached(const std::string& key, std::map<std::string, int>& map) const
{
return param::getCached(resolveName(key), map);
}
bool NodeHandle::getParamCached(const std::string& key, std::map<std::string, bool>& map) const
{
return param::getCached(resolveName(key), map);
}
bool NodeHandle::searchParam(const std::string& key, std::string& result_out) const
{
// searchParam needs a separate form of remapping -- remapping on the unresolved name, rather than the
// resolved one.
std::string remapped = key;
M_string::const_iterator it = unresolved_remappings_.find(key);
// First try our local remappings
if (it != unresolved_remappings_.end())
{
remapped = it->second;
}
return param::search(resolveName(""), remapped, result_out);
}
bool NodeHandle::ok() const
{
return ros::ok() && ok_;
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/broadcast_manager.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/xmlrpc_manager.h"
#include "ros/broadcast_manager.h"
#include "ros/network.h"
#include "ros/assert.h"
#include "ros/common.h"
#include "ros/file_log.h"
#include "ros/this_node.h"
#include "ros/io.h"
#include "ros/init.h"
#include "ros/time.h"
#include <string>
#include <cstdlib>
#include <sstream>
#include <chrono>
namespace ros
{
BroadcastManagerPtr g_br_manager;
std::mutex g_br_manager_mutex;
const BroadcastManagerPtr& BroadcastManager::instance()
{
if (!g_br_manager)
{
std::lock_guard<std::mutex> lg(g_br_manager_mutex);
if (!g_br_manager)
{
g_br_manager.reset(new BroadcastManager);
}
}
return g_br_manager;
}
BroadcastManager::BroadcastManager() : shutting_down_(false)
{
xmlrpc_manager_ = XMLRPCManager::instance();
topic_manager_ = TopicManager::instance();
initCallbacks();
node_timestamp_ = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
part_.reset(new Participant(this_node::getName()));
static auto f = [this] (const std::string& msg) {this->commonCallback(msg);};
if (!part_->init(f))
{
ROS_ERROR_STREAM("+++BroadcastManager+++ Init Participant failed.");
}
}
void BroadcastManager::start()
{
shutting_down_ = false;
usleep(1000000);
registerNode();
}
void BroadcastManager::initCallbacks()
{
REGISTRY(registerPublisher, registerPublisher);
REGISTRY(unregisterPublisher, unregisterPublisher);
REGISTRY(registerSubscriber, registerSubscriber);
REGISTRY(unregisterSubscriber, unregisterSubscriber);
REGISTRY(registerService, registerService);
REGISTRY(unregisterService, unregisterService);
}
BroadcastManager::~BroadcastManager()
{
shutdown();
}
void BroadcastManager::registerNode()
{
MsgInfo req = generateMessage("registerNode");
req.put(NODE_TIME, std::to_string(node_timestamp_));
sendMessage(req);
}
void BroadcastManager::sendMessage(const MsgInfo& pt)
{
std::stringstream ss;
write_json(ss, pt);
sendMessage(ss.str());
}
void BroadcastManager::sendMessage(const std::string& msg)
{
ROS_DEBUG_STREAM("[BroadcastManager]Send msg: " << msg);
part_->send(msg);
}
void BroadcastManager::shutdown()
{
if (isShuttingDown())
{
return;
}
shutting_down_ = true;
}
PubInfo BroadcastManager::getPubs(const std::string& topic_name)
{
return pub_cache_[topic_name];
}
SubInfo BroadcastManager::getSubs(const std::string& topic_name)
{
return sub_cache_[topic_name];
}
void BroadcastManager::publisherUpdate(const std::string& topic_name)
{
std::vector<std::string> pubs(pub_cache_[topic_name].begin(), pub_cache_[topic_name].end());
topic_manager_->pubUpdate(topic_name, pubs);
}
/********* message callbacks **********/
void BroadcastManager::registerPublisherCallback(const MsgInfo& result)
{
std::string topic_name = result.get<std::string>(TOPIC_NAME);
std::string pub_uri = result.get<std::string>(XMLRPC_URI);
pub_cache_[topic_name].insert(pub_uri);
topic_cache_.emplace_back(topic_name, pub_uri);
publisherUpdate(topic_name);
}
void BroadcastManager::unregisterPublisherCallback(const MsgInfo& result)
{
std::string topic_name = result.get<std::string>(TOPIC_NAME);
std::string uri = result.get<std::string>(XMLRPC_URI);
auto it = pub_cache_[topic_name].find(uri);
if (it != pub_cache_[topic_name].end())
{
pub_cache_[topic_name].erase(it);
}
publisherUpdate(topic_name);
}
void BroadcastManager::registerSubscriberCallback(const MsgInfo& result)
{
std::string topic_name = result.get<std::string>(TOPIC_NAME);
std::string sub_uri = result.get<std::string>(XMLRPC_URI);
sub_cache_[topic_name].insert(sub_uri);
}
void BroadcastManager::unregisterSubscriberCallback(const MsgInfo& result)
{
std::string topic = result.get<std::string>(TOPIC_NAME);
std::string uri = result.get<std::string>(XMLRPC_URI);
auto it = sub_cache_[topic].find(uri);
if (it != sub_cache_[topic].end())
{
sub_cache_[topic].erase(it);
}
}
void BroadcastManager::registerServiceCallback(const MsgInfo& result)
{
std::string service_name = result.get<std::string>(SERVICE_NAME);
std::string uri = result.get<std::string>(SERVICE_URI);
ServiceInfo si;
si.uri = uri;
si.is_owner = false;
service_cache_[service_name] = std::move(si);
}
void BroadcastManager::unregisterServiceCallback(const MsgInfo& result)
{
std::string srv_name = result.get<std::string>(SERVICE_NAME);
std::string uri = result.get<std::string>(SERVICE_URI);
auto it = service_cache_.find(srv_name);
if (it != service_cache_.end() && it->second.uri == uri)
{
service_cache_.erase(it);
}
}
void BroadcastManager::commonCallback(const std::string& msg)
{
MsgInfo result;
std::stringstream ss(msg);
try
{
read_json(ss, result);
}
catch (std::exception const& e)
{
ROS_ERROR_STREAM("Failed to parse message: " << e.what());
return;
}
if (result.get<std::string>(NODE_NAME) == this_node::getName())
{
if (result.get<std::string>(REQUEST_TYPE) == "registerNode"
&& result.get<std::string>(XMLRPC_URI) != xmlrpc_manager_->getServerURI()
&& std::stoul(result.get<std::string>(NODE_TIME)) > node_timestamp_)
{
ROS_ERROR_STREAM("Shutdown! Another node registered with same name");
requestShutdown();
}
return;
}
ROS_DEBUG_STREAM("[BroadcastManager] Recv msg: " << msg.c_str());
auto it = functions_.find(result.get<std::string>(REQUEST_TYPE));
if (it != functions_.end())
{
it->second(result);
}
else
{
ROS_DEBUG_STREAM("invalid request type: " << result.get<std::string>(REQUEST_TYPE).c_str());
}
}
/************************* Interfaces ********************************/
void BroadcastManager::registerPublisher(const std::string& topic,
const std::string& datatype,
const std::string& uri)
{
MsgInfo req = generateMessage("registerPublisher");
req.put(TOPIC_NAME, topic);
req.put(TOPIC_TYPE, datatype);
sendMessage(req);
TopicInfo ti;
ti.type = datatype;
advertised_topics_[topic] = ti;
pub_cache_[topic].insert(uri);
}
void BroadcastManager::unregisterPublisher(const std::string& topic_name, const std::string& uri)
{
(void)uri;
MsgInfo req = generateMessage("unregisterPublisher");
req.put(TOPIC_NAME, topic_name);
req.put(TOPIC_URI, uri);
sendMessage(req);
auto it = pub_cache_[topic_name].find(req.get<std::string>(XMLRPC_URI));
if (it != pub_cache_[topic_name].end())
{
pub_cache_[topic_name].erase(it);
}
}
void BroadcastManager::registerSubscriber(const std::string& topic, const std::string& type, const std::string& uri)
{
(void)uri;
MsgInfo req = generateMessage("registerSubscriber");
req.put(TOPIC_NAME, topic);
req.put(TOPIC_TYPE, type);
sendMessage(req);
sub_cache_[topic].insert(req.get<std::string>(XMLRPC_URI));
}
void BroadcastManager::unregisterSubscriber(const std::string& topic, const std::string& uri)
{
(void)uri;
MsgInfo req = generateMessage("unregisterSubscriber");
req.put(TOPIC_NAME, topic);
req.put(TOPIC_URI, uri);
sendMessage(req);
auto it = sub_cache_[topic].find(req.get<std::string>(XMLRPC_URI));
if (it != sub_cache_[topic].end())
{
sub_cache_[topic].erase(it);
}
}
void BroadcastManager::registerService(const std::string& node_name,
const std::string& srv_name,
const std::string& uri_buf,
const std::string& uri)
{
(void)node_name;
(void)uri;
MsgInfo req = generateMessage("registerService");
req.put(SERVICE_NAME, srv_name);
req.put(SERVICE_URI, uri_buf);
sendMessage(req);
ServiceInfo si;
si.uri = uri_buf;
si.is_owner = true;
service_cache_[srv_name] = std::move(si);
}
void BroadcastManager::unregisterService(const std::string& srv_name, const std::string& uri)
{
MsgInfo req = generateMessage("unregisterService");
req.put(SERVICE_NAME, srv_name);
req.put(SERVICE_URI, uri);
sendMessage(req);
}
bool BroadcastManager::lookupService(const std::string& service_name, std::string& service_uri, int timeout)
{
(void)timeout;
usleep(1000);
auto it = service_cache_.find(service_name);
if (it != service_cache_.end())
{
service_uri = it->second.uri;
}
else
{
return false;
}
return true;
}
MsgInfo BroadcastManager::generateMessage(const std::string& request_type)
{
uint64_t timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
return generateMessage(request_type, timestamp);
}
MsgInfo BroadcastManager::generateMessage(const std::string& request_type, uint64_t timestamp)
{
MsgInfo req;
req.put(NODE_NAME, this_node::getName());
req.put(REQUEST_TYPE, request_type);
req.put(TIMESTAMP, std::to_string(timestamp));
req.put(XMLRPC_URI, xmlrpc_manager_->getServerURI());
return req;
}
void BroadcastManager::getNodes(V_string& nodes)
{
for (auto& pub: pub_cache_)
{
nodes.push_back(pub.first);
}
}
void BroadcastManager::getTopics(master::V_TopicInfo& topics)
{
topics.clear();
topics.insert(topics.begin(), topic_cache_.begin(), topic_cache_.end());
}
void BroadcastManager::getTopicTypes(master::V_TopicInfo& topics)
{
return getTopics(topics);
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/internal_timer_manager.cpp | /*
* Copyright (C) 2010, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/internal_timer_manager.h"
#include "ros/timer_manager.h"
namespace ros
{
static InternalTimerManagerPtr g_timer_manager;
InternalTimerManagerPtr getInternalTimerManager()
{
return g_timer_manager;
}
void initInternalTimerManager()
{
if (!g_timer_manager)
{
g_timer_manager.reset(new InternalTimerManager);
}
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/subscriber_link.cpp | /*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/subscriber_link.h"
#include "ros/publication.h"
#include <boost/bind.hpp>
namespace ros
{
SubscriberLink::SubscriberLink()
: connection_id_(0), default_transport_(false), rospy_(false)
{
}
SubscriberLink::~SubscriberLink()
{
}
bool SubscriberLink::verifyDatatype(const std::string &datatype)
{
PublicationPtr parent = parent_.lock();
if (!parent)
{
ROS_ERROR("Trying to verify the datatype on a publisher without a parent");
ROS_BREAK();
return false;
}
if (datatype != parent->getDataType())
{
ROS_ERROR( "tried to send a message with type %s on a " \
"TransportSubscriberLink that has datatype %s",
datatype.c_str(), parent->getDataType().c_str());
return false; // todo: figure out a way to log this error
}
return true;
}
const std::string& SubscriberLink::getMD5Sum()
{
PublicationPtr parent = parent_.lock();
return parent->getMD5Sum();
}
const std::string& SubscriberLink::getDataType()
{
PublicationPtr parent = parent_.lock();
return parent->getDataType();
}
const std::string& SubscriberLink::getMessageDefinition()
{
PublicationPtr parent = parent_.lock();
return parent->getMessageDefinition();
}
void SubscriberLink::setDefaultTransport(bool default_transport)
{
default_transport_ = default_transport ;
}
bool SubscriberLink::getDefaultTransport ()
{
return default_transport_;
}
void SubscriberLink::setRospy(bool rospy)
{
rospy_ = rospy ;
}
bool SubscriberLink::getRospy ()
{
return rospy_ ;
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/subscription_queue.cpp | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/subscription_queue.h"
#include "ros/message_deserializer.h"
#include "ros/subscription_callback_helper.h"
#include "roscpp/SharedMemoryHeader.h"
#include "boost/bind.hpp"
#include "ros/names.h"
#include <thread>
#include "ros/config_comm.h"
namespace ros
{
SubscriptionQueue::SubscriptionQueue(const std::string& topic, int32_t queue_size, bool allow_concurrent_callbacks)
: topic_(topic)
, size_(queue_size)
, full_(false)
, queue_size_(0)
, allow_concurrent_callbacks_(allow_concurrent_callbacks)
, first_run_(true)
, internal_cb_runnning_(false)
, last_read_index_(-1)
{}
SubscriptionQueue::~SubscriptionQueue()
{
}
void SubscriptionQueue::push(bool default_transport, const SubscriptionCallbackHelperPtr& helper, const MessageDeserializerPtr& deserializer,
bool has_tracked_object, const VoidConstWPtr& tracked_object, bool nonconst_need_copy,
ros::Time receipt_time, bool* was_full)
{
boost::mutex::scoped_lock lock(queue_mutex_);
if (was_full)
{
*was_full = false;
}
if(fullNoLock())
{
queue_.pop_front();
--queue_size_;
if (!full_)
{
ROS_DEBUG("Incoming queue full for topic \"%s\". Discarding oldest message (current queue size [%d])", topic_.c_str(), (int)queue_.size());
}
full_ = true;
if (was_full)
{
*was_full = true;
}
}
else
{
full_ = false;
}
Item i;
i.default_transport = default_transport;
i.helper = helper;
i.deserializer = deserializer;
i.has_tracked_object = has_tracked_object;
i.tracked_object = tracked_object;
i.nonconst_need_copy = nonconst_need_copy;
i.receipt_time = receipt_time;
queue_.push_back(i);
++queue_size_;
}
void SubscriptionQueue::clear()
{
boost::recursive_mutex::scoped_lock cb_lock(callback_mutex_);
boost::mutex::scoped_lock queue_lock(queue_mutex_);
queue_.clear();
queue_size_ = 0;
}
CallbackInterface::CallResult SubscriptionQueue::call()
{
// The callback may result in our own destruction. Therefore, we may need to keep a reference to ourselves
// that outlasts the scoped_try_lock
boost::shared_ptr<SubscriptionQueue> self;
boost::recursive_mutex::scoped_try_lock lock(callback_mutex_, boost::defer_lock);
if (!allow_concurrent_callbacks_)
{
lock.try_lock();
if (!lock.owns_lock())
{
return CallbackInterface::TryAgain;
}
}
VoidConstPtr tracker;
Item i;
{
boost::mutex::scoped_lock lock(queue_mutex_);
if (queue_.empty())
{
return CallbackInterface::Invalid;
}
i = queue_.front();
if (queue_.empty())
{
return CallbackInterface::Invalid;
}
if (i.has_tracked_object)
{
tracker = i.tracked_object.lock();
if (!tracker)
{
return CallbackInterface::Invalid;
}
}
queue_.pop_front();
--queue_size_;
}
VoidConstPtr msg = i.deserializer->deserialize();
// msg can be null here if deserialization failed
if (msg)
{
try
{
self = shared_from_this();
}
catch (boost::bad_weak_ptr&) // For the tests, where we don't create a shared_ptr
{}
SubscriptionCallbackHelperCallParams params;
params.event = MessageEvent<void const>(msg, i.deserializer->getConnectionHeader(), i.receipt_time, i.nonconst_need_copy, MessageEvent<void const>::CreateFunction());
i.helper->call(params);
}
return CallbackInterface::Success;
}
bool SubscriptionQueue::ready()
{
return true;
}
bool SubscriptionQueue::full()
{
boost::mutex::scoped_lock lock(queue_mutex_);
return fullNoLock();
}
bool SubscriptionQueue::fullNoLock()
{
return (size_ > 0) && (queue_size_ >= (uint32_t)size_);
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/init.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/init.h"
#include "ros/names.h"
#include "ros/broadcast_manager.h"
#include "ros/xmlrpc_manager.h"
#include "ros/poll_manager.h"
#include "ros/connection_manager.h"
#include "ros/topic_manager.h"
#include "ros/service_manager.h"
#include "ros/this_node.h"
#include "ros/network.h"
#include "ros/file_log.h"
#include "ros/callback_queue.h"
#include "ros/param.h"
#include "ros/rosout_appender.h"
#include "ros/subscribe_options.h"
#include "ros/transport/transport_tcp.h"
#include "ros/internal_timer_manager.h"
#include "XmlRpcSocket.h"
#include "roscpp/GetLoggers.h"
#include "roscpp/SetLoggerLevel.h"
#include "roscpp/Empty.h"
#include <ros/console.h>
#include <ros/time.h>
#include <rosgraph_msgs/Clock.h>
#include <algorithm>
#include <signal.h>
#include <cstdlib>
#include "ros/config_comm.h"
#include "ros/shm_manager.h"
#include "yaml-cpp/yaml.h"
namespace ros
{
namespace master
{
void init(const M_string& remappings);
}
namespace this_node
{
void init(const std::string& names, const M_string& remappings, uint32_t options);
}
namespace network
{
void init(const M_string& remappings);
}
namespace param
{
void init(const M_string& remappings);
}
namespace file_log
{
void init(const M_string& remappings);
}
CallbackQueuePtr g_global_queue;
ROSOutAppender* g_rosout_appender;
static CallbackQueuePtr g_internal_callback_queue;
static bool g_initialized = false;
static bool g_started = false;
static bool g_atexit_registered = false;
static boost::mutex g_start_mutex;
static bool g_ok = false;
static uint32_t g_init_options = 0;
static bool g_shutdown_requested = false;
static volatile bool g_shutting_down = false;
static boost::recursive_mutex g_shutting_down_mutex;
static boost::thread g_internal_queue_thread;
struct ConfigComm g_config_comm;
bool isInitialized()
{
return g_initialized;
}
bool isShuttingDown()
{
return g_shutting_down;
}
void checkForShutdown()
{
if (g_shutdown_requested)
{
// Since this gets run from within a mutex inside PollManager, we need to prevent ourselves from deadlocking with
// another thread that's already in the middle of shutdown()
boost::recursive_mutex::scoped_try_lock lock(g_shutting_down_mutex, boost::defer_lock);
while (!lock.try_lock() && !g_shutting_down)
{
ros::WallDuration(0.001).sleep();
}
if (!g_shutting_down)
{
shutdown();
}
g_shutdown_requested = false;
}
}
void requestShutdown()
{
g_shutdown_requested = true;
}
void atexitCallback()
{
if (ok() && !isShuttingDown())
{
ROSCPP_LOG_DEBUG("shutting down due to exit() or end of main() without cleanup of all NodeHandles");
shutdown();
}
}
void shutdownCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result)
{
int num_params = 0;
if (params.getType() == XmlRpc::XmlRpcValue::TypeArray)
num_params = params.size();
if (num_params > 1)
{
std::string reason = params[1];
ROS_WARN("Shutdown request received.");
ROS_WARN("Reason given for shutdown: [%s]", reason.c_str());
requestShutdown();
}
result = xmlrpc::responseInt(1, "", 0);
}
bool getLoggers(roscpp::GetLoggers::Request&, roscpp::GetLoggers::Response& resp)
{
std::map<std::string, ros::console::levels::Level> loggers;
bool success = ::ros::console::get_loggers(loggers);
if (success)
{
for (std::map<std::string, ros::console::levels::Level>::const_iterator it = loggers.begin(); it != loggers.end(); it++)
{
roscpp::Logger logger;
logger.name = it->first;
ros::console::levels::Level level = it->second;
if (level == ros::console::levels::Debug)
{
logger.level = "debug";
}
else if (level == ros::console::levels::Info)
{
logger.level = "info";
}
else if (level == ros::console::levels::Warn)
{
logger.level = "warn";
}
else if (level == ros::console::levels::Error)
{
logger.level = "error";
}
else if (level == ros::console::levels::Fatal)
{
logger.level = "fatal";
}
resp.loggers.push_back(logger);
}
}
return success;
}
bool setLoggerLevel(roscpp::SetLoggerLevel::Request& req, roscpp::SetLoggerLevel::Response&)
{
std::transform(req.level.begin(), req.level.end(), req.level.begin(), (int(*)(int))std::toupper);
ros::console::levels::Level level;
if (req.level == "DEBUG")
{
level = ros::console::levels::Debug;
}
else if (req.level == "INFO")
{
level = ros::console::levels::Info;
}
else if (req.level == "WARN")
{
level = ros::console::levels::Warn;
}
else if (req.level == "ERROR")
{
level = ros::console::levels::Error;
}
else if (req.level == "FATAL")
{
level = ros::console::levels::Fatal;
}
else
{
return false;
}
bool success = ::ros::console::set_logger_level(req.logger, level);
if (success)
{
console::notifyLoggerLevelsChanged();
}
return success;
}
bool closeAllConnections(roscpp::Empty::Request&, roscpp::Empty::Response&)
{
ROSCPP_LOG_DEBUG("close_all_connections service called, closing connections");
ConnectionManager::instance()->clear(Connection::TransportDisconnect);
return true;
}
void clockCallback(const rosgraph_msgs::Clock::ConstPtr& msg)
{
Time::setNow(msg->clock);
}
CallbackQueuePtr getInternalCallbackQueue()
{
if (!g_internal_callback_queue)
{
g_internal_callback_queue.reset(new CallbackQueue);
}
return g_internal_callback_queue;
}
void basicSigintHandler(int sig)
{
(void)sig;
ros::requestShutdown();
}
void internalCallbackQueueThreadFunc()
{
disableAllSignalsInThisThread();
CallbackQueuePtr queue = getInternalCallbackQueue();
while (!g_shutting_down)
{
queue->callAvailable(WallDuration(0.1));
}
}
bool isStarted()
{
return g_started;
}
void start()
{
boost::mutex::scoped_lock lock(g_start_mutex);
if (g_started)
{
return;
}
g_shutdown_requested = false;
g_shutting_down = false;
g_started = true;
g_ok = true;
bool enable_debug = false;
std::string enable_debug_env;
if ( get_environment_variable(enable_debug_env,"ROSCPP_ENABLE_DEBUG") )
{
try
{
enable_debug = boost::lexical_cast<bool>(enable_debug_env.c_str());
}
catch (boost::bad_lexical_cast&)
{
}
}
char* env_ipv6 = NULL;
#ifdef _MSC_VER
_dupenv_s(&env_ipv6, NULL, "ROS_IPV6");
#else
env_ipv6 = getenv("ROS_IPV6");
#endif
bool use_ipv6 = (env_ipv6 && strcmp(env_ipv6,"on") == 0);
TransportTCP::s_use_ipv6_ = use_ipv6;
XmlRpc::XmlRpcSocket::s_use_ipv6_ = use_ipv6;
#ifdef _MSC_VER
if (env_ipv6)
{
free(env_ipv6);
}
#endif
// Parse transport_mode file to get switcher between shm and socket
std::string ros_etc_dir;
if (get_environment_variable(ros_etc_dir, "ROS_ETC_DIR"))
{
if(!configParse(ros_etc_dir+"/transport_mode.yaml"))
{
ROS_WARN_STREAM("Parse transport_mode file failed");
}
}
else
{
ROS_WARN_STREAM("Env variable ROS_ETC_DIR is not set");
}
param::param("/tcp_keepalive", TransportTCP::s_use_keepalive_, TransportTCP::s_use_keepalive_);
PollManager::instance()->addPollThreadListener(checkForShutdown);
XMLRPCManager::instance()->bind("shutdown", shutdownCallback);
initInternalTimerManager();
TopicManager::instance()->start();
ServiceManager::instance()->start();
ConnectionManager::instance()->start();
PollManager::instance()->start();
XMLRPCManager::instance()->start();
BroadcastManager::instance()->start();
if (!(g_init_options & init_options::NoSigintHandler))
{
signal(SIGINT, basicSigintHandler);
}
ros::Time::init();
ShmManager::instance()->start();
if (!(g_init_options & init_options::NoRosout))
{
g_rosout_appender = new ROSOutAppender;
ros::console::register_appender(g_rosout_appender);
}
if (g_shutting_down) goto end;
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::GetLoggers>(names::resolve("~get_loggers"), getLoggers);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (g_shutting_down) goto end;
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::SetLoggerLevel>(names::resolve("~set_logger_level"), setLoggerLevel);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (g_shutting_down) goto end;
if (enable_debug)
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::Empty>(names::resolve("~debug/close_all_connections"), closeAllConnections);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (g_shutting_down) goto end;
{
bool use_sim_time = false;
param::param("/use_sim_time", use_sim_time, use_sim_time);
if (use_sim_time)
{
Time::setNow(ros::Time());
}
if (g_shutting_down) goto end;
if (use_sim_time)
{
ros::SubscribeOptions ops;
ops.init<rosgraph_msgs::Clock>(names::resolve("/clock"), 1, clockCallback);
ops.callback_queue = getInternalCallbackQueue().get();
TopicManager::instance()->subscribe(ops);
}
}
if (g_shutting_down) goto end;
g_internal_queue_thread = boost::thread(internalCallbackQueueThreadFunc);
getGlobalCallbackQueue()->enable();
ROSCPP_LOG_DEBUG("Started node [%s], pid [%d], bound on [%s], xmlrpc port [%d], tcpros port [%d], using [%s] time",
this_node::getName().c_str(), getpid(), network::getHost().c_str(),
XMLRPCManager::instance()->getServerPort(), ConnectionManager::instance()->getTCPPort(),
Time::useSystemTime() ? "real" : "sim");
// Label used to abort if we've started shutting down in the middle of start(), which can happen in
// threaded code or if Ctrl-C is pressed while we're initializing
end:
// If we received a shutdown request while initializing, wait until we've shutdown to continue
if (g_shutting_down)
{
boost::recursive_mutex::scoped_lock lock(g_shutting_down_mutex);
}
}
void init(const M_string& remappings, const std::string& name, uint32_t options)
{
if (!g_atexit_registered)
{
g_atexit_registered = true;
atexit(atexitCallback);
}
if (!g_global_queue)
{
g_global_queue.reset(new CallbackQueue);
}
if (!g_initialized)
{
g_init_options = options;
g_ok = true;
ROSCONSOLE_AUTOINIT;
// Disable SIGPIPE
#ifndef WIN32
signal(SIGPIPE, SIG_IGN);
#endif
network::init(remappings);
master::init(remappings);
// names:: namespace is initialized by this_node
this_node::init(name, remappings, options);
file_log::init(remappings);
param::init(remappings);
g_initialized = true;
}
}
void init(int& argc, char** argv, const std::string& name, uint32_t options)
{
M_string remappings;
int full_argc = argc;
// now, move the remapping argv's to the end, and decrement argc as needed
for (int i = 0; i < argc; )
{
std::string arg = argv[i];
size_t pos = arg.find(":=");
if (pos != std::string::npos)
{
std::string local_name = arg.substr(0, pos);
std::string external_name = arg.substr(pos + 2);
ROSCPP_LOG_DEBUG("remap: %s => %s", local_name.c_str(), external_name.c_str());
remappings[local_name] = external_name;
// shuffle everybody down and stuff this guy at the end of argv
char *tmp = argv[i];
for (int j = i; j < full_argc - 1; j++)
argv[j] = argv[j+1];
argv[argc-1] = tmp;
argc--;
}
else
{
i++; // move on, since we didn't shuffle anybody here to replace it
}
}
init(remappings, name, options);
}
void init(const VP_string& remappings, const std::string& name, uint32_t options)
{
M_string remappings_map;
VP_string::const_iterator it = remappings.begin();
VP_string::const_iterator end = remappings.end();
for (; it != end; ++it)
{
remappings_map[it->first] = it->second;
}
init(remappings_map, name, options);
}
std::string getROSArg(int argc, const char* const* argv, const std::string& arg)
{
for (int i = 0; i < argc; ++i)
{
std::string str_arg = argv[i];
size_t pos = str_arg.find(":=");
if (str_arg.substr(0,pos) == arg)
{
return str_arg.substr(pos+2);
}
}
return "";
}
void removeROSArgs(int argc, const char* const* argv, V_string& args_out)
{
for (int i = 0; i < argc; ++i)
{
std::string arg = argv[i];
size_t pos = arg.find(":=");
if (pos == std::string::npos)
{
args_out.push_back(arg);
}
}
}
void spin()
{
SingleThreadedSpinner s;
spin(s);
}
void spin(Spinner& s)
{
s.spin();
}
void spinOnce()
{
g_global_queue->callAvailable(ros::WallDuration());
}
void waitForShutdown()
{
while (ok())
{
WallDuration(0.05).sleep();
}
}
CallbackQueue* getGlobalCallbackQueue()
{
return g_global_queue.get();
}
bool ok()
{
return g_ok;
}
void shutdown()
{
boost::recursive_mutex::scoped_lock lock(g_shutting_down_mutex);
if (g_shutting_down)
return;
else
g_shutting_down = true;
ros::console::shutdown();
g_global_queue->disable();
g_global_queue->clear();
if (g_internal_queue_thread.get_id() != boost::this_thread::get_id())
{
g_internal_queue_thread.join();
}
g_rosout_appender = 0;
if (g_started)
{
TopicManager::instance()->shutdown();
ServiceManager::instance()->shutdown();
PollManager::instance()->shutdown();
ConnectionManager::instance()->shutdown();
XMLRPCManager::instance()->shutdown();
BroadcastManager::instance()->shutdown();
if (ShmManager::instance()->isStarted())
{
ShmManager::instance()->shutdown();
}
}
WallTime end = WallTime::now();
g_started = false;
g_ok = false;
Time::shutdown();
}
bool configParse(std::string file)
{
// Exclude some topics
g_config_comm.topic_white_list.insert("/rosout");
g_config_comm.topic_white_list.insert("/rosout_agg");
g_config_comm.topic_white_list.insert("/tf");
// Parse transport_mode file
try
{
YAML::Node node = YAML::LoadFile(file);
if (node.IsNull())
{
ROS_WARN_STREAM("transport file: " << file << " is null");
return false;
}
if (!node.IsMap())
{
ROS_WARN_STREAM("transport file: " << file << " is not map");
return false;
}
if (node.size() == 0)
{
ROS_WARN_STREAM("transport file: " << file << " size is zero");
return false;
}
// For transport_mode
if (node["transport_mode"])
{
g_config_comm.transport_mode = node["transport_mode"].as<int>();
if (g_config_comm.transport_mode > 1 || g_config_comm.transport_mode < 0)
{
g_config_comm.transport_mode = 0;
}
}
else
{
ROS_WARN_STREAM("Key transport_mode doesn't exist");
}
// For topic_white_list
if (node["topic_white_list"])
{
if (node["topic_white_list"].IsSequence())
{
std::string topic;
for (int i = 0; i < node["topic_white_list"].size(); i++)
{
topic = node["topic_white_list"][i].as<std::string>();
g_config_comm.topic_white_list.insert(topic);
}
}
else
{
ROS_WARN_STREAM("Key topic_white_list is not Sequece");
}
}
else
{
ROS_WARN_STREAM("Key topic_white_list doesn't exist");
}
return true ;
} catch (YAML::Exception& e) {
ROS_WARN_STREAM("parse transport_mode file error:" << e.what());
return false;
}
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/connection.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/connection.h"
#include "ros/transport/transport.h"
#include "ros/file_log.h"
#include <ros/assert.h>
#include <boost/shared_array.hpp>
#include <boost/bind.hpp>
namespace ros
{
Connection::Connection()
: is_server_(false)
, dropped_(false)
, read_filled_(0)
, read_size_(0)
, reading_(false)
, has_read_callback_(0)
, write_sent_(0)
, write_size_(0)
, writing_(false)
, has_write_callback_(0)
, sending_header_error_(false)
{
}
Connection::~Connection()
{
ROS_DEBUG_NAMED("superdebug", "Connection destructing, dropped=%s", dropped_ ? "true" : "false");
drop(Destructing);
}
void Connection::initialize(const TransportPtr& transport, bool is_server, const HeaderReceivedFunc& header_func)
{
ROS_ASSERT(transport);
transport_ = transport;
header_func_ = header_func;
is_server_ = is_server;
transport_->setReadCallback(boost::bind(&Connection::onReadable, this, _1));
transport_->setWriteCallback(boost::bind(&Connection::onWriteable, this, _1));
transport_->setDisconnectCallback(boost::bind(&Connection::onDisconnect, this, _1));
if (header_func)
{
read(4, boost::bind(&Connection::onHeaderLengthRead, this, _1, _2, _3, _4));
}
}
boost::signals2::connection Connection::addDropListener(const DropFunc& slot)
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
return drop_signal_.connect(slot);
}
void Connection::removeDropListener(const boost::signals2::connection& c)
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
c.disconnect();
}
void Connection::onReadable(const TransportPtr& transport)
{
ROS_ASSERT(transport == transport_);
readTransport();
}
void Connection::readTransport()
{
boost::recursive_mutex::scoped_try_lock lock(read_mutex_);
if (!lock.owns_lock() || dropped_ || reading_)
{
return;
}
reading_ = true;
while (!dropped_ && has_read_callback_)
{
ROS_ASSERT(read_buffer_);
uint32_t to_read = read_size_ - read_filled_;
if (to_read > 0)
{
int32_t bytes_read = transport_->read(read_buffer_.get() + read_filled_, to_read);
ROS_DEBUG_NAMED("superdebug", "Connection read %d bytes", bytes_read);
if (dropped_)
{
return;
}
else if (bytes_read < 0)
{
// Bad read, throw away results and report error
ReadFinishedFunc callback;
callback = read_callback_;
read_callback_.clear();
read_buffer_.reset();
uint32_t size = read_size_;
read_size_ = 0;
read_filled_ = 0;
has_read_callback_ = 0;
if (callback)
{
callback(shared_from_this(), read_buffer_, size, false);
}
break;
}
read_filled_ += bytes_read;
}
ROS_ASSERT((int32_t)read_size_ >= 0);
ROS_ASSERT((int32_t)read_filled_ >= 0);
ROS_ASSERT_MSG(read_filled_ <= read_size_, "read_filled_ = %d, read_size_ = %d", read_filled_, read_size_);
if (read_filled_ == read_size_ && !dropped_)
{
ReadFinishedFunc callback;
uint32_t size;
boost::shared_array<uint8_t> buffer;
ROS_ASSERT(has_read_callback_);
// store off the read info in case another read() call is made from within the callback
callback = read_callback_;
size = read_size_;
buffer = read_buffer_;
read_callback_.clear();
read_buffer_.reset();
read_size_ = 0;
read_filled_ = 0;
has_read_callback_ = 0;
ROS_DEBUG_NAMED("superdebug", "Calling read callback");
callback(shared_from_this(), buffer, size, true);
}
else
{
break;
}
}
if (!has_read_callback_)
{
transport_->disableRead();
}
reading_ = false;
}
void Connection::writeTransport()
{
boost::recursive_mutex::scoped_try_lock lock(write_mutex_);
if (!lock.owns_lock() || dropped_ || writing_)
{
return;
}
writing_ = true;
bool can_write_more = true;
while (has_write_callback_ && can_write_more && !dropped_)
{
uint32_t to_write = write_size_ - write_sent_;
ROS_DEBUG_NAMED("superdebug", "Connection writing %d bytes", to_write);
int32_t bytes_sent = transport_->write(write_buffer_.get() + write_sent_, to_write);
ROS_DEBUG_NAMED("superdebug", "Connection wrote %d bytes", bytes_sent);
if (bytes_sent < 0)
{
writing_ = false;
return;
}
write_sent_ += bytes_sent;
if (bytes_sent < (int)write_size_ - (int)write_sent_)
{
can_write_more = false;
}
if (write_sent_ == write_size_ && !dropped_)
{
WriteFinishedFunc callback;
{
boost::mutex::scoped_lock lock(write_callback_mutex_);
ROS_ASSERT(has_write_callback_);
// Store off a copy of the callback in case another write() call happens in it
callback = write_callback_;
write_callback_ = WriteFinishedFunc();
write_buffer_ = boost::shared_array<uint8_t>();
write_sent_ = 0;
write_size_ = 0;
has_write_callback_ = 0;
}
ROS_DEBUG_NAMED("superdebug", "Calling write callback");
callback(shared_from_this());
}
}
{
boost::mutex::scoped_lock lock(write_callback_mutex_);
if (!has_write_callback_)
{
transport_->disableWrite();
}
}
writing_ = false;
}
void Connection::onWriteable(const TransportPtr& transport)
{
ROS_ASSERT(transport == transport_);
writeTransport();
}
void Connection::read(uint32_t size, const ReadFinishedFunc& callback)
{
if (dropped_ || sending_header_error_)
{
return;
}
{
boost::recursive_mutex::scoped_lock lock(read_mutex_);
ROS_ASSERT(!read_callback_);
read_callback_ = callback;
read_buffer_ = boost::shared_array<uint8_t>(new uint8_t[size]);
read_size_ = size;
read_filled_ = 0;
has_read_callback_ = 1;
}
transport_->enableRead();
// read immediately if possible
readTransport();
}
void Connection::write(const boost::shared_array<uint8_t>& buffer, uint32_t size, const WriteFinishedFunc& callback, bool immediate)
{
if (dropped_ || sending_header_error_)
{
return;
}
{
boost::mutex::scoped_lock lock(write_callback_mutex_);
ROS_ASSERT(!write_callback_);
write_callback_ = callback;
write_buffer_ = buffer;
write_size_ = size;
write_sent_ = 0;
has_write_callback_ = 1;
}
transport_->enableWrite();
if (immediate)
{
// write immediately if possible
writeTransport();
}
}
void Connection::onDisconnect(const TransportPtr& transport)
{
ROS_ASSERT(transport == transport_);
drop(TransportDisconnect);
}
void Connection::drop(DropReason reason)
{
ROSCPP_LOG_DEBUG("Connection::drop(%u)", reason);
bool did_drop = false;
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
if (!dropped_)
{
dropped_ = true;
did_drop = true;
}
}
if (did_drop)
{
drop_signal_(shared_from_this(), reason);
transport_->close();
}
}
bool Connection::isDropped()
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
return dropped_;
}
void Connection::writeHeader(const M_string& key_vals, const WriteFinishedFunc& finished_callback)
{
ROS_ASSERT(!header_written_callback_);
header_written_callback_ = finished_callback;
if (!transport_->requiresHeader())
{
onHeaderWritten(shared_from_this());
return;
}
boost::shared_array<uint8_t> buffer;
uint32_t len;
Header::write(key_vals, buffer, len);
uint32_t msg_len = len + 4;
boost::shared_array<uint8_t> full_msg(new uint8_t[msg_len]);
memcpy(full_msg.get() + 4, buffer.get(), len);
*((uint32_t*)full_msg.get()) = len;
write(full_msg, msg_len, boost::bind(&Connection::onHeaderWritten, this, _1), false);
}
void Connection::sendHeaderError(const std::string& error_msg)
{
M_string m;
m["error"] = error_msg;
writeHeader(m, boost::bind(&Connection::onErrorHeaderWritten, this, _1));
sending_header_error_ = true;
}
void Connection::onHeaderLengthRead(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
ROS_ASSERT(conn.get() == this);
ROS_ASSERT(size == 4);
if (!success)
return;
uint32_t len = *((uint32_t*)buffer.get());
if (len > 1000000000)
{
ROS_ERROR("a header of over a gigabyte was " \
"predicted in tcpros. that seems highly " \
"unlikely, so I'll assume protocol " \
"synchronization is lost.");
conn->drop(HeaderError);
}
read(len, boost::bind(&Connection::onHeaderRead, this, _1, _2, _3, _4));
}
void Connection::onHeaderRead(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
ROS_ASSERT(conn.get() == this);
if (!success)
return;
std::string error_msg;
if (!header_.parse(buffer, size, error_msg))
{
drop(HeaderError);
}
else
{
std::string error_val;
if (header_.getValue("error", error_val))
{
ROSCPP_LOG_DEBUG("Received error message in header for connection to [%s]: [%s]", transport_->getTransportInfo().c_str(), error_val.c_str());
drop(HeaderError);
}
else
{
ROS_ASSERT(header_func_);
transport_->parseHeader(header_);
header_func_(conn, header_);
}
}
}
void Connection::onHeaderWritten(const ConnectionPtr& conn)
{
ROS_ASSERT(conn.get() == this);
ROS_ASSERT(header_written_callback_);
header_written_callback_(conn);
header_written_callback_ = WriteFinishedFunc();
}
void Connection::onErrorHeaderWritten(const ConnectionPtr& conn)
{
(void)conn;
drop(HeaderError);
}
void Connection::setHeaderReceivedCallback(const HeaderReceivedFunc& func)
{
header_func_ = func;
if (transport_->requiresHeader())
read(4, boost::bind(&Connection::onHeaderLengthRead, this, _1, _2, _3, _4));
}
std::string Connection::getCallerId()
{
std::string callerid;
if (header_.getValue("callerid", callerid))
{
return callerid;
}
return std::string("unknown");
}
std::string Connection::getRemoteString()
{
std::stringstream ss;
ss << "callerid=[" << getCallerId() << "] address=[" << transport_->getTransportInfo() << "]";
return ss.str();
}
std::string Connection::getRemoteIp()
{
std::stringstream ss;
ss << transport_->getClientURI();
return ss.str();
}
std::string Connection::getLocalIp()
{
std::stringstream ss;
ss << transport_->getLocalIp();
return ss.str();
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/subscription.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <typeinfo>
#include <cstdlib>
#include "ros/common.h"
#include "ros/io.h"
#include "ros/subscription.h"
#include "ros/publication.h"
#include "ros/transport_publisher_link.h"
#include "ros/intraprocess_publisher_link.h"
#include "ros/intraprocess_subscriber_link.h"
#include "ros/connection.h"
#include "ros/transport/transport_tcp.h"
#include "ros/transport/transport_udp.h"
#include "ros/callback_queue_interface.h"
#include "ros/this_node.h"
#include "ros/network.h"
#include "ros/poll_manager.h"
#include "ros/connection_manager.h"
#include "ros/message_deserializer.h"
#include "ros/subscription_queue.h"
#include "ros/file_log.h"
#include "ros/transport_hints.h"
#include "ros/subscription_callback_helper.h"
#include <boost/make_shared.hpp>
#include "ros/param.h"
using XmlRpc::XmlRpcValue;
namespace ros
{
Subscription::Subscription(const std::string &name, const std::string& md5sum,
const std::string& datatype, const TransportHints& transport_hints)
: name_(name),
md5sum_(md5sum),
datatype_(datatype),
nonconst_callbacks_(0),
dropped_(false),
shutting_down_(false),
transport_hints_(transport_hints),
default_transport_(true),
self_subscribed_(false),
last_read_index_(-1)
{
}
Subscription::~Subscription()
{
pending_connections_.clear();
callbacks_.clear();
}
void Subscription::shutdown()
{
{
boost::mutex::scoped_lock lock(shutdown_mutex_);
shutting_down_ = true;
}
drop();
}
XmlRpcValue Subscription::getStats()
{
XmlRpcValue stats;
stats[0] = name_;
XmlRpcValue conn_data;
conn_data.setSize(0);
boost::mutex::scoped_lock lock(publisher_links_mutex_);
uint32_t cidx = 0;
for (V_PublisherLink::iterator c = publisher_links_.begin();
c != publisher_links_.end(); ++c)
{
const PublisherLink::Stats& s = (*c)->getStats();
conn_data[cidx][0] = (*c)->getConnectionID();
conn_data[cidx][1] = (int)s.bytes_received_;
conn_data[cidx][2] = (int)s.messages_received_;
conn_data[cidx][3] = (int)s.drops_;
conn_data[cidx][4] = 0; // figure out something for this. not sure.
}
stats[1] = conn_data;
return stats;
}
// [(connection_id, publisher_xmlrpc_uri, direction, transport, topic_name, connected, connection_info_string)*]
// e.g. [(1, 'http://host:54893/', 'i', 'TCPROS', '/chatter', 1, 'TCPROS connection on port 59746 to [host:34318 on socket 11]')]
void Subscription::getInfo(XmlRpc::XmlRpcValue& info)
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
for (V_PublisherLink::iterator c = publisher_links_.begin();
c != publisher_links_.end(); ++c)
{
XmlRpcValue curr_info;
curr_info[0] = (int)(*c)->getConnectionID();
curr_info[1] = (*c)->getPublisherXMLRPCURI();
curr_info[2] = "i";
curr_info[3] = (*c)->getTransportType();
curr_info[4] = name_;
curr_info[5] = true; // For length compatibility with rospy
curr_info[6] = (*c)->getTransportInfo();
info[info.size()] = curr_info;
}
}
uint32_t Subscription::getNumPublishers()
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
return (uint32_t)publisher_links_.size();
}
void Subscription::drop()
{
if (!dropped_)
{
dropped_ = true;
dropAllConnections();
}
}
void Subscription::dropAllConnections()
{
// Swap our subscribers list with a local one so we can only lock for a short period of time, because a
// side effect of our calling drop() on connections can be re-locking the subscribers mutex
V_PublisherLink localsubscribers;
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
localsubscribers.swap(publisher_links_);
}
V_PublisherLink::iterator it = localsubscribers.begin();
V_PublisherLink::iterator end = localsubscribers.end();
for (;it != end; ++it)
{
(*it)->drop();
}
}
void Subscription::addLocalConnection(const PublicationPtr& pub)
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
if (dropped_)
{
return;
}
ROSCPP_LOG_DEBUG("Creating intraprocess link for topic [%s]", name_.c_str());
IntraProcessPublisherLinkPtr pub_link(boost::make_shared<IntraProcessPublisherLink>(shared_from_this(),
XMLRPCManager::instance()->getServerURI(), transport_hints_));
IntraProcessSubscriberLinkPtr sub_link(boost::make_shared<IntraProcessSubscriberLink>(pub));
pub_link->setPublisher(sub_link);
sub_link->setSubscriber(pub_link);
addPublisherLink(pub_link);
pub->addSubscriberLink(sub_link);
}
bool urisEqual(const std::string& uri1, const std::string& uri2)
{
std::string host1, host2;
uint32_t port1 = 0, port2 = 0;
network::splitURI(uri1, host1, port1);
network::splitURI(uri2, host2, port2);
return port1 == port2 && host1 == host2;
}
bool Subscription::getSelfSubscribed()
{
return self_subscribed_;
}
void Subscription::setSelfSubscribed(bool self_subscribed)
{
self_subscribed_ = self_subscribed;
}
bool Subscription::pubUpdate(const V_string& new_pubs)
{
boost::mutex::scoped_lock lock(shutdown_mutex_);
if (shutting_down_ || dropped_)
{
return false;
}
bool retval = true;
{
std::stringstream ss;
for (V_string::const_iterator up_i = new_pubs.begin();
up_i != new_pubs.end(); ++up_i)
{
ss << *up_i << ", ";
}
ss << " already have these connections: ";
for (V_PublisherLink::iterator spc = publisher_links_.begin();
spc!= publisher_links_.end(); ++spc)
{
ss << (*spc)->getPublisherXMLRPCURI() << ", ";
}
boost::mutex::scoped_lock lock(pending_connections_mutex_);
S_PendingConnection::iterator it = pending_connections_.begin();
S_PendingConnection::iterator end = pending_connections_.end();
for (; it != end; ++it)
{
ss << (*it)->getRemoteURI() << ", ";
}
ROSCPP_LOG_DEBUG("Publisher update for [%s]: %s", name_.c_str(), ss.str().c_str());
}
V_string additions;
V_PublisherLink subtractions;
V_PublisherLink to_add;
// could use the STL set operations... but these sets are so small
// it doesn't really matter.
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
for (V_PublisherLink::iterator spc = publisher_links_.begin();
spc!= publisher_links_.end(); ++spc)
{
bool found = false;
for (V_string::const_iterator up_i = new_pubs.begin();
!found && up_i != new_pubs.end(); ++up_i)
{
if (urisEqual((*spc)->getPublisherXMLRPCURI(), *up_i))
{
found = true;
break;
}
}
if (!found)
{
subtractions.push_back(*spc);
}
}
for (V_string::const_iterator up_i = new_pubs.begin(); up_i != new_pubs.end(); ++up_i)
{
bool found = false;
for (V_PublisherLink::iterator spc = publisher_links_.begin();
!found && spc != publisher_links_.end(); ++spc)
{
if (urisEqual(*up_i, (*spc)->getPublisherXMLRPCURI()))
{
found = true;
break;
}
}
if (!found)
{
boost::mutex::scoped_lock lock(pending_connections_mutex_);
S_PendingConnection::iterator it = pending_connections_.begin();
S_PendingConnection::iterator end = pending_connections_.end();
for (; it != end; ++it)
{
if (urisEqual(*up_i, (*it)->getRemoteURI()))
{
found = true;
break;
}
}
}
if (!found)
{
additions.push_back(*up_i);
}
}
}
for (V_PublisherLink::iterator i = subtractions.begin(); i != subtractions.end(); ++i)
{
const PublisherLinkPtr& link = *i;
if (link->getPublisherXMLRPCURI() != XMLRPCManager::instance()->getServerURI())
{
ROSCPP_LOG_DEBUG("Disconnecting from publisher [%s] of topic [%s] at [%s]",
link->getCallerID().c_str(), name_.c_str(), link->getPublisherXMLRPCURI().c_str());
link->drop();
}
else
{
ROSCPP_LOG_DEBUG("Disconnect: skipping myself for topic [%s]", name_.c_str());
}
}
for (V_string::iterator i = additions.begin();
i != additions.end(); ++i)
{
// this function should never negotiate a self-subscription
if (XMLRPCManager::instance()->getServerURI() != *i)
{
retval &= negotiateConnection(*i);
}
else
{
ROSCPP_LOG_DEBUG("Skipping myself (%s, %s)", name_.c_str(), XMLRPCManager::instance()->getServerURI().c_str());
}
}
return retval;
}
bool Subscription::negotiateConnection(const std::string& xmlrpc_uri)
{
XmlRpcValue tcpros_array, protos_array, params;
XmlRpcValue udpros_array;
TransportUDPPtr udp_transport;
int protos = 0;
V_string transports = transport_hints_.getTransports();
if (transports.empty())
{
transport_hints_.reliable();
transports = transport_hints_.getTransports();
}
for (V_string::const_iterator it = transports.begin();
it != transports.end();
++it)
{
if (*it == "UDP")
{
int max_datagram_size = transport_hints_.getMaxDatagramSize();
udp_transport = boost::make_shared<TransportUDP>(&PollManager::instance()->getPollSet());
if (!max_datagram_size)
max_datagram_size = udp_transport->getMaxDatagramSize();
udp_transport->createIncoming(0, false);
udpros_array[0] = "UDPROS";
M_string m;
m["topic"] = getName();
m["md5sum"] = md5sum();
m["callerid"] = this_node::getName();
m["type"] = datatype();
boost::shared_array<uint8_t> buffer;
uint32_t len;
Header::write(m, buffer, len);
XmlRpcValue v(buffer.get(), len);
udpros_array[1] = v;
udpros_array[2] = network::getHost();
udpros_array[3] = udp_transport->getServerPort();
udpros_array[4] = max_datagram_size;
protos_array[protos++] = udpros_array;
}
else if (*it == "TCP")
{
tcpros_array[0] = std::string("TCPROS");
protos_array[protos++] = tcpros_array;
}
else
{
ROS_WARN("Unsupported transport type hinted: %s, skipping", it->c_str());
}
}
params[0] = this_node::getName();
params[1] = name_;
params[2] = protos_array;
std::string peer_host;
uint32_t peer_port;
if (!network::splitURI(xmlrpc_uri, peer_host, peer_port))
{
ROS_ERROR("Bad xml-rpc URI: [%s]", xmlrpc_uri.c_str());
return false;
}
XmlRpc::XmlRpcClient* c = new XmlRpc::XmlRpcClient(peer_host.c_str(),
peer_port, "/");
// if (!c.execute("requestTopic", params, result) || !g_node->validateXmlrpcResponse("requestTopic", result, proto))
// Initiate the negotiation. We'll come back and check on it later.
if (!c->executeNonBlock("requestTopic", params))
{
ROSCPP_LOG_DEBUG("Failed to contact publisher [%s:%d] for topic [%s]",
peer_host.c_str(), peer_port, name_.c_str());
delete c;
if (udp_transport)
{
udp_transport->close();
}
return false;
}
ROSCPP_LOG_DEBUG("Began asynchronous xmlrpc connection to [%s:%d]", peer_host.c_str(), peer_port);
// The PendingConnectionPtr takes ownership of c, and will delete it on
// destruction.
PendingConnectionPtr conn(boost::make_shared<PendingConnection>(c, udp_transport, shared_from_this(), xmlrpc_uri));
XMLRPCManager::instance()->addASyncConnection(conn);
// Put this connection on the list that we'll look at later.
{
boost::mutex::scoped_lock pending_connections_lock(pending_connections_mutex_);
pending_connections_.insert(conn);
}
return true;
}
void closeTransport(const TransportUDPPtr& trans)
{
if (trans)
{
trans->close();
}
}
void Subscription::pendingConnectionDone(const PendingConnectionPtr& conn, XmlRpcValue& result)
{
boost::mutex::scoped_lock lock(shutdown_mutex_);
if (shutting_down_ || dropped_)
{
return;
}
{
boost::mutex::scoped_lock pending_connections_lock(pending_connections_mutex_);
pending_connections_.erase(conn);
}
TransportUDPPtr udp_transport;
std::string peer_host = conn->getClient()->getHost();
uint32_t peer_port = conn->getClient()->getPort();
std::stringstream ss;
ss << "http://" << peer_host << ":" << peer_port << "/";
std::string xmlrpc_uri = ss.str();
udp_transport = conn->getUDPTransport();
XmlRpc::XmlRpcValue proto;
if (!XMLRPCManager::instance()->validateXmlrpcResponse("requestTopic", result, proto))
{
ROSCPP_LOG_DEBUG("Failed to contact publisher [%s:%d] for topic [%s]",
peer_host.c_str(), peer_port, name_.c_str());
closeTransport(udp_transport);
return;
}
if (proto.size() == 0)
{
ROSCPP_LOG_DEBUG("Couldn't agree on any common protocols with [%s] for topic [%s]", xmlrpc_uri.c_str(), name_.c_str());
closeTransport(udp_transport);
return;
}
if (proto.getType() != XmlRpcValue::TypeArray)
{
ROSCPP_LOG_DEBUG("Available protocol info returned from %s is not a list.", xmlrpc_uri.c_str());
closeTransport(udp_transport);
return;
}
if (proto[0].getType() != XmlRpcValue::TypeString)
{
ROSCPP_LOG_DEBUG("Available protocol info list doesn't have a string as its first element.");
closeTransport(udp_transport);
return;
}
std::string proto_name = proto[0];
if (proto_name == "TCPROS")
{
if (proto.size() != 3 ||
proto[1].getType() != XmlRpcValue::TypeString ||
proto[2].getType() != XmlRpcValue::TypeInt)
{
ROSCPP_LOG_DEBUG("publisher implements TCPROS, but the " \
"parameters aren't string,int");
return;
}
std::string pub_host = proto[1];
int pub_port = proto[2];
ROSCPP_LOG_DEBUG("Connecting via tcpros to topic [%s] at host [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port);
TransportTCPPtr transport(boost::make_shared<TransportTCP>(&PollManager::instance()->getPollSet()));
if (transport->connect(pub_host, pub_port))
{
ConnectionPtr connection(boost::make_shared<Connection>());
TransportPublisherLinkPtr pub_link(boost::make_shared<TransportPublisherLink>(shared_from_this(), xmlrpc_uri, transport_hints_));
connection->initialize(transport, false, HeaderReceivedFunc());
pub_link->initialize(connection);
ConnectionManager::instance()->addConnection(connection);
boost::mutex::scoped_lock lock(publisher_links_mutex_);
addPublisherLink(pub_link);
ROSCPP_LOG_DEBUG("Connected to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port);
}
else
{
ROSCPP_LOG_DEBUG("Failed to connect to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port);
}
}
else if (proto_name == "UDPROS")
{
if (proto.size() != 6 ||
proto[1].getType() != XmlRpcValue::TypeString ||
proto[2].getType() != XmlRpcValue::TypeInt ||
proto[3].getType() != XmlRpcValue::TypeInt ||
proto[4].getType() != XmlRpcValue::TypeInt ||
proto[5].getType() != XmlRpcValue::TypeBase64)
{
ROSCPP_LOG_DEBUG("publisher implements UDPROS, but the " \
"parameters aren't string,int,int,int,base64");
closeTransport(udp_transport);
return;
}
std::string pub_host = proto[1];
int pub_port = proto[2];
int conn_id = proto[3];
int max_datagram_size = proto[4];
std::vector<char> header_bytes = proto[5];
boost::shared_array<uint8_t> buffer(new uint8_t[header_bytes.size()]);
memcpy(buffer.get(), &header_bytes[0], header_bytes.size());
Header h;
std::string err;
if (!h.parse(buffer, header_bytes.size(), err))
{
ROSCPP_LOG_DEBUG("Unable to parse UDPROS connection header: %s", err.c_str());
closeTransport(udp_transport);
return;
}
ROSCPP_LOG_DEBUG("Connecting via udpros to topic [%s] at host [%s:%d] connection id [%08x] max_datagram_size [%d]",
name_.c_str(), pub_host.c_str(), pub_port, conn_id, max_datagram_size);
std::string error_msg;
if (h.getValue("error", error_msg))
{
ROSCPP_LOG_DEBUG("Received error message in header for connection to [%s]: [%s]", xmlrpc_uri.c_str(), error_msg.c_str());
closeTransport(udp_transport);
return;
}
TransportPublisherLinkPtr pub_link(boost::make_shared<TransportPublisherLink>(shared_from_this(), xmlrpc_uri, transport_hints_));
if (pub_link->setHeader(h))
{
ConnectionPtr connection(boost::make_shared<Connection>());
connection->initialize(udp_transport, false, NULL);
connection->setHeader(h);
pub_link->initialize(connection);
ConnectionManager::instance()->addConnection(connection);
boost::mutex::scoped_lock lock(publisher_links_mutex_);
addPublisherLink(pub_link);
ROSCPP_LOG_DEBUG("Connected to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port);
}
else
{
ROSCPP_LOG_DEBUG("Failed to connect to publisher of topic [%s] at [%s:%d]", name_.c_str(), pub_host.c_str(), pub_port);
closeTransport(udp_transport);
return;
}
}
else
{
ROSCPP_LOG_DEBUG("Publisher offered unsupported transport [%s]", proto_name.c_str());
}
}
uint32_t Subscription::handleMessage(const SerializedMessage& m, bool ser, bool nocopy,
const boost::shared_ptr<M_string>& connection_header, const PublisherLinkPtr& link)
{
boost::mutex::scoped_lock lock(callbacks_mutex_);
uint32_t drops = 0;
// Cache the deserializers by type info. If all the subscriptions are the same
// type this has the same performance as before. If
// there are subscriptions with different C++ type (but same ROS message type),
// this now works correctly rather than passing
// garbage to the messages with different C++ types than the first one.
cached_deserializers_.clear();
ros::Time receipt_time = ros::Time::now();
for (V_CallbackInfo::iterator cb = callbacks_.begin(); cb != callbacks_.end(); ++cb)
{
const CallbackInfoPtr& info = *cb;
ROS_ASSERT(info->callback_queue_);
const std::type_info* ti = &info->helper_->getTypeInfo();
if ((nocopy && m.type_info && *ti == *m.type_info) || (ser && (!m.type_info || *ti != *m.type_info)))
{
MessageDeserializerPtr deserializer;
V_TypeAndDeserializer::iterator des_it = cached_deserializers_.begin();
V_TypeAndDeserializer::iterator des_end = cached_deserializers_.end();
for (; des_it != des_end; ++des_it)
{
if (*des_it->first == *ti)
{
deserializer = des_it->second;
break;
}
}
if (!deserializer)
{
deserializer = boost::make_shared<MessageDeserializer>(info->helper_, m, connection_header);
cached_deserializers_.push_back(std::make_pair(ti, deserializer));
}
bool was_full = false;
bool nonconst_need_copy = false;
if (callbacks_.size() > 1)
{
nonconst_need_copy = true;
}
info->subscription_queue_->push(false, info->helper_, deserializer,
info->has_tracked_object_, info->tracked_object_,
nonconst_need_copy, receipt_time, &was_full);
if (was_full)
{
++drops;
}
else
{
info->callback_queue_->addCallback(info->subscription_queue_, (uint64_t)info.get());
}
}
}
if (name_ == "/rosout" || name_ == "/rosout_agg" || name_ == "/tf")
{
if (link)
{
// measure statistics
statistics_.callback(connection_header, name_, link->getCallerID(),
m, link->getStats().bytes_received_, receipt_time, drops > 0);
// If this link is latched, store off the message so we can immediately
// pass it to new subscribers later
if (link->isLatched())
{
LatchInfo li;
li.connection_header = connection_header;
li.link = link;
li.message = m;
li.receipt_time = receipt_time;
latched_messages_[link] = li;
}
}
}
else
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
for (V_PublisherLink::iterator it = publisher_links_.begin(); it != publisher_links_.end(); ++it)
{
if ((*it)->isLatched())
{
LatchInfo li;
li.connection_header = connection_header;
li.link = (*it);
li.message = m;
li.receipt_time = receipt_time;
latched_messages_[(*it)] = li;
}
}
}
cached_deserializers_.clear();
return drops;
}
bool Subscription::addCallback(const SubscriptionCallbackHelperPtr& helper, const std::string& md5sum,
CallbackQueueInterface* queue, int32_t queue_size, const VoidConstPtr& tracked_object, bool allow_concurrent_callbacks)
{
ROS_ASSERT(helper);
ROS_ASSERT(queue);
statistics_.init(helper);
helper_ = helper;
// Decay to a real type as soon as we have a subscriber with a real type
{
boost::mutex::scoped_lock lock(md5sum_mutex_);
if (md5sum_ == "*" && md5sum != "*")
{
md5sum_ = md5sum;
}
}
if (md5sum != "*" && md5sum != this->md5sum())
{
return false;
}
{
boost::mutex::scoped_lock lock(callbacks_mutex_);
CallbackInfoPtr info(boost::make_shared<CallbackInfo>());
info->helper_ = helper;
info->callback_queue_ = queue;
info->subscription_queue_ = boost::make_shared<SubscriptionQueue>(name_, queue_size, allow_concurrent_callbacks);
info->tracked_object_ = tracked_object;
info->has_tracked_object_ = false;
if (tracked_object)
{
info->has_tracked_object_ = true;
}
if (!helper->isConst())
{
++nonconst_callbacks_;
}
callbacks_.push_back(info);
cached_deserializers_.reserve(callbacks_.size());
// if we have any latched links, we need to immediately schedule callbacks
if (!latched_messages_.empty())
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
V_PublisherLink::iterator it = publisher_links_.begin();
V_PublisherLink::iterator end = publisher_links_.end();
for (; it != end;++it)
{
const PublisherLinkPtr& link = *it;
if (link->isLatched())
{
M_PublisherLinkToLatchInfo::iterator des_it = latched_messages_.find(link);
if (des_it != latched_messages_.end())
{
const LatchInfo& latch_info = des_it->second;
MessageDeserializerPtr des(boost::make_shared<MessageDeserializer>(helper,
latch_info.message, latch_info.connection_header));
bool was_full = false;
info->subscription_queue_->push(default_transport_, info->helper_, des, info->has_tracked_object_,
info->tracked_object_, true, latch_info.receipt_time, &was_full);
if (!was_full)
{
info->callback_queue_->addCallback(info->subscription_queue_, (uint64_t)info.get());
}
}
}
}
}
}
return true;
}
void Subscription::removeCallback(const SubscriptionCallbackHelperPtr& helper)
{
CallbackInfoPtr info;
{
boost::mutex::scoped_lock cbs_lock(callbacks_mutex_);
for (V_CallbackInfo::iterator it = callbacks_.begin();
it != callbacks_.end(); ++it)
{
if ((*it)->helper_ == helper)
{
info = *it;
callbacks_.erase(it);
if (!helper->isConst())
{
--nonconst_callbacks_;
}
break;
}
}
}
if (info)
{
info->subscription_queue_->clear();
info->callback_queue_->removeByID((uint64_t)info.get());
}
}
void Subscription::headerReceived(const PublisherLinkPtr& link, const Header& h)
{
(void)h;
boost::mutex::scoped_lock lock(md5sum_mutex_);
if (md5sum_ == "*")
{
md5sum_ = link->getMD5Sum();
}
}
void Subscription::addPublisherLink(const PublisherLinkPtr& link)
{
publisher_links_.push_back(link);
}
void Subscription::removePublisherLink(const PublisherLinkPtr& pub_link)
{
boost::mutex::scoped_lock lock(publisher_links_mutex_);
V_PublisherLink::iterator it = std::find(publisher_links_.begin(), publisher_links_.end(), pub_link);
if (it != publisher_links_.end())
{
publisher_links_.erase(it);
}
if (pub_link->isLatched())
{
latched_messages_.erase(pub_link);
}
}
void Subscription::getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti)
{
boost::mutex::scoped_lock lock(callbacks_mutex_);
for (V_CallbackInfo::iterator cb = callbacks_.begin();
cb != callbacks_.end(); ++cb)
{
const CallbackInfoPtr& info = *cb;
if (info->helper_->getTypeInfo() == ti)
{
nocopy = true;
}
else
{
ser = true;
}
if (nocopy && ser)
{
return;
}
}
}
const std::string Subscription::datatype()
{
return datatype_;
}
const std::string Subscription::md5sum()
{
boost::mutex::scoped_lock lock(md5sum_mutex_);
return md5sum_;
}
void Subscription::setLastIndex(int last_read_index)
{
last_read_index_ = last_read_index;
}
int Subscription::getLastIndex()
{
return last_read_index_;
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service_client_link.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/service_client_link.h"
#include "ros/service_publication.h"
#include "ros/header.h"
#include "ros/connection.h"
#include "ros/service_manager.h"
#include "ros/transport/transport.h"
#include "ros/this_node.h"
#include "ros/file_log.h"
#include <boost/bind.hpp>
namespace ros
{
ServiceClientLink::ServiceClientLink()
: persistent_(false)
{
}
ServiceClientLink::~ServiceClientLink()
{
if (connection_)
{
if (connection_->isSendingHeaderError())
{
connection_->removeDropListener(dropped_conn_);
}
else
{
connection_->drop(Connection::Destructing);
}
}
}
bool ServiceClientLink::initialize(const ConnectionPtr& connection)
{
connection_ = connection;
dropped_conn_ = connection_->addDropListener(boost::bind(&ServiceClientLink::onConnectionDropped, this, _1));
return true;
}
bool ServiceClientLink::handleHeader(const Header& header)
{
std::string md5sum, service, client_callerid;
if (!header.getValue("md5sum", md5sum)
|| !header.getValue("service", service)
|| !header.getValue("callerid", client_callerid))
{
std::string msg("bogus tcpros header. did not have the "
"required elements: md5sum, service, callerid");
ROS_ERROR("%s", msg.c_str());
connection_->sendHeaderError(msg);
return false;
}
std::string persistent;
if (header.getValue("persistent", persistent))
{
if (persistent == "1" || persistent == "true")
{
persistent_ = true;
}
}
ROSCPP_LOG_DEBUG("Service client [%s] wants service [%s] with md5sum [%s]", client_callerid.c_str(), service.c_str(), md5sum.c_str());
ServicePublicationPtr ss = ServiceManager::instance()->lookupServicePublication(service);
if (!ss)
{
std::string msg = std::string("received a tcpros connection for a "
"nonexistent service [") +
service + std::string("].");
ROS_ERROR("%s", msg.c_str());
connection_->sendHeaderError(msg);
return false;
}
if (ss->getMD5Sum() != md5sum &&
(md5sum != std::string("*") && ss->getMD5Sum() != std::string("*")))
{
std::string msg = std::string("client wants service ") + service +
std::string(" to have md5sum ") + md5sum +
std::string(", but it has ") + ss->getMD5Sum() +
std::string(". Dropping connection.");
ROS_ERROR("%s", msg.c_str());
connection_->sendHeaderError(msg);
return false;
}
// Check whether the service (ss here) has been deleted from
// advertised_topics through a call to unadvertise(), which could
// have happened while we were waiting for the subscriber to
// provide the md5sum.
if(ss->isDropped())
{
std::string msg = std::string("received a tcpros connection for a "
"nonexistent service [") +
service + std::string("].");
ROS_ERROR("%s", msg.c_str());
connection_->sendHeaderError(msg);
return false;
}
else
{
parent_ = ServicePublicationWPtr(ss);
// Send back a success, with info
M_string m;
m["request_type"] = ss->getRequestDataType();
m["response_type"] = ss->getResponseDataType();
m["type"] = ss->getDataType();
m["md5sum"] = ss->getMD5Sum();
m["callerid"] = this_node::getName();
connection_->writeHeader(m, boost::bind(&ServiceClientLink::onHeaderWritten, this, _1));
ss->addServiceClientLink(shared_from_this());
}
return true;
}
void ServiceClientLink::onConnectionDropped(const ConnectionPtr& conn)
{
ROS_ASSERT(conn == connection_);
if (ServicePublicationPtr parent = parent_.lock())
{
parent->removeServiceClientLink(shared_from_this());
}
}
void ServiceClientLink::onHeaderWritten(const ConnectionPtr& conn)
{
(void)conn;
connection_->read(4, boost::bind(&ServiceClientLink::onRequestLength, this, _1, _2, _3, _4));
}
void ServiceClientLink::onRequestLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
if (!success)
return;
ROS_ASSERT(conn == connection_);
ROS_ASSERT(size == 4);
uint32_t len = *((uint32_t*)buffer.get());
if (len > 1000000000)
{
ROS_ERROR("a message of over a gigabyte was " \
"predicted in tcpros. that seems highly " \
"unlikely, so I'll assume protocol " \
"synchronization is lost.");
conn->drop(Connection::Destructing);
return;
}
connection_->read(len, boost::bind(&ServiceClientLink::onRequest, this, _1, _2, _3, _4));
}
void ServiceClientLink::onRequest(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
if (!success)
return;
ROS_ASSERT(conn == connection_);
if (ServicePublicationPtr parent = parent_.lock())
{
parent->processRequest(buffer, size, shared_from_this());
}
else
{
ROS_BREAK();
}
}
void ServiceClientLink::onResponseWritten(const ConnectionPtr& conn)
{
ROS_ASSERT(conn == connection_);
if (persistent_)
{
connection_->read(4, boost::bind(&ServiceClientLink::onRequestLength, this, _1, _2, _3, _4));
}
else
{
connection_->drop(Connection::Destructing);
}
}
void ServiceClientLink::processResponse(bool ok, const SerializedMessage& res)
{
(void)ok;
connection_->write(res.buf, res.num_bytes, boost::bind(&ServiceClientLink::onResponseWritten, this, _1));
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/publisher_link.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/publisher_link.h"
#include "ros/subscription.h"
#include "ros/header.h"
#include "ros/connection.h"
#include "ros/transport/transport.h"
#include "ros/this_node.h"
#include "ros/connection_manager.h"
#include "ros/file_log.h"
#include <boost/bind.hpp>
#include <sstream>
namespace ros
{
PublisherLink::PublisherLink(const SubscriptionPtr& parent, const std::string& xmlrpc_uri,
const TransportHints& transport_hints)
: parent_(parent)
, connection_id_(0)
, publisher_xmlrpc_uri_(xmlrpc_uri)
, transport_hints_(transport_hints)
, latched_(false)
{ }
PublisherLink::~PublisherLink()
{ }
bool PublisherLink::setHeader(const Header& header)
{
header.getValue("callerid", caller_id_);
std::string md5sum, type, latched_str;
if (!header.getValue("md5sum", md5sum))
{
ROS_ERROR("Publisher header did not have required element: md5sum");
return false;
}
md5sum_ = md5sum;
if (!header.getValue("type", type))
{
ROS_ERROR("Publisher header did not have required element: type");
return false;
}
latched_ = false;
if (header.getValue("latching", latched_str))
{
if (latched_str == "1")
{
latched_ = true;
}
}
connection_id_ = ConnectionManager::instance()->getNewConnectionID();
header_ = header;
if (SubscriptionPtr parent = parent_.lock())
{
parent->headerReceived(shared_from_this(), header);
}
return true;
}
const std::string& PublisherLink::getPublisherXMLRPCURI()
{
return publisher_xmlrpc_uri_;
}
const std::string& PublisherLink::getMD5Sum()
{
ROS_ASSERT(!md5sum_.empty());
return md5sum_;
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/connection_manager.cpp | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/connection_manager.h"
#include "ros/poll_manager.h"
#include "ros/connection.h"
#include "ros/transport_subscriber_link.h"
#include "ros/service_client_link.h"
#include "ros/transport/transport_tcp.h"
#include "ros/transport/transport_udp.h"
#include "ros/file_log.h"
#include "ros/network.h"
#include <ros/assert.h>
namespace ros
{
ConnectionManagerPtr g_connection_manager;
boost::mutex g_connection_manager_mutex;
const ConnectionManagerPtr& ConnectionManager::instance()
{
if (!g_connection_manager)
{
boost::mutex::scoped_lock lock(g_connection_manager_mutex);
if (!g_connection_manager)
{
g_connection_manager = boost::make_shared<ConnectionManager>();
}
}
return g_connection_manager;
}
ConnectionManager::ConnectionManager()
: connection_id_counter_(0)
{
}
ConnectionManager::~ConnectionManager()
{
shutdown();
}
void ConnectionManager::start()
{
poll_manager_ = PollManager::instance();
poll_conn_ = poll_manager_->addPollThreadListener(boost::bind(&ConnectionManager::removeDroppedConnections,
this));
// Bring up the TCP listener socket
tcpserver_transport_ = boost::make_shared<TransportTCP>(&poll_manager_->getPollSet());
if (!tcpserver_transport_->listen(network::getTCPROSPort(),
MAX_TCPROS_CONN_QUEUE,
boost::bind(&ConnectionManager::tcprosAcceptConnection, this, _1)))
{
ROS_FATAL("Listen on port [%d] failed", network::getTCPROSPort());
ROS_BREAK();
}
// Bring up the UDP listener socket
udpserver_transport_ = boost::make_shared<TransportUDP>(&poll_manager_->getPollSet());
if (!udpserver_transport_->createIncoming(0, true))
{
ROS_FATAL("Listen failed");
ROS_BREAK();
}
}
void ConnectionManager::shutdown()
{
if (udpserver_transport_)
{
udpserver_transport_->close();
udpserver_transport_.reset();
}
if (tcpserver_transport_)
{
tcpserver_transport_->close();
tcpserver_transport_.reset();
}
poll_manager_->removePollThreadListener(poll_conn_);
clear(Connection::Destructing);
}
void ConnectionManager::clear(Connection::DropReason reason)
{
S_Connection local_connections;
{
boost::mutex::scoped_lock conn_lock(connections_mutex_);
local_connections.swap(connections_);
}
for(S_Connection::iterator itr = local_connections.begin();
itr != local_connections.end();
itr++)
{
const ConnectionPtr& conn = *itr;
conn->drop(reason);
}
boost::mutex::scoped_lock dropped_lock(dropped_connections_mutex_);
dropped_connections_.clear();
}
uint32_t ConnectionManager::getTCPPort()
{
return tcpserver_transport_->getServerPort();
}
uint32_t ConnectionManager::getUDPPort()
{
return udpserver_transport_->getServerPort();
}
uint32_t ConnectionManager::getNewConnectionID()
{
boost::mutex::scoped_lock lock(connection_id_counter_mutex_);
uint32_t ret = connection_id_counter_++;
return ret;
}
void ConnectionManager::addConnection(const ConnectionPtr& conn)
{
boost::mutex::scoped_lock lock(connections_mutex_);
connections_.insert(conn);
conn->addDropListener(boost::bind(&ConnectionManager::onConnectionDropped, this, _1));
}
void ConnectionManager::onConnectionDropped(const ConnectionPtr& conn)
{
boost::mutex::scoped_lock lock(dropped_connections_mutex_);
dropped_connections_.push_back(conn);
}
void ConnectionManager::removeDroppedConnections()
{
V_Connection local_dropped;
{
boost::mutex::scoped_lock dropped_lock(dropped_connections_mutex_);
dropped_connections_.swap(local_dropped);
}
boost::mutex::scoped_lock conn_lock(connections_mutex_);
V_Connection::iterator conn_it = local_dropped.begin();
V_Connection::iterator conn_end = local_dropped.end();
for (;conn_it != conn_end; ++conn_it)
{
const ConnectionPtr& conn = *conn_it;
connections_.erase(conn);
}
}
void ConnectionManager::udprosIncomingConnection(const TransportUDPPtr& transport, Header& header)
{
std::string client_uri = ""; // TODO: transport->getClientURI();
ROSCPP_LOG_DEBUG("UDPROS received a connection from [%s]", client_uri.c_str());
ConnectionPtr conn(boost::make_shared<Connection>());
addConnection(conn);
conn->initialize(transport, true, NULL);
onConnectionHeaderReceived(conn, header);
}
void ConnectionManager::tcprosAcceptConnection(const TransportTCPPtr& transport)
{
std::string client_uri = transport->getClientURI();
ROSCPP_LOG_DEBUG("TCPROS received a connection from [%s]", client_uri.c_str());
ConnectionPtr conn(boost::make_shared<Connection>());
addConnection(conn);
conn->initialize(transport, true, boost::bind(&ConnectionManager::onConnectionHeaderReceived, this, _1, _2));
}
bool ConnectionManager::onConnectionHeaderReceived(const ConnectionPtr& conn, const Header& header)
{
bool ret = false;
std::string val;
if (header.getValue("topic", val))
{
ROSCPP_LOG_DEBUG("Connection: Creating TransportSubscriberLink for topic [%s] connected to [%s]",
val.c_str(), conn->getRemoteString().c_str());
TransportSubscriberLinkPtr sub_link(boost::make_shared<TransportSubscriberLink>());
sub_link->initialize(conn);
ret = sub_link->handleHeader(header);
}
else if (header.getValue("service", val))
{
ROSCPP_LOG_DEBUG("Connection: Creating ServiceClientLink for service [%s] connected to [%s]",
val.c_str(), conn->getRemoteString().c_str());
ServiceClientLinkPtr link(boost::make_shared<ServiceClientLink>());
link->initialize(conn);
ret = link->handleHeader(header);
}
else
{
ROSCPP_LOG_DEBUG("Got a connection for a type other than 'topic' or 'service' from [%s]. Fail.",
conn->getRemoteString().c_str());
return false;
}
return ret;
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/poll_manager.cpp | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/poll_manager.h"
#include "ros/common.h"
#include <signal.h>
namespace ros
{
PollManagerPtr g_poll_manager;
boost::mutex g_poll_manager_mutex;
const PollManagerPtr& PollManager::instance()
{
if (!g_poll_manager)
{
boost::mutex::scoped_lock lock(g_poll_manager_mutex);
if (!g_poll_manager)
{
g_poll_manager.reset(new PollManager);
}
}
return g_poll_manager;
}
PollManager::PollManager()
: shutting_down_(false)
{
}
PollManager::~PollManager()
{
shutdown();
}
void PollManager::start()
{
shutting_down_ = false;
thread_ = boost::thread(&PollManager::threadFunc, this);
}
void PollManager::shutdown()
{
if (shutting_down_) return;
shutting_down_ = true;
if (thread_.get_id() != boost::this_thread::get_id())
{
thread_.join();
}
boost::recursive_mutex::scoped_lock lock(signal_mutex_);
poll_signal_.disconnect_all_slots();
}
void PollManager::threadFunc()
{
disableAllSignalsInThisThread();
while (!shutting_down_)
{
{
boost::recursive_mutex::scoped_lock lock(signal_mutex_);
poll_signal_();
}
if (shutting_down_)
{
return;
}
poll_set_.update(100);
}
}
boost::signals2::connection PollManager::addPollThreadListener(const VoidFunc& func)
{
boost::recursive_mutex::scoped_lock lock(signal_mutex_);
return poll_signal_.connect(func);
}
void PollManager::removePollThreadListener(boost::signals2::connection c)
{
boost::recursive_mutex::scoped_lock lock(signal_mutex_);
c.disconnect();
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/transport/transport.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/transport/transport.h"
#include "ros/console.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#if !defined(__ANDROID__)
#include <ifaddrs.h>
#endif
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
namespace ros
{
Transport::Transport()
: only_localhost_allowed_(false)
{
char *ros_ip_env = NULL, *ros_hostname_env = NULL;
#ifdef _MSC_VER
_dupenv_s(&ros_ip_env, NULL, "ROS_IP");
_dupenv_s(&ros_hostname_env, NULL, "ROS_HOSTNAME");
#else
ros_ip_env = getenv("ROS_IP");
ros_hostname_env = getenv("ROS_HOSTNAME");
#endif
if (ros_hostname_env && !strcmp(ros_hostname_env, "localhost"))
only_localhost_allowed_ = true;
else if (ros_ip_env && !strncmp(ros_ip_env, "127.", 4))
only_localhost_allowed_ = true;
else if (ros_ip_env && !strcmp(ros_ip_env, "::1"))
only_localhost_allowed_ = true;
char our_hostname[256] = {0};
gethostname(our_hostname, sizeof(our_hostname)-1);
allowed_hosts_.push_back(std::string(our_hostname));
allowed_hosts_.push_back("localhost");
#if !defined(__ANDROID__)
// for ipv4 loopback, we'll explicitly search for 127.* in isHostAllowed()
// now we need to iterate all local interfaces and add their addresses
// from the getifaddrs manpage: (maybe something similar for windows ?)
ifaddrs *ifaddr;
if (-1 == getifaddrs(&ifaddr))
{
ROS_ERROR("getifaddr() failed");
return;
}
for (ifaddrs *ifa = ifaddr; ifa; ifa = ifa->ifa_next)
{
if(NULL == ifa->ifa_addr)
continue; // ifa_addr can be NULL
int family = ifa->ifa_addr->sa_family;
if (family != AF_INET && family != AF_INET6)
continue; // we're only looking for IP addresses
char addr[NI_MAXHOST] = {0};
if (getnameinfo(ifa->ifa_addr,
(family == AF_INET) ? sizeof(sockaddr_in)
: sizeof(sockaddr_in6),
addr, NI_MAXHOST,
NULL, 0, NI_NUMERICHOST))
{
ROS_ERROR("getnameinfo() failed");
continue;
}
allowed_hosts_.push_back(std::string(addr));
}
freeifaddrs(ifaddr);
#endif
}
bool Transport::isHostAllowed(const std::string &host) const
{
if (!only_localhost_allowed_)
return true; // doesn't matter; we'll connect to anybody
if (host.length() >= 4 && host.substr(0, 4) == std::string("127."))
return true; // ipv4 localhost
// now, loop through the list of valid hostnames and see if we find it
for (std::vector<std::string>::const_iterator it = allowed_hosts_.begin();
it != allowed_hosts_.end(); ++it)
{
if (host == *it)
return true; // hooray
}
ROS_WARN("ROS_HOSTNAME / ROS_IP is set to only allow local connections, so "
"a requested connection to '%s' is being rejected.", host.c_str());
return false; // sadness
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/transport/transport_tcp.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/io.h"
#include "ros/transport/transport_tcp.h"
#include "ros/poll_set.h"
#include "ros/header.h"
#include "ros/file_log.h"
#include <ros/assert.h>
#include <sstream>
#include <boost/bind.hpp>
#include <fcntl.h>
#include <errno.h>
namespace ros
{
bool TransportTCP::s_use_keepalive_ = true;
bool TransportTCP::s_use_ipv6_ = false;
TransportTCP::TransportTCP(PollSet* poll_set, int flags)
: sock_(ROS_INVALID_SOCKET)
, closed_(false)
, expecting_read_(false)
, expecting_write_(false)
, is_server_(false)
, server_port_(-1)
, local_port_(-1)
, poll_set_(poll_set)
, flags_(flags)
{
}
TransportTCP::~TransportTCP()
{
ROS_ASSERT_MSG(sock_ == -1, "TransportTCP socket [%d] was never closed", sock_);
}
bool TransportTCP::setSocket(int sock)
{
sock_ = sock;
return initializeSocket();
}
bool TransportTCP::setNonBlocking()
{
if (!(flags_ & SYNCHRONOUS))
{
int result = set_non_blocking(sock_);
if ( result != 0 ) {
ROS_ERROR("setting socket [%d] as non_blocking failed with error [%d]", sock_, result);
close();
return false;
}
}
return true;
}
bool TransportTCP::initializeSocket()
{
ROS_ASSERT(sock_ != ROS_INVALID_SOCKET);
if (!setNonBlocking())
{
return false;
}
setKeepAlive(s_use_keepalive_, 60, 10, 9);
// connect() will set cached_remote_host_ because it already has the host/port available
if (cached_remote_host_.empty())
{
if (is_server_)
{
cached_remote_host_ = "TCPServer Socket";
}
else
{
std::stringstream ss;
ss << getClientURI() << " on socket " << sock_;
cached_remote_host_ = ss.str();
}
}
if (local_port_ < 0)
{
la_len_ = s_use_ipv6_ ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);
getsockname(sock_, (sockaddr *)&local_address_, &la_len_);
switch (local_address_.ss_family)
{
case AF_INET:
local_port_ = ntohs(((sockaddr_in *)&local_address_)->sin_port);
break;
case AF_INET6:
local_port_ = ntohs(((sockaddr_in6 *)&local_address_)->sin6_port);
break;
}
}
#ifdef ROSCPP_USE_TCP_NODELAY
setNoDelay(true);
#endif
ROS_ASSERT(poll_set_ || (flags_ & SYNCHRONOUS));
if (poll_set_)
{
ROS_DEBUG("Adding tcp socket [%d] to pollset", sock_);
poll_set_->addSocket(sock_, boost::bind(&TransportTCP::socketUpdate, this, _1), shared_from_this());
}
if (!(flags_ & SYNCHRONOUS))
{
//enableRead();
}
return true;
}
void TransportTCP::parseHeader(const Header& header)
{
std::string nodelay;
if (header.getValue("tcp_nodelay", nodelay) && nodelay == "1")
{
ROSCPP_LOG_DEBUG("Setting nodelay on socket [%d]", sock_);
setNoDelay(true);
}
}
void TransportTCP::setNoDelay(bool nodelay)
{
int flag = nodelay ? 1 : 0;
int result = setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
if (result < 0)
{
ROS_ERROR("setsockopt failed to set TCP_NODELAY on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
}
void TransportTCP::setKeepAlive(bool use, uint32_t idle, uint32_t interval, uint32_t count)
{
if (use)
{
int val = 1;
if (setsockopt(sock_, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<const char*>(&val), sizeof(val)) != 0)
{
ROS_DEBUG("setsockopt failed to set SO_KEEPALIVE on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
/* cygwin SOL_TCP does not seem to support TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT */
#if defined(SOL_TCP) && !defined(__CYGWIN__)
val = idle;
if (setsockopt(sock_, SOL_TCP, TCP_KEEPIDLE, &val, sizeof(val)) != 0)
{
ROS_DEBUG("setsockopt failed to set TCP_KEEPIDLE on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
val = interval;
if (setsockopt(sock_, SOL_TCP, TCP_KEEPINTVL, &val, sizeof(val)) != 0)
{
ROS_DEBUG("setsockopt failed to set TCP_KEEPINTVL on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
val = count;
if (setsockopt(sock_, SOL_TCP, TCP_KEEPCNT, &val, sizeof(val)) != 0)
{
ROS_DEBUG("setsockopt failed to set TCP_KEEPCNT on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
#endif
}
else
{
int val = 0;
if (setsockopt(sock_, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<const char*>(&val), sizeof(val)) != 0)
{
ROS_DEBUG("setsockopt failed to set SO_KEEPALIVE on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
}
}
bool TransportTCP::connect(const std::string& host, int port)
{
if (!isHostAllowed(host))
return false; // adios amigo
sock_ = socket(s_use_ipv6_ ? AF_INET6 : AF_INET, SOCK_STREAM, 0);
connected_host_ = host;
connected_port_ = port;
if (sock_ == ROS_INVALID_SOCKET)
{
ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
return false;
}
setNonBlocking();
sockaddr_storage sas;
socklen_t sas_len;
in_addr ina;
in6_addr in6a;
if (inet_pton(AF_INET, host.c_str(), &ina) == 1)
{
sockaddr_in *address = (sockaddr_in*) &sas;
sas_len = sizeof(sockaddr_in);
la_len_ = sizeof(sockaddr_in);
address->sin_family = AF_INET;
address->sin_port = htons(port);
address->sin_addr.s_addr = ina.s_addr;
}
else if (inet_pton(AF_INET6, host.c_str(), &in6a) == 1)
{
sockaddr_in6 *address = (sockaddr_in6*) &sas;
sas_len = sizeof(sockaddr_in6);
la_len_ = sizeof(sockaddr_in6);
address->sin6_family = AF_INET6;
address->sin6_port = htons(port);
memcpy(address->sin6_addr.s6_addr, in6a.s6_addr, sizeof(in6a.s6_addr));
}
else
{
struct addrinfo* addr;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
if (getaddrinfo(host.c_str(), NULL, &hints, &addr) != 0)
{
close();
ROS_ERROR("couldn't resolve publisher host [%s]", host.c_str());
return false;
}
bool found = false;
struct addrinfo* it = addr;
char namebuf[128];
for (; it; it = it->ai_next)
{
if (!s_use_ipv6_ && it->ai_family == AF_INET)
{
sockaddr_in *address = (sockaddr_in*) &sas;
sas_len = sizeof(*address);
memcpy(address, it->ai_addr, it->ai_addrlen);
address->sin_family = it->ai_family;
address->sin_port = htons(port);
strcpy(namebuf, inet_ntoa(address->sin_addr));
found = true;
break;
}
if (s_use_ipv6_ && it->ai_family == AF_INET6)
{
sockaddr_in6 *address = (sockaddr_in6*) &sas;
sas_len = sizeof(*address);
memcpy(address, it->ai_addr, it->ai_addrlen);
address->sin6_family = it->ai_family;
address->sin6_port = htons((u_short) port);
// TODO IPV6: does inet_ntop need other includes for Windows?
inet_ntop(AF_INET6, (void*)&(address->sin6_addr), namebuf, sizeof(namebuf));
found = true;
break;
}
}
freeaddrinfo(addr);
if (!found)
{
ROS_ERROR("Couldn't resolve an address for [%s]\n", host.c_str());
return false;
}
ROSCPP_LOG_DEBUG("Resolved publisher host [%s] to [%s] for socket [%d]", host.c_str(), namebuf, sock_);
}
int ret = ::connect(sock_, (sockaddr*) &sas, sas_len);
// windows might need some time to sleep (input from service robotics hack) add this if testing proves it is necessary.
ROS_ASSERT((flags_ & SYNCHRONOUS) || ret != 0);
if (((flags_ & SYNCHRONOUS) && ret != 0) || // synchronous, connect() should return 0
(!(flags_ & SYNCHRONOUS) && last_socket_error() != ROS_SOCKETS_ASYNCHRONOUS_CONNECT_RETURN)) // asynchronous, connect() should return -1 and WSAGetLastError()=WSAEWOULDBLOCK/errno=EINPROGRESS
{
ROSCPP_LOG_DEBUG("Connect to tcpros publisher [%s:%d] failed with error [%d, %s]", host.c_str(), port, ret, last_socket_error_string());
close();
return false;
}
// from daniel stonier:
#ifdef WIN32
// This is hackish, but windows fails at recv() if its slow to connect (e.g. happens with wireless)
// recv() needs to check if its connected or not when its asynchronous?
Sleep(100);
#endif
std::stringstream ss;
ss << host << ":" << port << " on socket " << sock_;
cached_remote_host_ = ss.str();
if (!initializeSocket())
{
return false;
}
if (flags_ & SYNCHRONOUS)
{
ROSCPP_LOG_DEBUG("connect() succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
}
else
{
ROSCPP_LOG_DEBUG("Async connect() in progress to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
}
return true;
}
bool TransportTCP::listen(int port, int backlog, const AcceptCallback& accept_cb)
{
is_server_ = true;
accept_cb_ = accept_cb;
if (s_use_ipv6_)
{
sock_ = socket(AF_INET6, SOCK_STREAM, 0);
sockaddr_in6 *address = (sockaddr_in6 *)&server_address_;
address->sin6_family = AF_INET6;
address->sin6_addr = isOnlyLocalhostAllowed() ?
in6addr_loopback :
in6addr_any;
address->sin6_port = htons(port);
sa_len_ = sizeof(sockaddr_in6);
}
else
{
sock_ = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in *address = (sockaddr_in *)&server_address_;
address->sin_family = AF_INET;
address->sin_addr.s_addr = isOnlyLocalhostAllowed() ?
htonl(INADDR_LOOPBACK) :
INADDR_ANY;
address->sin_port = htons(port);
sa_len_ = sizeof(sockaddr_in);
}
if (sock_ <= 0)
{
ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
return false;
}
if (bind(sock_, (sockaddr *)&server_address_, sa_len_) < 0)
{
ROS_ERROR("bind() failed with error [%s]", last_socket_error_string());
return false;
}
::listen(sock_, backlog);
getsockname(sock_, (sockaddr *)&server_address_, &sa_len_);
switch (server_address_.ss_family)
{
case AF_INET:
server_port_ = ntohs(((sockaddr_in *)&server_address_)->sin_port);
break;
case AF_INET6:
server_port_ = ntohs(((sockaddr_in6 *)&server_address_)->sin6_port);
break;
}
if (!initializeSocket())
{
return false;
}
if (!(flags_ & SYNCHRONOUS))
{
enableRead();
}
return true;
}
void TransportTCP::close()
{
Callback disconnect_cb;
if (!closed_)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (!closed_)
{
closed_ = true;
ROS_ASSERT(sock_ != ROS_INVALID_SOCKET);
if (poll_set_)
{
poll_set_->delSocket(sock_);
}
::shutdown(sock_, ROS_SOCKETS_SHUT_RDWR);
if ( close_socket(sock_) != 0 )
{
ROS_ERROR("Error closing socket [%d]: [%s]", sock_, last_socket_error_string());
} else
{
ROSCPP_LOG_DEBUG("TCP socket [%d] closed", sock_);
}
sock_ = ROS_INVALID_SOCKET;
disconnect_cb = disconnect_cb_;
disconnect_cb_ = Callback();
read_cb_ = Callback();
write_cb_ = Callback();
accept_cb_ = AcceptCallback();
}
}
}
if (disconnect_cb)
{
disconnect_cb(shared_from_this());
}
}
int32_t TransportTCP::read(uint8_t* buffer, uint32_t size)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to read on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT(size > 0);
// never read more than INT_MAX since this is the maximum we can report back with the current return type
uint32_t read_size = std::min(size, static_cast<uint32_t>(INT_MAX));
int num_bytes = ::recv(sock_, reinterpret_cast<char*>(buffer), read_size, 0);
if (num_bytes < 0)
{
if ( !last_socket_error_is_would_block() ) // !WSAWOULDBLOCK / !EAGAIN && !EWOULDBLOCK
{
ROSCPP_LOG_DEBUG("recv() on socket [%d] failed with error [%s]", sock_, last_socket_error_string());
close();
}
else
{
num_bytes = 0;
}
}
else if (num_bytes == 0)
{
ROSCPP_LOG_DEBUG("Socket [%d] received 0/%u bytes, closing", sock_, size);
close();
return -1;
}
return num_bytes;
}
int32_t TransportTCP::write(uint8_t* buffer, uint32_t size)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to write on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT(size > 0);
// never write more than INT_MAX since this is the maximum we can report back with the current return type
uint32_t writesize = std::min(size, static_cast<uint32_t>(INT_MAX));
int num_bytes = ::send(sock_, reinterpret_cast<const char*>(buffer), writesize, 0);
if (num_bytes < 0)
{
if ( !last_socket_error_is_would_block() )
{
ROSCPP_LOG_DEBUG("send() on socket [%d] failed with error [%s]", sock_, last_socket_error_string());
close();
}
else
{
num_bytes = 0;
}
}
return num_bytes;
}
void TransportTCP::enableRead()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_read_)
{
poll_set_->addEvents(sock_, POLLIN);
expecting_read_ = true;
}
}
void TransportTCP::disableRead()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (expecting_read_)
{
poll_set_->delEvents(sock_, POLLIN);
expecting_read_ = false;
}
}
void TransportTCP::enableWrite()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_write_)
{
poll_set_->addEvents(sock_, POLLOUT);
expecting_write_ = true;
}
}
void TransportTCP::disableWrite()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (expecting_write_)
{
poll_set_->delEvents(sock_, POLLOUT);
expecting_write_ = false;
}
}
TransportTCPPtr TransportTCP::accept()
{
ROS_ASSERT(is_server_);
sockaddr client_address;
socklen_t len = sizeof(client_address);
int new_sock = ::accept(sock_, (sockaddr *)&client_address, &len);
if (new_sock >= 0)
{
ROSCPP_LOG_DEBUG("Accepted connection on socket [%d], new socket [%d]", sock_, new_sock);
TransportTCPPtr transport(boost::make_shared<TransportTCP>(poll_set_, flags_));
if (!transport->setSocket(new_sock))
{
ROS_ERROR("Failed to set socket on transport for socket %d", new_sock);
}
return transport;
}
else
{
ROS_ERROR("accept() on socket [%d] failed with error [%s]", sock_, last_socket_error_string());
}
return TransportTCPPtr();
}
void TransportTCP::socketUpdate(int events)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
// Handle read events before err/hup/nval, since there may be data left on the wire
if ((events & POLLIN) && expecting_read_)
{
if (is_server_)
{
// Should not block here, because poll() said that it's ready
// for reading
TransportTCPPtr transport = accept();
if (transport)
{
ROS_ASSERT(accept_cb_);
accept_cb_(transport);
}
}
else
{
if (read_cb_)
{
read_cb_(shared_from_this());
}
}
}
if ((events & POLLOUT) && expecting_write_)
{
if (write_cb_)
{
write_cb_(shared_from_this());
}
}
}
if((events & POLLERR) ||
(events & POLLHUP) ||
(events & POLLNVAL))
{
uint32_t error = -1;
socklen_t len = sizeof(error);
if (getsockopt(sock_, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &len) < 0)
{
ROSCPP_LOG_DEBUG("getsockopt failed on socket [%d]", sock_);
}
#ifdef _MSC_VER
char err[60];
strerror_s(err,60,error);
ROSCPP_LOG_DEBUG("Socket %d closed with (ERR|HUP|NVAL) events %d: %s", sock_, events, err);
#else
ROSCPP_LOG_DEBUG("Socket %d closed with (ERR|HUP|NVAL) events %d: %s", sock_, events, strerror(error));
#endif
close();
}
}
std::string TransportTCP::getTransportInfo()
{
std::stringstream str;
str << "TCPROS connection on port " << local_port_ << " to [" << cached_remote_host_ << "]";
return str.str();
}
std::string TransportTCP::getClientURI()
{
ROS_ASSERT(!is_server_);
sockaddr_storage sas;
socklen_t sas_len = sizeof(sas);
getpeername(sock_, (sockaddr *)&sas, &sas_len);
sockaddr_in *sin = (sockaddr_in *)&sas;
sockaddr_in6 *sin6 = (sockaddr_in6 *)&sas;
char namebuf[128];
int port;
switch (sas.ss_family)
{
case AF_INET:
port = ntohs(sin->sin_port);
strcpy(namebuf, inet_ntoa(sin->sin_addr));
break;
case AF_INET6:
port = ntohs(sin6->sin6_port);
inet_ntop(AF_INET6, (void*)&(sin6->sin6_addr), namebuf, sizeof(namebuf));
break;
default:
namebuf[0] = 0;
port = 0;
break;
}
std::string ip = namebuf;
std::stringstream uri;
uri << ip << ":" << port;
return uri.str();
}
std::string TransportTCP::getLocalIp()
{
socklen_t local_address_len = sizeof(local_address_);
getsockname(sock_, (sockaddr *)&local_address_, &local_address_len);
sockaddr_in *sin = (sockaddr_in *)&local_address_;
sockaddr_in6 *sin6 = (sockaddr_in6 *)&local_address_;
char namebuf[128];
int port = 0;
switch (local_address_.ss_family)
{
case AF_INET:
port = ntohs(sin->sin_port);
strcpy(namebuf, inet_ntoa(sin->sin_addr));
break;
case AF_INET6:
port = ntohs(sin6->sin6_port);
inet_ntop(AF_INET6, (void*)&(sin6->sin6_addr), namebuf, sizeof(namebuf));
break;
default:
namebuf[0] = 0;
port = 0;
break;
}
std::string ip = namebuf;
std::stringstream uri;
uri << ip << ":" << port;
return uri.str();
}
} // namespace ros
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/transport/transport_udp.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/transport/transport_udp.h"
#include "ros/poll_set.h"
#include "ros/file_log.h"
#include <ros/assert.h>
#include <boost/bind.hpp>
#include <fcntl.h>
#if defined(__APPLE__)
// For readv() and writev()
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#elif defined(__ANDROID__)
// For readv() and writev() on ANDROID
#include <sys/uio.h>
#endif
namespace ros
{
TransportUDP::TransportUDP(PollSet* poll_set, int flags, int max_datagram_size)
: sock_(-1)
, closed_(false)
, expecting_read_(false)
, expecting_write_(false)
, is_server_(false)
, server_port_(-1)
, local_port_(-1)
, poll_set_(poll_set)
, flags_(flags)
, connection_id_(0)
, current_message_id_(0)
, total_blocks_(0)
, last_block_(0)
, max_datagram_size_(max_datagram_size)
, data_filled_(0)
, reorder_buffer_(0)
, reorder_bytes_(0)
{
// This may eventually be machine dependent
if (max_datagram_size_ == 0)
max_datagram_size_ = 1500;
reorder_buffer_ = new uint8_t[max_datagram_size_];
reorder_start_ = reorder_buffer_;
data_buffer_ = new uint8_t[max_datagram_size_];
data_start_ = data_buffer_;
}
TransportUDP::~TransportUDP()
{
ROS_ASSERT_MSG(sock_ == ROS_INVALID_SOCKET, "TransportUDP socket [%d] was never closed", sock_);
delete [] reorder_buffer_;
delete [] data_buffer_;
}
bool TransportUDP::setSocket(int sock)
{
sock_ = sock;
return initializeSocket();
}
void TransportUDP::socketUpdate(int events)
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if((events & POLLERR) ||
(events & POLLHUP) ||
(events & POLLNVAL))
{
ROSCPP_LOG_DEBUG("Socket %d closed with (ERR|HUP|NVAL) events %d", sock_, events);
close();
}
else
{
if ((events & POLLIN) && expecting_read_)
{
if (read_cb_)
{
read_cb_(shared_from_this());
}
}
if ((events & POLLOUT) && expecting_write_)
{
if (write_cb_)
{
write_cb_(shared_from_this());
}
}
}
}
std::string TransportUDP::getTransportInfo()
{
std::stringstream str;
str << "UDPROS connection on port " << local_port_ << " to [" << cached_remote_host_ << "]";
return str.str();
}
bool TransportUDP::connect(const std::string& host, int port, int connection_id)
{
if (!isHostAllowed(host))
return false; // adios amigo
sock_ = socket(AF_INET, SOCK_DGRAM, 0);
connection_id_ = connection_id;
if (sock_ == ROS_INVALID_SOCKET)
{
ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
return false;
}
sockaddr_in sin;
sin.sin_family = AF_INET;
if (inet_addr(host.c_str()) == INADDR_NONE)
{
struct addrinfo* addr;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
if (getaddrinfo(host.c_str(), NULL, &hints, &addr) != 0)
{
close();
ROS_ERROR("couldn't resolve host [%s]", host.c_str());
return false;
}
bool found = false;
struct addrinfo* it = addr;
for (; it; it = it->ai_next)
{
if (it->ai_family == AF_INET)
{
memcpy(&sin, it->ai_addr, it->ai_addrlen);
sin.sin_family = it->ai_family;
sin.sin_port = htons(port);
found = true;
break;
}
}
freeaddrinfo(addr);
if (!found)
{
ROS_ERROR("Couldn't find an AF_INET address for [%s]\n", host.c_str());
return false;
}
ROSCPP_LOG_DEBUG("Resolved host [%s] to [%s]", host.c_str(), inet_ntoa(sin.sin_addr));
}
else
{
sin.sin_addr.s_addr = inet_addr(host.c_str()); // already an IP addr
}
sin.sin_port = htons(port);
if (::connect(sock_, (sockaddr *)&sin, sizeof(sin)))
{
ROSCPP_LOG_DEBUG("Connect to udpros host [%s:%d] failed with error [%s]", host.c_str(), port, last_socket_error_string());
close();
return false;
}
// from daniel stonier:
#ifdef WIN32
// This is hackish, but windows fails at recv() if its slow to connect (e.g. happens with wireless)
// recv() needs to check if its connected or not when its asynchronous?
Sleep(100);
#endif
std::stringstream ss;
ss << host << ":" << port << " on socket " << sock_;
cached_remote_host_ = ss.str();
if (!initializeSocket())
{
return false;
}
ROSCPP_LOG_DEBUG("Connect succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
return true;
}
bool TransportUDP::createIncoming(int port, bool is_server)
{
is_server_ = is_server;
sock_ = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_ <= 0)
{
ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
return false;
}
server_address_.sin_family = AF_INET;
server_address_.sin_port = htons(port);
server_address_.sin_addr.s_addr = isOnlyLocalhostAllowed() ?
htonl(INADDR_LOOPBACK) :
INADDR_ANY;
if (bind(sock_, (sockaddr *)&server_address_, sizeof(server_address_)) < 0)
{
ROS_ERROR("bind() failed with error [%s]", last_socket_error_string());
return false;
}
socklen_t len = sizeof(server_address_);
getsockname(sock_, (sockaddr *)&server_address_, &len);
server_port_ = ntohs(server_address_.sin_port);
ROSCPP_LOG_DEBUG("UDPROS server listening on port [%d]", server_port_);
if (!initializeSocket())
{
return false;
}
enableRead();
return true;
}
bool TransportUDP::initializeSocket()
{
ROS_ASSERT(sock_ != ROS_INVALID_SOCKET);
if (!(flags_ & SYNCHRONOUS))
{
int result = set_non_blocking(sock_);
if ( result != 0 ) {
ROS_ERROR("setting socket [%d] as non_blocking failed with error [%d]", sock_, result);
close();
return false;
}
}
socklen_t len = sizeof(local_address_);
getsockname(sock_, (sockaddr *)&local_address_, &len);
local_port_ = ntohs(local_address_.sin_port);
ROS_ASSERT(poll_set_ || (flags_ & SYNCHRONOUS));
if (poll_set_)
{
poll_set_->addSocket(sock_, boost::bind(&TransportUDP::socketUpdate, this, _1), shared_from_this());
}
return true;
}
void TransportUDP::close()
{
Callback disconnect_cb;
if (!closed_)
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (!closed_)
{
closed_ = true;
ROSCPP_LOG_DEBUG("UDP socket [%d] closed", sock_);
ROS_ASSERT(sock_ != ROS_INVALID_SOCKET);
if (poll_set_)
{
poll_set_->delSocket(sock_);
}
if ( close_socket(sock_) != 0 )
{
ROS_ERROR("Error closing socket [%d]: [%s]", sock_, last_socket_error_string());
}
sock_ = ROS_INVALID_SOCKET;
disconnect_cb = disconnect_cb_;
disconnect_cb_ = Callback();
read_cb_ = Callback();
write_cb_ = Callback();
}
}
}
if (disconnect_cb)
{
disconnect_cb(shared_from_this());
}
}
int32_t TransportUDP::read(uint8_t* buffer, uint32_t size)
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to read on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT((int32_t)size > 0);
uint32_t bytes_read = 0;
while (bytes_read < size)
{
TransportUDPHeader header;
// Get the data either from the reorder buffer or the socket
// copy_bytes will contain the read size.
// from_previous is true if the data belongs to the previous UDP datagram.
uint32_t copy_bytes = 0;
bool from_previous = false;
if (reorder_bytes_)
{
if (reorder_start_ != reorder_buffer_)
{
from_previous = true;
}
copy_bytes = std::min(size - bytes_read, reorder_bytes_);
header = reorder_header_;
memcpy(buffer + bytes_read, reorder_start_, copy_bytes);
reorder_bytes_ -= copy_bytes;
reorder_start_ += copy_bytes;
}
else
{
if (data_filled_ == 0)
{
#if defined(WIN32)
SSIZE_T num_bytes = 0;
DWORD received_bytes = 0;
DWORD flags = 0;
WSABUF iov[2];
iov[0].buf = reinterpret_cast<char*>(&header);
iov[0].len = sizeof(header);
iov[1].buf = reinterpret_cast<char*>(data_buffer_);
iov[1].len = max_datagram_size_ - sizeof(header);
int rc = WSARecv(sock_, iov, 2, &received_bytes, &flags, NULL, NULL);
if ( rc == SOCKET_ERROR) {
num_bytes = -1;
} else {
num_bytes = received_bytes;
}
#else
ssize_t num_bytes;
struct iovec iov[2];
iov[0].iov_base = &header;
iov[0].iov_len = sizeof(header);
iov[1].iov_base = data_buffer_;
iov[1].iov_len = max_datagram_size_ - sizeof(header);
// Read a datagram with header
num_bytes = readv(sock_, iov, 2);
#endif
if (num_bytes < 0)
{
if ( last_socket_error_is_would_block() )
{
num_bytes = 0;
break;
}
else
{
ROSCPP_LOG_DEBUG("readv() failed with error [%s]", last_socket_error_string());
close();
break;
}
}
else if (num_bytes == 0)
{
ROSCPP_LOG_DEBUG("Socket [%d] received 0/%d bytes, closing", sock_, size);
close();
return -1;
}
else if (num_bytes < (unsigned) sizeof(header))
{
ROS_ERROR("Socket [%d] received short header (%d bytes): %s", sock_, int(num_bytes), last_socket_error_string());
close();
return -1;
}
num_bytes -= sizeof(header);
data_filled_ = num_bytes;
data_start_ = data_buffer_;
}
else
{
from_previous = true;
}
copy_bytes = std::min(size - bytes_read, data_filled_);
// Copy from the data buffer, whether it has data left in it from a previous datagram or
// was just filled by readv()
memcpy(buffer + bytes_read, data_start_, copy_bytes);
data_filled_ -= copy_bytes;
data_start_ += copy_bytes;
}
if (from_previous)
{
// We are simply reading data from the last UDP datagram, nothing to
// parse
bytes_read += copy_bytes;
}
else
{
// This datagram is new, process header
switch (header.op_)
{
case ROS_UDP_DATA0:
if (current_message_id_)
{
ROS_DEBUG("Received new message [%d:%d], while still working on [%d] (block %d of %d)", header.message_id_, header.block_, current_message_id_, last_block_ + 1, total_blocks_);
reorder_header_ = header;
// Copy the entire data buffer to the reorder buffer, as we will
// need to replay this UDP datagram in the next call.
reorder_bytes_ = data_filled_ + (data_start_ - data_buffer_);
memcpy(reorder_buffer_, data_buffer_, reorder_bytes_);
reorder_start_ = reorder_buffer_;
current_message_id_ = 0;
total_blocks_ = 0;
last_block_ = 0;
data_filled_ = 0;
data_start_ = data_buffer_;
return -1;
}
total_blocks_ = header.block_;
last_block_ = 0;
current_message_id_ = header.message_id_;
break;
case ROS_UDP_DATAN:
if (header.message_id_ != current_message_id_)
{
ROS_DEBUG("Message Id mismatch: %d != %d", header.message_id_, current_message_id_);
data_filled_ = 0; // discard datagram
return 0;
}
if (header.block_ != last_block_ + 1)
{
ROS_DEBUG("Expected block %d, received %d", last_block_ + 1, header.block_);
data_filled_ = 0; // discard datagram
return 0;
}
last_block_ = header.block_;
break;
default:
ROS_ERROR("Unexpected UDP header OP [%d]", header.op_);
return -1;
}
bytes_read += copy_bytes;
if (last_block_ == (total_blocks_ - 1))
{
current_message_id_ = 0;
break;
}
}
}
return bytes_read;
}
int32_t TransportUDP::write(uint8_t* buffer, uint32_t size)
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to write on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT((int32_t)size > 0);
const uint32_t max_payload_size = max_datagram_size_ - sizeof(TransportUDPHeader);
uint32_t bytes_sent = 0;
uint32_t this_block = 0;
if (++current_message_id_ == 0)
++current_message_id_;
while (bytes_sent < size)
{
TransportUDPHeader header;
header.connection_id_ = connection_id_;
header.message_id_ = current_message_id_;
if (this_block == 0)
{
header.op_ = ROS_UDP_DATA0;
header.block_ = (size + max_payload_size - 1) / max_payload_size;
}
else
{
header.op_ = ROS_UDP_DATAN;
header.block_ = this_block;
}
++this_block;
#if defined(WIN32)
WSABUF iov[2];
DWORD sent_bytes;
SSIZE_T num_bytes = 0;
DWORD flags = 0;
int rc;
iov[0].buf = reinterpret_cast<char*>(&header);
iov[0].len = sizeof(header);
iov[1].buf = reinterpret_cast<char*>(buffer + bytes_sent);
iov[1].len = std::min(max_payload_size, size - bytes_sent);
rc = WSASend(sock_, iov, 2, &sent_bytes, flags, NULL, NULL);
num_bytes = sent_bytes;
if (rc == SOCKET_ERROR) {
num_bytes = -1;
}
#else
struct iovec iov[2];
iov[0].iov_base = &header;
iov[0].iov_len = sizeof(header);
iov[1].iov_base = buffer + bytes_sent;
iov[1].iov_len = std::min(max_payload_size, size - bytes_sent);
ssize_t num_bytes = writev(sock_, iov, 2);
#endif
//usleep(100);
if (num_bytes < 0)
{
if( !last_socket_error_is_would_block() ) // Actually EAGAIN or EWOULDBLOCK on posix
{
ROSCPP_LOG_DEBUG("writev() failed with error [%s]", last_socket_error_string());
close();
break;
}
else
{
num_bytes = 0;
--this_block;
}
}
else if (num_bytes < (unsigned) sizeof(header))
{
ROSCPP_LOG_DEBUG("Socket [%d] short write (%d bytes), closing", sock_, int(num_bytes));
close();
break;
}
else
{
num_bytes -= sizeof(header);
}
bytes_sent += num_bytes;
}
return bytes_sent;
}
void TransportUDP::enableRead()
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_read_)
{
poll_set_->addEvents(sock_, POLLIN);
expecting_read_ = true;
}
}
void TransportUDP::disableRead()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (expecting_read_)
{
poll_set_->delEvents(sock_, POLLIN);
expecting_read_ = false;
}
}
void TransportUDP::enableWrite()
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_write_)
{
poll_set_->addEvents(sock_, POLLOUT);
expecting_write_ = true;
}
}
void TransportUDP::disableWrite()
{
{
boost::mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (expecting_write_)
{
poll_set_->delEvents(sock_, POLLOUT);
expecting_write_ = false;
}
}
TransportUDPPtr TransportUDP::createOutgoing(std::string host, int port, int connection_id, int max_datagram_size)
{
ROS_ASSERT(is_server_);
TransportUDPPtr transport(boost::make_shared<TransportUDP>(poll_set_, flags_, max_datagram_size));
if (!transport->connect(host, port, connection_id))
{
ROS_ERROR("Failed to create outgoing connection");
return TransportUDPPtr();
}
return transport;
}
std::string TransportUDP::getClientURI()
{
ROS_ASSERT(!is_server_);
sockaddr_storage sas;
socklen_t sas_len = sizeof(sas);
getpeername(sock_, (sockaddr *)&sas, &sas_len);
sockaddr_in *sin = (sockaddr_in *)&sas;
char namebuf[128];
int port = ntohs(sin->sin_port);
strcpy(namebuf, inet_ntoa(sin->sin_addr));
std::string ip = namebuf;
std::stringstream uri;
uri << ip << ":" << port;
return uri.str();
}
std::string TransportUDP::getLocalIp()
{
socklen_t local_address_len = sizeof(local_address_);
getsockname(sock_, (sockaddr *)&local_address_, &local_address_len);
sockaddr_in *sin = (sockaddr_in *)&local_address_;
char namebuf[128];
int port = ntohs(sin->sin_port);
strcpy(namebuf, inet_ntoa(sin->sin_addr));
std::string ip = namebuf;
std::stringstream uri;
uri << ip << ":" << port;
return uri.str();
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/sharedmem_transport/sharedmem_block.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sharedmem_transport/sharedmem_block.h"
namespace sharedmem_transport
{
/**************************************************************************************
* Public function in SharedMemoryBlock
**************************************************************************************/
SharedMemoryBlock::SharedMemoryBlock() :
_writing_flag(false),
_reading_count(0),
_msg_size(0),
_alloc_size(0)
{
}
SharedMemoryBlock::SharedMemoryBlock(
bool wf, uint32_t rc, uint32_t ms, uint32_t as) :
_writing_flag(wf),
_reading_count(rc),
_msg_size(ms),
_alloc_size(as)
{
}
bool SharedMemoryBlock::try_reserve_for_radical_write()
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(
_write_read_mutex);
// Block is not available for write
if (_writing_flag || _reading_count)
{
return false;
}
// Block is available for write
_writing_flag = true;
return true;
}
bool SharedMemoryBlock::try_reserve_for_radical_read()
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(
_write_read_mutex);
// Block is not available for read
if (_writing_flag)
{
return false;
}
// Block is available for read
++_reading_count;
return true;
}
void SharedMemoryBlock::release_reserve_for_radical_write()
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(
_write_read_mutex);
_writing_flag = false;
}
void SharedMemoryBlock::release_reserve_for_radical_read()
{
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(
_write_read_mutex);
--_reading_count;
}
bool SharedMemoryBlock::write_to_block(uint8_t* dest, const ros::SerializedMessage& msg)
{
// Serialize Data
bool result = serialize(dest, msg);
return result;
}
bool SharedMemoryBlock::read_from_block(uint8_t* src, ros::VoidConstPtr& msg,
ros::SubscriptionCallbackHelperPtr& helper, ros::M_stringPtr& header_ptr)
{
// Deserialze msg from block
ros::SubscriptionCallbackHelperDeserializeParams params ;
params.buffer = src;
params.length = (uint32_t)_msg_size;
params.connection_header = header_ptr;
msg = helper->deserialize(params);
return true;
}
} // namespace sharedmem_transport
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/sharedmem_transport/sharedmem_segment.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sharedmem_transport/sharedmem_segment.h"
namespace sharedmem_transport
{
/**************************************************************************************
* Public function in SharedMemorySegment
**************************************************************************************/
bool SharedMemorySegment::init_all_blocks(boost::interprocess::managed_shared_memory& segment,
uint32_t queue_size, uint64_t msg_size, uint64_t& real_alloc_size, SharedMemoryBlock*& descriptors_pub,
uint8_t** addr_pub)
{
// Lock mutex in segment
boost::interprocess::scoped_lock < boost::interprocess::interprocess_mutex > lock(
_wrote_num_mutex);
// Init descriptors_pub for all blocks
uint64_t alloc_size = (uint64_t)((msg_size + ROS_SHM_BLOCK_SIZE) * ROS_SHM_BLOCK_SIZE_RATIO);
try
{
descriptors_pub = segment.find_or_construct < SharedMemoryBlock > ("BlockDescriptor")
[queue_size](false, 0, msg_size, alloc_size);
} catch (boost::interprocess::bad_alloc e)
{
ROS_ERROR("Block allocate error");
return false;
}
if (!descriptors_pub)
{
ROS_ERROR("Not create descriptors_pub!");
return false;
}
// Init all blocks
for (uint32_t i = 0; i < queue_size; ++i)
{
std::stringstream block_name;
block_name << i;
uint8_t* addr = NULL;
try
{
addr = segment.find_or_construct < uint8_t >
(block_name.str().c_str())[alloc_size](0);
} catch (boost::interprocess::bad_alloc e)
{
ROS_ERROR("Addr pub %d allocate error", i);
return false;
}
if (!addr)
{
ROS_ERROR("Not create %d block!", i);
return false;
}
addr_pub[i] = addr;
ROS_DEBUG("pub init: connected block %d to index %d, addr %p", i, i, addr);
}
// Get real_alloc_size
descriptors_pub->get_alloc_size(real_alloc_size);
return true;
}
bool SharedMemorySegment::map_all_blocks(boost::interprocess::managed_shared_memory*& segment,
uint32_t queue_size, uint8_t** addr_sub)
{
// Lock mutex in segment
boost::interprocess::scoped_lock < boost::interprocess::interprocess_mutex > lock(
_wrote_num_mutex);
// Map all blocks
for (uint32_t i = 0; i < queue_size; ++i)
{
std::stringstream block_name;
block_name << i;
uint8_t* addr = NULL;
try
{
addr = segment->find < uint8_t > (block_name.str().c_str()).first;
} catch (boost::interprocess::bad_alloc e)
{
ROS_ERROR("Addr sub %d allocate error", i);
return false;
}
if (!addr)
{
ROS_INFO("Not find %d block!", i);
return false;
}
addr_sub[i] = addr;
ROS_DEBUG("sub map: connected block %d to index %d, addr %p", i, i, addr);
}
return true;
}
bool SharedMemorySegment::write_data(const ros::SerializedMessage& msg,
uint32_t queue_size,SharedMemoryBlock* descriptors_pub, uint8_t** addr_pub, int32_t& last_index)
{
ROS_DEBUG("Write radical start!");
int32_t block_index;
{
// Lock _wrote_num_mutex in segment
ROS_DEBUG("Lock _wrote_num_mutex in segment");
boost::interprocess::scoped_lock < boost::interprocess::interprocess_mutex >
segment_lock(_wrote_num_mutex);
// Reserve next writable block
block_index = reserve_radical_writable_block(queue_size, descriptors_pub);
}
// Block needs to be reallocated
if (block_index == ROS_SHM_SEGMENT_WROTE_NUM)
{
last_index = block_index;
return false;
}
// Get descriptor current pointer
SharedMemoryBlock* descriptors_curr = descriptors_pub + block_index;
// Write to block
bool result = descriptors_curr->write_to_block(addr_pub[block_index], msg);
// Release reserve block, after we have wrote to block
descriptors_curr->release_reserve_for_radical_write();
// Check write result, if failed, return; if succeed, continue
if (!result)
{
return false;
}
// Set _wrote_num to current
set_wrote_num(block_index);
// Publisher wrote done, notify subscriber read
_wrote_num_cond.notify_all();
ROS_DEBUG("Write radical end! %d", block_index);
return true;
}
bool SharedMemorySegment::read_data(ros::VoidConstPtr& msg, int32_t& last_read_index,
SharedMemoryBlock* descriptors_sub, uint8_t** addr_sub,
ros::SubscriptionCallbackHelperPtr& helper, const std::string& topic,
ros::M_stringPtr& header_ptr)
{
ROS_DEBUG("Read radical start!");
int32_t block_index;
{
// Lock _wrote_num_mutex in segment
ROS_DEBUG("Lock _wrote_num_mutex in segment");
boost::interprocess::scoped_lock < boost::interprocess::interprocess_mutex >
segment_lock(_wrote_num_mutex);
// Block needs to be reallocated
if (_wrote_num == ROS_SHM_SEGMENT_WROTE_NUM)
{
last_read_index = _wrote_num;
return false;
}
// Block is not available for read, or block has been read
if (_wrote_num == -1 || _wrote_num == last_read_index)
{
ROS_DEBUG("Block %d is not available, or has been read", _wrote_num);
// Define wait timeout
boost::posix_time::ptime max_wait =
boost::posix_time::microsec_clock::universal_time() +
boost::posix_time::seconds(ROS_SHM_BLOCK_MUTEX_TIMEOUT_SEC);
// Wait publisher wrote timeout
if (!_wrote_num_cond.timed_wait(segment_lock, max_wait))
{
ROS_DEBUG("Wait radical publisher wrote topic %s, block %d timeout",
topic.c_str(), _wrote_num);
return false;
}
}
// Reserve next readable block failed
if (!reserve_radical_readable_block(descriptors_sub))
{
return false;
}
// Reserve next readable block succeed
block_index = _wrote_num;
}
// Get descriptor current pointer
SharedMemoryBlock* descriptors_curr = descriptors_sub + block_index;
// Read from block
bool result = descriptors_curr->read_from_block(addr_sub[block_index], msg, helper, header_ptr);
// Release reserve block, after we have read from block
descriptors_curr->release_reserve_for_radical_read();
// Check read result, if failed, return; if succeed, continue
if (!result)
{
return false;
}
// Set last read num
last_read_index = block_index;
ROS_DEBUG("Read radical end! %d", block_index);
return true;
}
/**************************************************************************************
* Private function in SharedMemorySegment
**************************************************************************************/
int32_t SharedMemorySegment::reserve_radical_writable_block(uint32_t queue_size,
SharedMemoryBlock* descriptors_pub)
{
// Get current _wrote_num
int32_t wrote_curr = _wrote_num;
// First publish
if (wrote_curr == -1)
{
++wrote_curr;
return wrote_curr;
}
// Non-First publish
while (wrote_curr != ROS_SHM_SEGMENT_WROTE_NUM && ros::ok())
{
++wrote_curr;
// Find in cycle
if (wrote_curr >= (int32_t)queue_size)
{
wrote_curr = wrote_curr % queue_size;
}
if ((descriptors_pub + wrote_curr)->try_reserve_for_radical_write())
{
ROS_DEBUG("Reserve block %d succeed", wrote_curr);
return wrote_curr;
}
else
{
ROS_DEBUG("Reserve block %d failed", wrote_curr);
}
}
// ROS in not ok
return wrote_curr;
}
bool SharedMemorySegment::reserve_radical_readable_block(SharedMemoryBlock* descriptors_sub)
{
if ((descriptors_sub + _wrote_num)->try_reserve_for_radical_read())
{
ROS_DEBUG("Reserve block %d succeed", _wrote_num);
return true;
}
else
{
ROS_DEBUG("Reserve block %d failed", _wrote_num);
return false;
}
}
} // namespace sharedmem_transport
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/sharedmem_transport/sharedmem_publisher_impl.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sharedmem_transport/sharedmem_publisher_impl.h"
#include "ros/service.h"
#include "ros/ros.h"
namespace sharedmem_transport
{
SharedMemoryPublisherImpl::SharedMemoryPublisherImpl() :
_segment(NULL), _addr_pub(NULL)
{
}
SharedMemoryPublisherImpl::~SharedMemoryPublisherImpl()
{
// This just disconnect from the segment, any subscriber can still finish reading it
if (_segment)
{
delete _segment;
}
if (_addr_pub)
{
delete []_addr_pub;
}
}
bool SharedMemoryPublisherImpl::create_topic_segement(
const std::string& topic, int32_t& index, uint32_t queue_size, uint64_t msg_size,
uint64_t& real_alloc_size, std::string datatype, std::string md5sum, std::string msg_def)
{
// Check if size_ratio is valid
if (!check_size_ratio())
{
ROS_FATAL("Size ratio is invalid");
return false;
}
// Get segment size
uint64_t segment_size = ROS_SHM_BLOCK_SIZE_RATIO * queue_size * (msg_size + ROS_SHM_BLOCK_SIZE)
+ ROS_SHM_SEGMENT_SIZE;
if (topic.length() >= ROS_SHM_UTIL_SEGMENT_NAME_SIZE)
{
ROS_ERROR("Topic name length overflow");
return false;
}
ROS_DEBUG("segment_size %ld, queue_size %d, msg_size %ld",
segment_size, queue_size, msg_size);
SharedMemoryUtil sharedmem_util;
// Create segment
_segment = sharedmem_util.create_segment(topic.c_str(), segment_size);
// Create segment mgr
_segment_mgr = sharedmem_util.create_segment_mgr(_segment);
ROS_DEBUG("Created segment %p, segment mgr %p", _segment, _segment_mgr);
// Init all blocks from publisher
_addr_pub = new uint8_t*[queue_size];
if (!_segment || !_segment_mgr || !_addr_pub)
{
ROS_ERROR("Connected to SHM failed");
delete _segment;
_segment = NULL;
index = -1;
if (_addr_pub)
{
delete []_addr_pub;
_addr_pub = NULL;
}
return false;
}
try
{
sharedmem_util.set_datatype(_segment, datatype);
sharedmem_util.set_md5sum(_segment, md5sum);
sharedmem_util.set_msg_def(_segment, msg_def);
} catch (boost::interprocess::interprocess_exception& e)
{
ROS_ERROR("SHM save field failed");
}
return _segment_mgr->init_all_blocks(*_segment, queue_size, msg_size, real_alloc_size,
_descriptors_pub, _addr_pub);
}
bool SharedMemoryPublisherImpl::check_size_ratio()
{
if (ROS_SHM_BLOCK_SIZE_RATIO < 1.0)
{
ROS_ERROR("ROS_SHM_BLOCK_SIZE_RATIO %f is invalid, suggest [1.0, 3.0]",
ROS_SHM_BLOCK_SIZE_RATIO);
return false;
}
if (ROS_SHM_BLOCK_SIZE_RATIO > 3.0)
{
ROS_WARN("ROS_SHM_BLOCK_SIZE_RATIO %f is invalid, suggest [1.0, 3.0]",
ROS_SHM_BLOCK_SIZE_RATIO);
}
return true;
}
} // namespace sharedmem_transport
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/sharedmem_transport/sharedmem_util.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sharedmem_transport/sharedmem_util.h"
namespace sharedmem_transport
{
/**************************************************************************************
* Public function in SharedMemoryUtil
**************************************************************************************/
bool SharedMemoryUtil::init_sharedmem(const char* topic_name,
boost::interprocess::managed_shared_memory*& segment,
sharedmem_transport::SharedMemorySegment*& segment_mgr,
sharedmem_transport::SharedMemoryBlock*& descriptors,
uint32_t& queue_size)
{
char segment_name[ROS_SHM_UTIL_SEGMENT_NAME_SIZE];
get_segment_name(topic_name, segment_name);
try
{
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_only, segment_name);
} catch (boost::interprocess::interprocess_exception e)
{
return false;
}
if (!segment)
{
return false;
}
segment_mgr = (segment->find < SharedMemorySegment > ("Manager")).first;
std::pair<SharedMemoryBlock*, std::size_t> descriptors_block(NULL, 0);
descriptors_block = segment->find < SharedMemoryBlock > ("BlockDescriptor");
descriptors = descriptors_block.first;
queue_size = descriptors_block.second;
if (!segment_mgr || !descriptors)
{
delete segment;
return false;
}
return true;
}
boost::interprocess::managed_shared_memory* SharedMemoryUtil::get_segment(const char* topic_name)
{
ROS_DEBUG("Get segment");
char segment_name[ROS_SHM_UTIL_SEGMENT_NAME_SIZE];
get_segment_name(topic_name, segment_name);
ROS_DEBUG("get segment topic name: %s", topic_name);
boost::interprocess::managed_shared_memory* segment = NULL;
try
{
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_only, segment_name);
} catch (boost::interprocess::interprocess_exception e)
{
ROS_DEBUG("segment is null");
}
return segment;
}
boost::interprocess::managed_shared_memory* SharedMemoryUtil::create_segment(
const char* topic_name, uint64_t segment_size)
{
ROS_DEBUG("Create segment");
char segment_name[ROS_SHM_UTIL_SEGMENT_NAME_SIZE];
get_segment_name(topic_name, segment_name);
boost::interprocess::managed_shared_memory* segment = NULL;
try
{
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_or_create, segment_name, segment_size);
} catch (boost::interprocess::interprocess_exception e)
{
ROS_ERROR_STREAM("Create segment failed" << topic_name);
}
return segment;
}
SharedMemorySegment* SharedMemoryUtil::get_segment_mgr(
boost::interprocess::managed_shared_memory*& segment)
{
ROS_DEBUG("Connected to segment_mgr");
SharedMemorySegment* segment_mgr = NULL;
if (!segment)
{
ROS_ERROR("Segment is NULL");
return segment_mgr;
}
segment_mgr = (segment->find < SharedMemorySegment > ("Manager")).first;
return segment_mgr;
}
SharedMemorySegment* SharedMemoryUtil::create_segment_mgr(
boost::interprocess::managed_shared_memory*& segment)
{
ROS_DEBUG("Create segment_mgr");
SharedMemorySegment* segment_mgr = NULL;
if (!segment)
{
ROS_ERROR("Segment is NULL");
return segment_mgr;
}
segment_mgr = segment->find_or_construct < SharedMemorySegment > ("Manager")();
return segment_mgr;
}
bool SharedMemoryUtil::remove_segment(const char* topic_name)
{
ROS_DEBUG("Remove segment %s", topic_name);
char segment_name[ROS_SHM_UTIL_SEGMENT_NAME_SIZE];
get_segment_name(topic_name, segment_name);
bool status = false;
try
{
status = boost::interprocess::shared_memory_object::remove(segment_name);
} catch (boost::interprocess::interprocess_exception e)
{
ROS_ERROR_STREAM("Delete segment failed" << topic_name);
}
return status;
}
void SharedMemoryUtil::set_datatype(boost::interprocess::managed_shared_memory*& segment, std::string content)
{
set_segment_string(segment, "datatype", content);
}
std::string SharedMemoryUtil::get_datatype(boost::interprocess::managed_shared_memory*& segment)
{
return get_segment_string(segment, "datatype");
}
void SharedMemoryUtil::set_md5sum(boost::interprocess::managed_shared_memory*& segment, std::string content)
{
set_segment_string(segment, "md5sum", content);
}
std::string SharedMemoryUtil::get_md5sum(boost::interprocess::managed_shared_memory*& segment)
{
return get_segment_string(segment, "md5sum");
}
void SharedMemoryUtil::set_msg_def(boost::interprocess::managed_shared_memory*& segment, std::string content)
{
set_segment_string(segment, "msg_def", content);
}
std::string SharedMemoryUtil::get_msg_def(boost::interprocess::managed_shared_memory*& segment)
{
return get_segment_string(segment, "msg_def");
}
/**************************************************************************************
* Private function in SharedMemoryUtil
**************************************************************************************/
void SharedMemoryUtil::set_segment_string(boost::interprocess::managed_shared_memory*& segment,
std::string string_name, std::string string_content)
{
segment->find_or_construct<SHMString>(string_name.c_str())(string_content.c_str(), segment->get_segment_manager());
}
std::string SharedMemoryUtil::get_segment_string(boost::interprocess::managed_shared_memory*& segment,
std::string string_name)
{
std::pair<SHMString*, size_t> p = segment->find<SHMString>(string_name.c_str());
if (!p.first)
{
return NULL;
}
return p.first->c_str();
}
void SharedMemoryUtil::get_segment_name(const char* topic_name, char* segment_name)
{
if (strlen(topic_name) >= ROS_SHM_UTIL_SEGMENT_NAME_SIZE)
{
ROS_ERROR("Topic name length overflow");
return;
}
snprintf(segment_name, ROS_SHM_UTIL_SEGMENT_NAME_SIZE, "%s", topic_name);
replace_all(segment_name, '/', ':');
}
char* SharedMemoryUtil::replace_all(char* src, char old_char, char new_char)
{
char* head = src;
int size = strlen(src);
for (int i = 0; i < size; ++i)
{
if (*src == old_char)
{
*src = new_char;
}
++src;
}
return head;
}
} // namespace sharedmem_transport
extern "C"
bool remove_segment(const char* topic_name)
{
sharedmem_transport::SharedMemoryUtil shm_util;
return shm_util.remove_segment(topic_name);
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/discovery/MetaMessage.idl | struct MetaMessage {
unsigned long message_id;
string data;
};
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/discovery/participant.cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, The Apollo Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "discovery/participant.h"
#include "ros/platform.h"
#include <string>
#include <vector>
namespace ros
{
bool Participant::init_py()
{
auto cb = [this] (const std::string& msg) {this->cache_msg(msg);};
init(cb);
return true;
}
void Participant::cache_msg(const std::string& msg)
{
{
std::lock_guard<std::mutex> lg(_msg_lock);
_unread_msg.push_back(msg);
}
_msg_cond.notify_one();
}
std::string Participant::read_msg()
{
std::string msg = "";
std::unique_lock<std::mutex> ul(_msg_lock);
if (_unread_msg.size() > 0)
{
msg = std::move(_unread_msg.front());
_unread_msg.pop_front();
return msg;
}
_msg_cond.wait(ul, [this]{return !this->_unread_msg.empty();});
if (_unread_msg.size() > 0)
{
msg = std::move(_unread_msg.front());
_unread_msg.pop_front();
}
return msg;
}
bool Participant::init(user_callback cb)
{
if (_inited)
{
return false;
}
std::string topic("ros_meta");
std::string data_type("MetaMessage");
int domain_id = 50000;
const char *val = ::getenv("ROS_DOMAIN_ID");
if (val != NULL)
{
try
{
domain_id = std::stoi(val);
}
catch (std::exception const &e)
{
//using default domain_id.
}
}
eprosima::fastrtps::ParticipantAttributes participant_param;
participant_param.rtps.defaultSendPort = 50000;
participant_param.rtps.use_IP6_to_send = false;
participant_param.rtps.builtin.use_SIMPLE_RTPSParticipantDiscoveryProtocol = true;
participant_param.rtps.builtin.use_SIMPLE_EndpointDiscoveryProtocol = true;
participant_param.rtps.builtin.m_simpleEDP.use_PublicationReaderANDSubscriptionWriter = true;
participant_param.rtps.builtin.m_simpleEDP.use_PublicationWriterANDSubscriptionReader = true;
participant_param.rtps.builtin.domainId = domain_id;
participant_param.rtps.builtin.leaseDuration = c_TimeInfinite;
participant_param.rtps.builtin.leaseDuration_announcementperiod.seconds = 3;
participant_param.rtps.setName(_name.c_str());
// set unicast ip
std::string ip_env;
if (get_environment_variable(ip_env, "ROS_IP"))
{
if (ip_env.size() == 0)
{
std::cerr << "invalid ROS_IP (an empty string)" << std::endl;
}
eprosima::fastrtps::Locator_t locator;
locator.port = 0; //RTPS
locator.set_IP4_address(ip_env);
locator.kind = LOCATOR_KIND_UDPv4;
participant_param.rtps.defaultUnicastLocatorList.push_back(locator);
participant_param.rtps.defaultOutLocatorList.push_back(locator);
participant_param.rtps.builtin.metatrafficUnicastLocatorList.push_back(locator);
locator.set_IP4_address(239, 255, 0, 1);
participant_param.rtps.builtin.metatrafficMulticastLocatorList.push_back(locator);
}
_participant = Domain::createParticipant(participant_param);
if (_participant == nullptr)
{
std::cerr << "Create participant failed." << std::endl;
return false;
}
Domain::registerType(_participant, &_type);
//Create publisher
eprosima::fastrtps::PublisherAttributes pub_param;
pub_param.topic.topicName = topic;
pub_param.topic.topicDataType = data_type;
pub_param.historyMemoryPolicy = DYNAMIC_RESERVE_MEMORY_MODE;
pub_param.topic.topicKind = NO_KEY;
pub_param.topic.historyQos.kind = KEEP_ALL_HISTORY_QOS;
pub_param.qos.m_durability.kind = TRANSIENT_LOCAL_DURABILITY_QOS;
pub_param.qos.m_reliability.kind = RELIABLE_RELIABILITY_QOS;
pub_param.topic.historyQos.depth = 5000;
pub_param.topic.resourceLimitsQos.max_samples = 10000;
pub_param.times.heartbeatPeriod.seconds = 2;
pub_param.times.heartbeatPeriod.fraction = 0;
_meta_publisher = Domain::createPublisher(_participant, pub_param, &_pub_listener);
if (_meta_publisher == nullptr)
{
Domain::removeParticipant(_participant);
_participant = nullptr;
std::cerr << "Create publisher failed." << std::endl;
return false;
}
// create listener
eprosima::fastrtps::rtps::GUID_t guid = _meta_publisher->getGuid();
_meta_listener = new Listener(guid);
if (!_meta_listener) {
Domain::removeParticipant(_participant);
_participant = nullptr;
std::cerr << "Create subsciber listener failed." << std::endl;
return false;
}
_meta_listener->register_callback(cb);
eprosima::fastrtps::SubscriberAttributes sub_param;
sub_param.topic.topicName = topic;
sub_param.topic.topicDataType = data_type;
sub_param.historyMemoryPolicy = DYNAMIC_RESERVE_MEMORY_MODE;
sub_param.topic.topicKind = NO_KEY;
sub_param.topic.historyQos.kind = KEEP_ALL_HISTORY_QOS;
sub_param.qos.m_durability.kind = TRANSIENT_LOCAL_DURABILITY_QOS;
sub_param.qos.m_reliability.kind = RELIABLE_RELIABILITY_QOS;
sub_param.topic.historyQos.depth = 5000;
sub_param.topic.resourceLimitsQos.max_samples = 10000;
_meta_subscriber = Domain::createSubscriber(_participant, sub_param, _meta_listener);
if (_meta_subscriber == nullptr)
{
Domain::removeParticipant(_participant);
_participant = nullptr;
delete _meta_listener;
_meta_listener = nullptr;
std::cerr << "Create subsciber failed." << std::endl;
return false;
}
return true;
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/discovery/MetaMessage.cxx | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*!
* @file MetaMessage.cpp
* This source file contains the definition of the described types in the IDL file.
*
* This file was generated by the tool gen.
*/
#ifdef _WIN32
// Remove linker warning LNK4221 on Visual Studio
namespace { char dummy; }
#endif
#include "discovery/MetaMessage.h"
#include <fastcdr/Cdr.h>
#include <fastcdr/exceptions/BadParamException.h>
using namespace eprosima::fastcdr::exception;
#include <utility>
MetaMessage::MetaMessage()
{
m_message_id = 0;
}
MetaMessage::~MetaMessage()
{
}
MetaMessage::MetaMessage(const MetaMessage &x)
{
m_message_id = x.m_message_id;
m_data = x.m_data;
}
MetaMessage::MetaMessage(MetaMessage &&x)
{
m_message_id = x.m_message_id;
m_data = std::move(x.m_data);
}
MetaMessage& MetaMessage::operator=(const MetaMessage &x)
{
m_message_id = x.m_message_id;
m_data = x.m_data;
return *this;
}
MetaMessage& MetaMessage::operator=(MetaMessage &&x)
{
m_message_id = x.m_message_id;
m_data = std::move(x.m_data);
return *this;
}
size_t MetaMessage::getMaxCdrSerializedSize(size_t current_alignment)
{
size_t initial_alignment = current_alignment;
current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4);
current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4) + 8192 + 1;
return current_alignment - initial_alignment;
}
size_t MetaMessage::getCdrSerializedSize(const MetaMessage& data, size_t current_alignment)
{
size_t initial_alignment = current_alignment;
current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4);
current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4) + data.data().size() + 1;
return current_alignment - initial_alignment;
}
void MetaMessage::serialize(eprosima::fastcdr::Cdr &scdr) const
{
scdr << m_message_id;
if(m_data.length() <= 8192)
scdr << m_data;
else
throw eprosima::fastcdr::exception::BadParamException("data field exceeds the maximum length");
}
void MetaMessage::deserialize(eprosima::fastcdr::Cdr &dcdr)
{
dcdr >> m_message_id;
dcdr >> m_data;
}
size_t MetaMessage::getKeyMaxCdrSerializedSize(size_t current_alignment)
{
size_t current_align = current_alignment;
return current_align;
}
bool MetaMessage::isKeyDefined()
{
return false;
}
void MetaMessage::serializeKey(eprosima::fastcdr::Cdr &scdr) const
{
(void)scdr;
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros | apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/discovery/MetaMessagePubSubTypes.cxx | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*!
* @file MetaMessagePubSubTypes.cpp
* This header file contains the implementation of the serialization functions.
*
* This file was generated by the tool fastcdrgen.
*/
#include <fastcdr/FastBuffer.h>
#include <fastcdr/Cdr.h>
#include "discovery/MetaMessagePubSubTypes.h"
MetaMessagePubSubType::MetaMessagePubSubType() {
setName("MetaMessage");
m_typeSize = (uint32_t)MetaMessage::getMaxCdrSerializedSize() + 4 /*encapsulation*/;
m_isGetKeyDefined = MetaMessage::isKeyDefined();
m_keyBuffer = (unsigned char*)malloc(MetaMessage::getKeyMaxCdrSerializedSize()>16 ? MetaMessage::getKeyMaxCdrSerializedSize() : 16);
}
MetaMessagePubSubType::~MetaMessagePubSubType() {
if(m_keyBuffer!=nullptr)
free(m_keyBuffer);
}
bool MetaMessagePubSubType::serialize(void *data, SerializedPayload_t *payload) {
MetaMessage *p_type = (MetaMessage*) data;
eprosima::fastcdr::FastBuffer fastbuffer((char*) payload->data, payload->max_size); // Object that manages the raw buffer.
eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN,
eprosima::fastcdr::Cdr::DDS_CDR); // Object that serializes the data.
payload->encapsulation = ser.endianness() == eprosima::fastcdr::Cdr::BIG_ENDIANNESS ? CDR_BE : CDR_LE;
// Serialize encapsulation
ser.serialize_encapsulation();
p_type->serialize(ser); // Serialize the object:
payload->length = (uint32_t)ser.getSerializedDataLength(); //Get the serialized length
return true;
}
bool MetaMessagePubSubType::deserialize(SerializedPayload_t* payload, void* data) {
MetaMessage* p_type = (MetaMessage*) data; //Convert DATA to pointer of your type
eprosima::fastcdr::FastBuffer fastbuffer((char*)payload->data, payload->length); // Object that manages the raw buffer.
eprosima::fastcdr::Cdr deser(fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN,
eprosima::fastcdr::Cdr::DDS_CDR); // Object that deserializes the data.
// Deserialize encapsulation.
deser.read_encapsulation();
payload->encapsulation = deser.endianness() == eprosima::fastcdr::Cdr::BIG_ENDIANNESS ? CDR_BE : CDR_LE;
p_type->deserialize(deser); //Deserialize the object:
return true;
}
std::function<uint32_t()> MetaMessagePubSubType::getSerializedSizeProvider(void* data) {
return [data]() -> uint32_t
{
return (uint32_t)type::getCdrSerializedSize(*static_cast<MetaMessage*>(data)) + 4 /*encapsulation*/;
};
}
void* MetaMessagePubSubType::createData() {
return (void*)new MetaMessage();
}
void MetaMessagePubSubType::deleteData(void* data) {
delete((MetaMessage*)data);
}
bool MetaMessagePubSubType::getKey(void *data, InstanceHandle_t* handle) {
if(!m_isGetKeyDefined)
return false;
MetaMessage* p_type = (MetaMessage*) data;
eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,MetaMessage::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer.
eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data.
p_type->serializeKey(ser);
if(MetaMessage::getKeyMaxCdrSerializedSize()>16) {
m_md5.init();
m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength());
m_md5.finalize();
for(uint8_t i = 0;i<16;++i) {
handle->value[i] = m_md5.digest[i];
}
}
else {
for(uint8_t i = 0;i<16;++i) {
handle->value[i] = m_keyBuffer[i];
}
}
return true;
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/index.rst | Message Filters --- chained message processing
==============================================
:mod:`message_filters` is a collection of message "filters" which take messages in,
either from a ROS subscription or another filter,
and may or may not output the message
at some time in the future, depending on a policy defined for that filter.
message_filters also defines a common interface for these filters, allowing you to chain them together.
The filters currently implemented in this package are:
* :class:`message_filters.Subscriber` - A source filter, which wraps a ROS subscription. Most filter chains will begin with a Subscriber.
* :class:`message_filters.Cache` - Caches messages which pass through it, allowing later lookup by time stamp.
* :class:`message_filters.TimeSynchronizer` - Synchronizes multiple messages by their timestamps, only passing them through when all have arrived.
* :class:`message_filters.TimeSequencer` - Tries to pass messages through ordered by their timestamps, even if some arrive out of order.
Here's a simple example of using a Subscriber with a Cache::
def myCallback(posemsg):
print posemsg
sub = message_filters.Subscriber("pose_topic", robot_msgs.msg.Pose)
cache = message_filters.Cache(sub, 10)
cache.registerCallback(myCallback)
The Subscriber here acts as the source of messages. Each message is passed to the cache, which then passes it through to the
user's callback ``myCallback``.
Using the time synchronizer::
from message_filters import TimeSynchronizer, Subscriber
def gotimage(image, camerainfo):
assert image.header.stamp == camerainfo.header.stamp
print "got an Image and CameraInfo"
tss = TimeSynchronizer(Subscriber("/wide_stereo/left/image_rect_color", sensor_msgs.msg.Image),
Subscriber("/wide_stereo/left/camera_info", sensor_msgs.msg.CameraInfo))
tss.registerCallback(gotimage)
The message filter interface
----------------------------
For an object to be usable as a message filter, it needs to have one method,
``registerCallback``. To collect messages from a message filter, register a callback with::
anyfilter.registerCallback(my_callback)
The signature of ``my_callback`` varies according to the message filter. For many filters it is simply::
def my_callback(msg):
where ``msg`` is the message.
Message filters that accept input from an upstream
message filter (e.g. :class:`message_filters.Cache`) register their own
message handler as a callback.
Output connections are registered through the ``registerCallback()`` function.
.. automodule:: message_filters
:members: Subscriber, Cache, TimeSynchronizer, TimeSequencer
:inherited-members:
Indices and tables
==================
* :ref:`genindex`
* :ref:`search`
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(message_filters)
if(NOT WIN32)
set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra")
endif()
find_package(catkin REQUIRED COMPONENTS roscpp xmlrpcpp rosconsole)
catkin_package(
INCLUDE_DIRS include
LIBRARIES message_filters
CATKIN_DEPENDS roscpp xmlrpcpp rosconsole
)
catkin_python_setup()
find_package(Boost REQUIRED COMPONENTS signals thread)
include_directories(include ${catkin_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
link_directories(${catkin_LIBRARY_DIRS})
add_library(${PROJECT_NAME} src/connection.cpp)
target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${Boost_LIBRARIES})
install(TARGETS ${PROJECT_NAME}
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h")
if(CATKIN_ENABLE_TESTING)
# Ugly workaround for check_test_ran macro issue
#add_subdirectory(test)
find_package(catkin COMPONENTS rostest rosunit)
include_directories(${GTEST_INCLUDE_DIRS})
# ********** Tests **********
catkin_add_gtest(${PROJECT_NAME}-msg_cache_unittest test/msg_cache_unittest.cpp)
if(TARGET ${PROJECT_NAME}-msg_cache_unittest)
target_link_libraries(${PROJECT_NAME}-msg_cache_unittest message_filters ${GTEST_LIBRARIES})
endif()
catkin_add_gtest(${PROJECT_NAME}-time_synchronizer_unittest test/time_synchronizer_unittest.cpp)
if(TARGET ${PROJECT_NAME}-time_synchronizer_unittest)
target_link_libraries(${PROJECT_NAME}-time_synchronizer_unittest message_filters ${GTEST_LIBRARIES})
endif()
catkin_add_gtest(${PROJECT_NAME}-test_synchronizer test/test_synchronizer.cpp)
if(TARGET ${PROJECT_NAME}-test_synchronizer)
target_link_libraries(${PROJECT_NAME}-test_synchronizer message_filters ${GTEST_LIBRARIES})
endif()
catkin_add_gtest(${PROJECT_NAME}-test_exact_time_policy test/test_exact_time_policy.cpp)
if(TARGET ${PROJECT_NAME}-test_exact_time_policy)
target_link_libraries(${PROJECT_NAME}-test_exact_time_policy message_filters ${GTEST_LIBRARIES})
endif()
catkin_add_gtest(${PROJECT_NAME}-test_approximate_time_policy test/test_approximate_time_policy.cpp)
if(TARGET ${PROJECT_NAME}-test_approximate_time_policy)
target_link_libraries(${PROJECT_NAME}-test_approximate_time_policy message_filters ${GTEST_LIBRARIES})
endif()
catkin_add_gtest(${PROJECT_NAME}-test_simple test/test_simple.cpp)
if(TARGET ${PROJECT_NAME}-test_simple)
target_link_libraries(${PROJECT_NAME}-test_simple message_filters ${GTEST_LIBRARIES})
endif()
catkin_add_gtest(${PROJECT_NAME}-test_chain test/test_chain.cpp)
if(TARGET ${PROJECT_NAME}-test_chain)
target_link_libraries(${PROJECT_NAME}-test_chain message_filters ${GTEST_LIBRARIES})
endif()
# Needs to be a rostest because it spins up a node, which blocks until it hears from the master (unfortunately)
add_rostest_gtest(${PROJECT_NAME}-time_sequencer_unittest test/time_sequencer_unittest.xml test/time_sequencer_unittest.cpp)
if(TARGET ${PROJECT_NAME}-time_sequencer_unittest)
target_link_libraries(${PROJECT_NAME}-time_sequencer_unittest message_filters)
endif()
add_rostest_gtest(${PROJECT_NAME}-test_subscriber test/test_subscriber.xml test/test_subscriber.cpp)
if(TARGET ${PROJECT_NAME}-test_subscriber)
target_link_libraries(${PROJECT_NAME}-test_subscriber message_filters)
endif()
# Unit test of the approximate synchronizer
catkin_add_nosetests(test/test_approxsync.py)
catkin_add_nosetests(test/test_message_filters_cache.py)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/package.xml | <package>
<name>message_filters</name>
<version>1.11.21</version>
<description>
A set of message filters which take in messages and may output those messages at a later time, based on the conditions that filter needs met.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/message_filters</url>
<author>Josh Faust</author>
<author>Vijay Pradeep</author>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>boost</build_depend>
<build_depend>rosconsole</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>rostest</build_depend>
<build_depend>rosunit</build_depend>
<build_depend>xmlrpcpp</build_depend>
<run_depend>rosconsole</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>xmlrpcpp</run_depend>
<export>
<rosdoc config="rosdoc.yaml"/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/conf.py | # -*- coding: utf-8 -*-
#
# message_filters documentation build configuration file, created by
# sphinx-quickstart on Mon Jun 1 14:21:53 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.pngmath']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'message_filters'
copyright = u'2009, Willow Garage, Inc.'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
exclude_patterns = ['CHANGELOG.rst']
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'tfdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'message_filters.tex', u'stereo\\_utils Documentation',
u'James Bowman', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'http://docs.python.org/': None,
'http://docs.scipy.org/doc/numpy' : None
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/mainpage.dox | /**
\mainpage
\htmlinclude manifest.html
\b message_filters is a set of message "filters" which take messages in, usually through a callback from somewhere else,
and may or may not spit them out at some time in the future, depending on the conditions which need to be met for that
filter to do so.
\b message_filters also sets up a common pattern for these filters, allowing you to chain them together, even though they
have no explicit base class.
\section codeapi Code API
The filters currently implemented in this package are:
- message_filters::Subscriber - A source filter, which wraps a ROS subscription. Most filter chains will begin with a Subscriber.
- message_filters::Cache - Caches messages which pass through it, allowing later lookup by time stamp.
- message_filters::TimeSynchronizer - Synchronizes multiple messages by their timestamps, only passing them through when all have arrived.
- message_filters::TimeSequencer - Tries to pass messages through ordered by their timestamps, even if some arrive out of order.
There is also a base-class provided for simple filters: message_filters::SimpleFilter. This provides callback management and disconnection
for any filter that derives from it. A simple filter is defined as one that outputs a single message. message_filters::SimpleFilter provides
the registerCallback() method for any of its derived classes. message_filters::Subscriber, message_filters::Cache and message_filters::TimeSequencer
are all derived from message_filters::SimpleFilter.
Here's a simple example of using a Subscriber with a Cache:
\verbatim
void myCallback(const robot_msgs::Pose::ConstPtr& pose)
{}
ros::NodeHandle nh;
message_filters::Subscriber<robot_msgs::Pose> sub(nh, "pose_topic", 1);
message_filters::Cache<robot_msgs::Pose> cache(sub, 10);
cache.registerCallback(myCallback);
\endverbatim
The Subscriber here acts as the source of messages. Each message is passed to the cache, which then passes it through to the
user's callback (myCallback)
\section connections CONNECTIONS
Every filter can have up to two types of connections, input and output. Source filters (such as message_filters::Subscriber) only
have output connections, whereas most other filters have both input and output connections.
The two connection types do not have to be identical. For example, message_filters::TimeSynchronizer's input connection takes one
parameter, but its output connection has somewhere between 2 and 9 parameters, depending on the number of connections being
synchronized.
Input connections are registered either in the filter's constructor, or by calling connectInput() on the filter. For example:
\verbatim
message_filters::Cache<robot_msgs::Pose> cache(10);
cache.connectInput(sub);
\endverbatim
This connects cache's input to sub's output.
Output connections are registered through the registerCallback() function.
*/ | 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/rosdoc.yaml | - builder: sphinx
name: Python API
output_dir: python
- builder: doxygen
name: C++ API
output_dir: c++
file_patterns: '*.c *.cpp *.h *.cc *.hh *.dox'
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/setup.py | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['message_filters'],
package_dir={'': 'src'},
requires=['genmsg', 'genpy', 'roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/message_filters/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-message_filters-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package message_filters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.21 (2017-03-06)
--------------------
1.11.20 (2016-06-27)
--------------------
1.11.19 (2016-04-18)
--------------------
* use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_)
1.11.18 (2016-03-17)
--------------------
* fix compiler warnings
1.11.17 (2016-03-11)
--------------------
* use boost::make_shared instead of new for constructing boost::shared_ptr (`#740 <https://github.com/ros/ros_comm/issues/740>`_)
* add __getattr_\_ to handle sub in message_filters as standard one (`#700 <https://github.com/ros/ros_comm/pull/700>`_)
1.11.16 (2015-11-09)
--------------------
1.11.15 (2015-10-13)
--------------------
* add unregister() method to message_filter.Subscriber (`#683 <https://github.com/ros/ros_comm/pull/683>`_)
1.11.14 (2015-09-19)
--------------------
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
* implement message filter cache in Python (`#599 <https://github.com/ros/ros_comm/pull/599>`_)
1.11.10 (2014-12-22)
--------------------
1.11.9 (2014-08-18)
-------------------
1.11.8 (2014-08-04)
-------------------
1.11.7 (2014-07-18)
-------------------
1.11.6 (2014-07-10)
-------------------
1.11.5 (2014-06-24)
-------------------
1.11.4 (2014-06-16)
-------------------
* add approximate Python time synchronizer (used to be in camera_calibration) (`#424 <https://github.com/ros/ros_comm/issues/424>`_)
1.11.3 (2014-05-21)
-------------------
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* update API to use boost::signals2 (`#267 <https://github.com/ros/ros_comm/issues/267>`_)
1.11.0 (2014-03-04)
-------------------
* suppress boost::signals deprecation warning (`#362 <https://github.com/ros/ros_comm/issues/362>`_)
1.10.0 (2014-02-11)
-------------------
1.9.54 (2014-01-27)
-------------------
1.9.53 (2014-01-14)
-------------------
* add kwargs for message_filters.Subscriber
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
* update code after refactoring into rosbag_storage and roscpp_core (`#299 <https://github.com/ros/ros_comm/issues/299>`_)
* fix segmentation fault on OS X 10.9 (clang / libc++)
1.9.50 (2013-10-04)
-------------------
1.9.49 (2013-09-16)
-------------------
1.9.48 (2013-08-21)
-------------------
1.9.47 (2013-07-03)
-------------------
* check for CATKIN_ENABLE_TESTING to enable configure without tests
1.9.46 (2013-06-18)
-------------------
1.9.45 (2013-06-06)
-------------------
* fix template syntax for signal\_.template addCallback() to work with Intel compiler
1.9.44 (2013-03-21)
-------------------
* fix install destination for dll's under Windows
1.9.43 (2013-03-13)
-------------------
* fix exports of message filter symbols for Windows
1.9.42 (2013-03-08)
-------------------
1.9.41 (2013-01-24)
-------------------
1.9.40 (2013-01-13)
-------------------
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_approxsync.py | #!/usr/bin/env python
#
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Willow Garage nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import rostest
import rospy
import unittest
import random
import message_filters
from message_filters import ApproximateTimeSynchronizer
class MockHeader:
pass
class MockMessage:
def __init__(self, stamp, data):
self.header = MockHeader()
self.header.stamp = stamp
self.data = data
class MockFilter(message_filters.SimpleFilter):
pass
class TestApproxSync(unittest.TestCase):
def cb_collector_2msg(self, msg1, msg2):
self.collector.append((msg1, msg2))
def test_approx(self):
m0 = MockFilter()
m1 = MockFilter()
ts = ApproximateTimeSynchronizer([m0, m1], 1, 0.1)
ts.registerCallback(self.cb_collector_2msg)
if 0:
# Simple case, pairs of messages, make sure that they get combined
for t in range(10):
self.collector = []
msg0 = MockMessage(t, 33)
msg1 = MockMessage(t, 34)
m0.signalMessage(msg0)
self.assertEqual(self.collector, [])
m1.signalMessage(msg1)
self.assertEqual(self.collector, [(msg0, msg1)])
# Scramble sequences of length N. Make sure that TimeSequencer recombines them.
random.seed(0)
for N in range(1, 10):
m0 = MockFilter()
m1 = MockFilter()
seq0 = [MockMessage(rospy.Time(t), random.random()) for t in range(N)]
seq1 = [MockMessage(rospy.Time(t), random.random()) for t in range(N)]
# random.shuffle(seq0)
ts = ApproximateTimeSynchronizer([m0, m1], N, 0.1)
ts.registerCallback(self.cb_collector_2msg)
self.collector = []
for msg in random.sample(seq0, N):
m0.signalMessage(msg)
self.assertEqual(self.collector, [])
for msg in random.sample(seq1, N):
m1.signalMessage(msg)
self.assertEqual(set(self.collector), set(zip(seq0, seq1)))
if __name__ == '__main__':
if 1:
rostest.unitrun('camera_calibration', 'testapproxsync', TestApproxSync)
else:
suite = unittest.TestSuite()
suite.addTest(TestApproxSync('test_approx'))
unittest.TextTestRunner(verbosity=2).run(suite)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_chain.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include <ros/init.h>
#include "message_filters/chain.h"
using namespace message_filters;
struct Msg
{
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
class Helper
{
public:
Helper()
: count_(0)
{}
void cb()
{
++count_;
}
int32_t count_;
};
typedef boost::shared_ptr<PassThrough<Msg> > PassThroughPtr;
TEST(Chain, simple)
{
Helper h;
Chain<Msg> c;
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.registerCallback(boost::bind(&Helper::cb, &h));
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 1);
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 2);
}
TEST(Chain, multipleFilters)
{
Helper h;
Chain<Msg> c;
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.registerCallback(boost::bind(&Helper::cb, &h));
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 1);
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 2);
}
TEST(Chain, addingFilters)
{
Helper h;
Chain<Msg> c;
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.registerCallback(boost::bind(&Helper::cb, &h));
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 1);
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 2);
}
TEST(Chain, inputFilter)
{
Helper h;
Chain<Msg> c;
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.registerCallback(boost::bind(&Helper::cb, &h));
PassThrough<Msg> p;
c.connectInput(p);
p.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 1);
p.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 2);
}
TEST(Chain, nonSharedPtrFilter)
{
Helper h;
Chain<Msg> c;
PassThrough<Msg> p;
c.addFilter(&p);
c.registerCallback(boost::bind(&Helper::cb, &h));
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 1);
c.add(boost::make_shared<Msg>());
EXPECT_EQ(h.count_, 2);
}
TEST(Chain, retrieveFilter)
{
Chain<Msg> c;
ASSERT_FALSE(c.getFilter<PassThrough<Msg> >(0));
c.addFilter(boost::make_shared<PassThrough<Msg> >());
ASSERT_TRUE(c.getFilter<PassThrough<Msg> >(0));
ASSERT_FALSE(c.getFilter<PassThrough<Msg> >(1));
}
TEST(Chain, retrieveFilterThroughBaseClass)
{
Chain<Msg> c;
ChainBase* cb = &c;
ASSERT_FALSE(cb->getFilter<PassThrough<Msg> >(0));
c.addFilter(boost::make_shared<PassThrough<Msg> >());
ASSERT_TRUE(cb->getFilter<PassThrough<Msg> >(0));
ASSERT_FALSE(cb->getFilter<PassThrough<Msg> >(1));
}
struct PTDerived : public PassThrough<Msg>
{
};
TEST(Chain, retrieveBaseClass)
{
Chain<Msg> c;
c.addFilter(boost::make_shared<PTDerived>());
ASSERT_TRUE(c.getFilter<PassThrough<Msg> >(0));
ASSERT_TRUE(c.getFilter<PTDerived>(0));
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_subscriber.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include "roscpp/Logger.h"
#include "message_filters/subscriber.h"
#include "message_filters/chain.h"
using namespace message_filters;
typedef roscpp::Logger Msg;
typedef roscpp::LoggerPtr MsgPtr;
typedef roscpp::LoggerConstPtr MsgConstPtr;
class Helper
{
public:
Helper()
: count_(0)
{}
void cb(const MsgConstPtr&)
{
++count_;
}
int32_t count_;
};
TEST(Subscriber, simple)
{
ros::NodeHandle nh;
Helper h;
Subscriber<Msg> sub(nh, "test_topic", 0);
sub.registerCallback(boost::bind(&Helper::cb, &h, _1));
ros::Publisher pub = nh.advertise<Msg>("test_topic", 0);
ros::Time start = ros::Time::now();
while (h.count_ == 0 && (ros::Time::now() - start) < ros::Duration(1.0))
{
pub.publish(Msg());
ros::Duration(0.01).sleep();
ros::spinOnce();
}
ASSERT_GT(h.count_, 0);
}
TEST(Subscriber, subUnsubSub)
{
ros::NodeHandle nh;
Helper h;
Subscriber<Msg> sub(nh, "test_topic", 0);
sub.registerCallback(boost::bind(&Helper::cb, &h, _1));
ros::Publisher pub = nh.advertise<Msg>("test_topic", 0);
sub.unsubscribe();
sub.subscribe();
ros::Time start = ros::Time::now();
while (h.count_ == 0 && (ros::Time::now() - start) < ros::Duration(1.0))
{
pub.publish(Msg());
ros::Duration(0.01).sleep();
ros::spinOnce();
}
ASSERT_GT(h.count_, 0);
}
TEST(Subscriber, subInChain)
{
ros::NodeHandle nh;
Helper h;
Chain<Msg> c;
c.addFilter(boost::make_shared<Subscriber<Msg> >(boost::ref(nh), "test_topic", 0));
c.registerCallback(boost::bind(&Helper::cb, &h, _1));
ros::Publisher pub = nh.advertise<Msg>("test_topic", 0);
ros::Time start = ros::Time::now();
while (h.count_ == 0 && (ros::Time::now() - start) < ros::Duration(1.0))
{
pub.publish(Msg());
ros::Duration(0.01).sleep();
ros::spinOnce();
}
ASSERT_GT(h.count_, 0);
}
struct ConstHelper
{
void cb(const MsgConstPtr& msg)
{
msg_ = msg;
}
MsgConstPtr msg_;
};
struct NonConstHelper
{
void cb(const MsgPtr& msg)
{
msg_ = msg;
}
MsgPtr msg_;
};
TEST(Subscriber, singleNonConstCallback)
{
ros::NodeHandle nh;
NonConstHelper h;
Subscriber<Msg> sub(nh, "test_topic", 0);
sub.registerCallback(&NonConstHelper::cb, &h);
ros::Publisher pub = nh.advertise<Msg>("test_topic", 0);
MsgPtr msg(boost::make_shared<Msg>());
pub.publish(msg);
ros::spinOnce();
ASSERT_TRUE(h.msg_);
ASSERT_EQ(msg.get(), h.msg_.get());
}
TEST(Subscriber, multipleNonConstCallbacksFilterSubscriber)
{
ros::NodeHandle nh;
NonConstHelper h, h2;
Subscriber<Msg> sub(nh, "test_topic", 0);
sub.registerCallback(&NonConstHelper::cb, &h);
sub.registerCallback(&NonConstHelper::cb, &h2);
ros::Publisher pub = nh.advertise<Msg>("test_topic", 0);
MsgPtr msg(boost::make_shared<Msg>());
pub.publish(msg);
ros::spinOnce();
ASSERT_TRUE(h.msg_);
ASSERT_TRUE(h2.msg_);
EXPECT_NE(msg.get(), h.msg_.get());
EXPECT_NE(msg.get(), h2.msg_.get());
EXPECT_NE(h.msg_.get(), h2.msg_.get());
}
TEST(Subscriber, multipleCallbacksSomeFilterSomeDirect)
{
ros::NodeHandle nh;
NonConstHelper h, h2;
Subscriber<Msg> sub(nh, "test_topic", 0);
sub.registerCallback(&NonConstHelper::cb, &h);
ros::Subscriber sub2 = nh.subscribe("test_topic", 0, &NonConstHelper::cb, &h2);
ros::Publisher pub = nh.advertise<Msg>("test_topic", 0);
MsgPtr msg(boost::make_shared<Msg>());
pub.publish(msg);
ros::spinOnce();
ASSERT_TRUE(h.msg_);
ASSERT_TRUE(h2.msg_);
EXPECT_NE(msg.get(), h.msg_.get());
EXPECT_NE(msg.get(), h2.msg_.get());
EXPECT_NE(h.msg_.get(), h2.msg_.get());
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "test_subscriber");
ros::NodeHandle nh;
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/time_synchronizer_unittest.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include "message_filters/time_synchronizer.h"
#include "message_filters/pass_through.h"
#include <ros/init.h>
using namespace message_filters;
struct Header
{
ros::Time stamp;
};
struct Msg
{
Header header;
int data;
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
namespace ros
{
namespace message_traits
{
template<>
struct TimeStamp<Msg>
{
static ros::Time value(const Msg& m)
{
return m.header.stamp;
}
};
}
}
class Helper
{
public:
Helper()
: count_(0)
, drop_count_(0)
{}
void cb()
{
++count_;
}
void dropcb()
{
++drop_count_;
}
int32_t count_;
int32_t drop_count_;
};
TEST(TimeSynchronizer, compile2)
{
NullFilter<Msg> f0, f1;
TimeSynchronizer<Msg, Msg> sync(f0, f1, 1);
}
TEST(TimeSynchronizer, compile3)
{
NullFilter<Msg> f0, f1, f2;
TimeSynchronizer<Msg, Msg, Msg> sync(f0, f1, f2, 1);
}
TEST(TimeSynchronizer, compile4)
{
NullFilter<Msg> f0, f1, f2, f3;
TimeSynchronizer<Msg, Msg, Msg, Msg> sync(f0, f1, f2, f3, 1);
}
TEST(TimeSynchronizer, compile5)
{
NullFilter<Msg> f0, f1, f2, f3, f4;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg> sync(f0, f1, f2, f3, f4, 1);
}
TEST(TimeSynchronizer, compile6)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg> sync(f0, f1, f2, f3, f4, f5, 1);
}
TEST(TimeSynchronizer, compile7)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5, f6;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(f0, f1, f2, f3, f4, f5, f6, 1);
}
TEST(TimeSynchronizer, compile8)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5, f6, f7;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(f0, f1, f2, f3, f4, f5, f6, f7, 1);
}
TEST(TimeSynchronizer, compile9)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5, f6, f7, f8;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(f0, f1, f2, f3, f4, f5, f6, f7, f8, 1);
}
void function2(const MsgConstPtr&, const MsgConstPtr&) {}
void function3(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function4(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function5(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function6(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function7(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function8(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function9(const MsgConstPtr&, MsgConstPtr, const MsgPtr&, MsgPtr, const Msg&, Msg, const ros::MessageEvent<Msg const>&, const ros::MessageEvent<Msg>&, const MsgConstPtr&) {}
TEST(TimeSynchronizer, compileFunction2)
{
TimeSynchronizer<Msg, Msg> sync(1);
sync.registerCallback(function2);
}
TEST(TimeSynchronizer, compileFunction3)
{
TimeSynchronizer<Msg, Msg, Msg> sync(1);
sync.registerCallback(function3);
}
TEST(TimeSynchronizer, compileFunction4)
{
TimeSynchronizer<Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(function4);
}
TEST(TimeSynchronizer, compileFunction5)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(function5);
}
TEST(TimeSynchronizer, compileFunction6)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(function6);
}
TEST(TimeSynchronizer, compileFunction7)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(function7);
}
TEST(TimeSynchronizer, compileFunction8)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(function8);
}
TEST(TimeSynchronizer, compileFunction9)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(function9);
}
struct MethodHelper
{
void method2(const MsgConstPtr&, const MsgConstPtr&) {}
void method3(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method4(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method5(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method6(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method7(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method8(const MsgConstPtr&, MsgConstPtr, const MsgPtr&, MsgPtr, const Msg&, Msg, const ros::MessageEvent<Msg const>&, const ros::MessageEvent<Msg>&) {}
// Can only do 8 here because the object instance counts as a parameter and bind only supports 9
};
TEST(TimeSynchronizer, compileMethod2)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method2, &h);
}
TEST(TimeSynchronizer, compileMethod3)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method3, &h);
}
TEST(TimeSynchronizer, compileMethod4)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method4, &h);
}
TEST(TimeSynchronizer, compileMethod5)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method5, &h);
}
TEST(TimeSynchronizer, compileMethod6)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method6, &h);
}
TEST(TimeSynchronizer, compileMethod7)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method7, &h);
}
TEST(TimeSynchronizer, compileMethod8)
{
MethodHelper h;
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
sync.registerCallback(&MethodHelper::method8, &h);
}
TEST(TimeSynchronizer, immediate2)
{
TimeSynchronizer<Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate3)
{
TimeSynchronizer<Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate4)
{
TimeSynchronizer<Msg, Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
sync.add3(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate5)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
sync.add3(m);
ASSERT_EQ(h.count_, 0);
sync.add4(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate6)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
sync.add3(m);
ASSERT_EQ(h.count_, 0);
sync.add4(m);
ASSERT_EQ(h.count_, 0);
sync.add5(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate7)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
sync.add3(m);
ASSERT_EQ(h.count_, 0);
sync.add4(m);
ASSERT_EQ(h.count_, 0);
sync.add5(m);
ASSERT_EQ(h.count_, 0);
sync.add6(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate8)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
sync.add3(m);
ASSERT_EQ(h.count_, 0);
sync.add4(m);
ASSERT_EQ(h.count_, 0);
sync.add5(m);
ASSERT_EQ(h.count_, 0);
sync.add6(m);
ASSERT_EQ(h.count_, 0);
sync.add7(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, immediate9)
{
TimeSynchronizer<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
sync.add3(m);
ASSERT_EQ(h.count_, 0);
sync.add4(m);
ASSERT_EQ(h.count_, 0);
sync.add5(m);
ASSERT_EQ(h.count_, 0);
sync.add6(m);
ASSERT_EQ(h.count_, 0);
sync.add7(m);
ASSERT_EQ(h.count_, 0);
sync.add8(m);
ASSERT_EQ(h.count_, 1);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// From here on we assume that testing the 3-message version is sufficient, so as not to duplicate
// tests for everywhere from 2-9
//////////////////////////////////////////////////////////////////////////////////////////////////
TEST(TimeSynchronizer, multipleTimes)
{
TimeSynchronizer<Msg, Msg, Msg> sync(2);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
m = boost::make_shared<Msg>();
m->header.stamp = ros::Time(0.1);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSynchronizer, queueSize)
{
TimeSynchronizer<Msg, Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time();
sync.add0(m);
ASSERT_EQ(h.count_, 0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
m = boost::make_shared<Msg>();
m->header.stamp = ros::Time(0.1);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
m = boost::make_shared<Msg>();
m->header.stamp = ros::Time(0);
sync.add1(m);
ASSERT_EQ(h.count_, 0);
sync.add2(m);
ASSERT_EQ(h.count_, 0);
}
TEST(TimeSynchronizer, dropCallback)
{
TimeSynchronizer<Msg, Msg> sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
sync.registerDropCallback(boost::bind(&Helper::dropcb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time();
sync.add0(m);
ASSERT_EQ(h.drop_count_, 0);
m->header.stamp = ros::Time(0.1);
sync.add0(m);
ASSERT_EQ(h.drop_count_, 1);
}
struct EventHelper
{
void callback(const ros::MessageEvent<Msg const>& e1, const ros::MessageEvent<Msg const>& e2)
{
e1_ = e1;
e2_ = e2;
}
ros::MessageEvent<Msg const> e1_;
ros::MessageEvent<Msg const> e2_;
};
TEST(TimeSynchronizer, eventInEventOut)
{
TimeSynchronizer<Msg, Msg> sync(2);
EventHelper h;
sync.registerCallback(&EventHelper::callback, &h);
ros::MessageEvent<Msg const> evt(boost::make_shared<Msg>(), ros::Time(4));
sync.add<0>(evt);
sync.add<1>(evt);
ASSERT_TRUE(h.e1_.getMessage());
ASSERT_TRUE(h.e2_.getMessage());
ASSERT_EQ(h.e1_.getReceiptTime(), evt.getReceiptTime());
ASSERT_EQ(h.e2_.getReceiptTime(), evt.getReceiptTime());
}
TEST(TimeSynchronizer, connectConstructor)
{
PassThrough<Msg> pt1, pt2;
TimeSynchronizer<Msg, Msg> sync(pt1, pt2, 1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time::now();
pt1.add(m);
ASSERT_EQ(h.count_, 0);
pt2.add(m);
ASSERT_EQ(h.count_, 1);
}
//TEST(TimeSynchronizer, connectToSimple)
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
ros::Time::setNow(ros::Time());
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/time_sequencer_unittest.xml | <launch>
<test test-name="time_sequencer" pkg="message_filters" type="message_filters-time_sequencer_unittest"/>
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_synchronizer.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include <ros/init.h>
#include "message_filters/synchronizer.h"
#include <boost/array.hpp>
using namespace message_filters;
struct Header
{
ros::Time stamp;
};
struct Msg
{
Header header;
int data;
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
template<typename M0, typename M1, typename M2 = NullType, typename M3 = NullType, typename M4 = NullType,
typename M5 = NullType, typename M6 = NullType, typename M7 = NullType, typename M8 = NullType>
struct NullPolicy : public PolicyBase<M0, M1, M2, M3, M4, M5, M6, M7, M8>
{
typedef Synchronizer<NullPolicy> Sync;
typedef PolicyBase<M0, M1, M2, M3, M4, M5, M6, M7, M8> Super;
typedef typename Super::Messages Messages;
typedef typename Super::Signal Signal;
typedef typename Super::Events Events;
typedef typename Super::RealTypeCount RealTypeCount;
NullPolicy()
{
for (int i = 0; i < RealTypeCount::value; ++i)
{
added_[i] = 0;
}
}
void initParent(Sync*)
{
}
template<int i>
void add(const typename mpl::at_c<Events, i>::type&)
{
++added_.at(i);
}
boost::array<int32_t, RealTypeCount::value> added_;
};
typedef NullPolicy<Msg, Msg> Policy2;
typedef NullPolicy<Msg, Msg, Msg> Policy3;
typedef NullPolicy<Msg, Msg, Msg, Msg> Policy4;
typedef NullPolicy<Msg, Msg, Msg, Msg, Msg> Policy5;
typedef NullPolicy<Msg, Msg, Msg, Msg, Msg, Msg> Policy6;
typedef NullPolicy<Msg, Msg, Msg, Msg, Msg, Msg, Msg> Policy7;
typedef NullPolicy<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> Policy8;
typedef NullPolicy<Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg, Msg> Policy9;
TEST(Synchronizer, compile2)
{
NullFilter<Msg> f0, f1;
Synchronizer<Policy2> sync(f0, f1);
}
TEST(Synchronizer, compile3)
{
NullFilter<Msg> f0, f1, f2;
Synchronizer<Policy3> sync(f0, f1, f2);
}
TEST(Synchronizer, compile4)
{
NullFilter<Msg> f0, f1, f2, f3;
Synchronizer<Policy4> sync(f0, f1, f2, f3);
}
TEST(Synchronizer, compile5)
{
NullFilter<Msg> f0, f1, f2, f3, f4;
Synchronizer<Policy5> sync(f0, f1, f2, f3, f4);
}
TEST(Synchronizer, compile6)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5;
Synchronizer<Policy6> sync(f0, f1, f2, f3, f4, f5);
}
TEST(Synchronizer, compile7)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5, f6;
Synchronizer<Policy7> sync(f0, f1, f2, f3, f4, f5, f6);
}
TEST(Synchronizer, compile8)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5, f6, f7;
Synchronizer<Policy8> sync(f0, f1, f2, f3, f4, f5, f6, f7);
}
TEST(Synchronizer, compile9)
{
NullFilter<Msg> f0, f1, f2, f3, f4, f5, f6, f7, f8;
Synchronizer<Policy9> sync(f0, f1, f2, f3, f4, f5, f6, f7, f8);
}
void function2(const MsgConstPtr&, const MsgConstPtr&) {}
void function3(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function4(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function5(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function6(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function7(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function8(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void function9(const MsgConstPtr&, MsgConstPtr, const MsgPtr&, MsgPtr, const Msg&, Msg, const ros::MessageEvent<Msg const>&, const ros::MessageEvent<Msg>&, const MsgConstPtr&) {}
TEST(Synchronizer, compileFunction2)
{
Synchronizer<Policy2> sync;
sync.registerCallback(function2);
}
TEST(Synchronizer, compileFunction3)
{
Synchronizer<Policy3> sync;
sync.registerCallback(function3);
}
TEST(Synchronizer, compileFunction4)
{
Synchronizer<Policy4> sync;
sync.registerCallback(function4);
}
TEST(Synchronizer, compileFunction5)
{
Synchronizer<Policy5> sync;
sync.registerCallback(function5);
}
TEST(Synchronizer, compileFunction6)
{
Synchronizer<Policy6> sync;
sync.registerCallback(function6);
}
TEST(Synchronizer, compileFunction7)
{
Synchronizer<Policy7> sync;
sync.registerCallback(function7);
}
TEST(Synchronizer, compileFunction8)
{
Synchronizer<Policy8> sync;
sync.registerCallback(function8);
}
TEST(Synchronizer, compileFunction9)
{
Synchronizer<Policy9> sync;
sync.registerCallback(function9);
}
struct MethodHelper
{
void method2(const MsgConstPtr&, const MsgConstPtr&) {}
void method3(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method4(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method5(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method6(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method7(const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&, const MsgConstPtr&) {}
void method8(const MsgConstPtr&, MsgConstPtr, const MsgPtr&, MsgPtr, const Msg&, Msg, const ros::MessageEvent<Msg const>&, const ros::MessageEvent<Msg>&) {}
// Can only do 8 here because the object instance counts as a parameter and bind only supports 9
};
TEST(Synchronizer, compileMethod2)
{
MethodHelper h;
Synchronizer<Policy2> sync;
sync.registerCallback(&MethodHelper::method2, &h);
}
TEST(Synchronizer, compileMethod3)
{
MethodHelper h;
Synchronizer<Policy3> sync;
sync.registerCallback(&MethodHelper::method3, &h);
}
TEST(Synchronizer, compileMethod4)
{
MethodHelper h;
Synchronizer<Policy4> sync;
sync.registerCallback(&MethodHelper::method4, &h);
}
TEST(Synchronizer, compileMethod5)
{
MethodHelper h;
Synchronizer<Policy5> sync;
sync.registerCallback(&MethodHelper::method5, &h);
}
TEST(Synchronizer, compileMethod6)
{
MethodHelper h;
Synchronizer<Policy6> sync;
sync.registerCallback(&MethodHelper::method6, &h);
}
TEST(Synchronizer, compileMethod7)
{
MethodHelper h;
Synchronizer<Policy7> sync;
sync.registerCallback(&MethodHelper::method7, &h);
}
TEST(Synchronizer, compileMethod8)
{
MethodHelper h;
Synchronizer<Policy8> sync;
sync.registerCallback(&MethodHelper::method8, &h);
}
TEST(Synchronizer, add2)
{
Synchronizer<Policy2> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
}
TEST(Synchronizer, add3)
{
Synchronizer<Policy3> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
}
TEST(Synchronizer, add4)
{
Synchronizer<Policy4> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
ASSERT_EQ(sync.added_[3], 0);
sync.add<3>(m);
ASSERT_EQ(sync.added_[3], 1);
}
TEST(Synchronizer, add5)
{
Synchronizer<Policy5> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
ASSERT_EQ(sync.added_[3], 0);
sync.add<3>(m);
ASSERT_EQ(sync.added_[3], 1);
ASSERT_EQ(sync.added_[4], 0);
sync.add<4>(m);
ASSERT_EQ(sync.added_[4], 1);
}
TEST(Synchronizer, add6)
{
Synchronizer<Policy6> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
ASSERT_EQ(sync.added_[3], 0);
sync.add<3>(m);
ASSERT_EQ(sync.added_[3], 1);
ASSERT_EQ(sync.added_[4], 0);
sync.add<4>(m);
ASSERT_EQ(sync.added_[4], 1);
ASSERT_EQ(sync.added_[5], 0);
sync.add<5>(m);
ASSERT_EQ(sync.added_[5], 1);
}
TEST(Synchronizer, add7)
{
Synchronizer<Policy7> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
ASSERT_EQ(sync.added_[3], 0);
sync.add<3>(m);
ASSERT_EQ(sync.added_[3], 1);
ASSERT_EQ(sync.added_[4], 0);
sync.add<4>(m);
ASSERT_EQ(sync.added_[4], 1);
ASSERT_EQ(sync.added_[5], 0);
sync.add<5>(m);
ASSERT_EQ(sync.added_[5], 1);
ASSERT_EQ(sync.added_[6], 0);
sync.add<6>(m);
ASSERT_EQ(sync.added_[6], 1);
}
TEST(Synchronizer, add8)
{
Synchronizer<Policy8> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
ASSERT_EQ(sync.added_[3], 0);
sync.add<3>(m);
ASSERT_EQ(sync.added_[3], 1);
ASSERT_EQ(sync.added_[4], 0);
sync.add<4>(m);
ASSERT_EQ(sync.added_[4], 1);
ASSERT_EQ(sync.added_[5], 0);
sync.add<5>(m);
ASSERT_EQ(sync.added_[5], 1);
ASSERT_EQ(sync.added_[6], 0);
sync.add<6>(m);
ASSERT_EQ(sync.added_[6], 1);
ASSERT_EQ(sync.added_[7], 0);
sync.add<7>(m);
ASSERT_EQ(sync.added_[7], 1);
}
TEST(Synchronizer, add9)
{
Synchronizer<Policy9> sync;
MsgPtr m(boost::make_shared<Msg>());
ASSERT_EQ(sync.added_[0], 0);
sync.add<0>(m);
ASSERT_EQ(sync.added_[0], 1);
ASSERT_EQ(sync.added_[1], 0);
sync.add<1>(m);
ASSERT_EQ(sync.added_[1], 1);
ASSERT_EQ(sync.added_[2], 0);
sync.add<2>(m);
ASSERT_EQ(sync.added_[2], 1);
ASSERT_EQ(sync.added_[3], 0);
sync.add<3>(m);
ASSERT_EQ(sync.added_[3], 1);
ASSERT_EQ(sync.added_[4], 0);
sync.add<4>(m);
ASSERT_EQ(sync.added_[4], 1);
ASSERT_EQ(sync.added_[5], 0);
sync.add<5>(m);
ASSERT_EQ(sync.added_[5], 1);
ASSERT_EQ(sync.added_[6], 0);
sync.add<6>(m);
ASSERT_EQ(sync.added_[6], 1);
ASSERT_EQ(sync.added_[7], 0);
sync.add<7>(m);
ASSERT_EQ(sync.added_[7], 1);
ASSERT_EQ(sync.added_[8], 0);
sync.add<8>(m);
ASSERT_EQ(sync.added_[8], 1);
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
ros::Time::setNow(ros::Time());
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_exact_time_policy.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/ros.h"
#include "message_filters/synchronizer.h"
#include "message_filters/sync_policies/exact_time.h"
using namespace message_filters;
using namespace message_filters::sync_policies;
struct Header
{
ros::Time stamp;
};
struct Msg
{
Header header;
int data;
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
namespace ros
{
namespace message_traits
{
template<>
struct TimeStamp<Msg>
{
static ros::Time value(const Msg& m)
{
return m.header.stamp;
}
};
}
}
class Helper
{
public:
Helper()
: count_(0)
, drop_count_(0)
{}
void cb()
{
++count_;
}
void dropcb()
{
++drop_count_;
}
int32_t count_;
int32_t drop_count_;
};
typedef ExactTime<Msg, Msg> Policy2;
typedef ExactTime<Msg, Msg, Msg> Policy3;
typedef Synchronizer<Policy2> Sync2;
typedef Synchronizer<Policy3> Sync3;
//////////////////////////////////////////////////////////////////////////////////////////////////
// From here on we assume that testing the 3-message version is sufficient, so as not to duplicate
// tests for everywhere from 2-9
//////////////////////////////////////////////////////////////////////////////////////////////////
TEST(ExactTime, multipleTimes)
{
Sync3 sync(2);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time();
sync.add<0>(m);
ASSERT_EQ(h.count_, 0);
m = boost::make_shared<Msg>();
m->header.stamp = ros::Time(0.1);
sync.add<1>(m);
ASSERT_EQ(h.count_, 0);
sync.add<0>(m);
ASSERT_EQ(h.count_, 0);
sync.add<2>(m);
ASSERT_EQ(h.count_, 1);
}
TEST(ExactTime, queueSize)
{
Sync3 sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time();
sync.add<0>(m);
ASSERT_EQ(h.count_, 0);
sync.add<1>(m);
ASSERT_EQ(h.count_, 0);
m = boost::make_shared<Msg>();
m->header.stamp = ros::Time(0.1);
sync.add<1>(m);
ASSERT_EQ(h.count_, 0);
m = boost::make_shared<Msg>();
m->header.stamp = ros::Time(0);
sync.add<1>(m);
ASSERT_EQ(h.count_, 0);
sync.add<2>(m);
ASSERT_EQ(h.count_, 0);
}
TEST(ExactTime, dropCallback)
{
Sync2 sync(1);
Helper h;
sync.registerCallback(boost::bind(&Helper::cb, &h));
sync.getPolicy()->registerDropCallback(boost::bind(&Helper::dropcb, &h));
MsgPtr m(boost::make_shared<Msg>());
m->header.stamp = ros::Time();
sync.add<0>(m);
ASSERT_EQ(h.drop_count_, 0);
m->header.stamp = ros::Time(0.1);
sync.add<0>(m);
ASSERT_EQ(h.drop_count_, 1);
}
struct EventHelper
{
void callback(const ros::MessageEvent<Msg const>& e1, const ros::MessageEvent<Msg const>& e2)
{
e1_ = e1;
e2_ = e2;
}
ros::MessageEvent<Msg const> e1_;
ros::MessageEvent<Msg const> e2_;
};
TEST(ExactTime, eventInEventOut)
{
Sync2 sync(2);
EventHelper h;
sync.registerCallback(&EventHelper::callback, &h);
ros::MessageEvent<Msg const> evt(boost::make_shared<Msg>(), ros::Time(4));
sync.add<0>(evt);
sync.add<1>(evt);
ASSERT_TRUE(h.e1_.getMessage());
ASSERT_TRUE(h.e2_.getMessage());
ASSERT_EQ(h.e1_.getReceiptTime(), evt.getReceiptTime());
ASSERT_EQ(h.e2_.getReceiptTime(), evt.getReceiptTime());
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
ros::Time::setNow(ros::Time());
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/directed.py | # image_transport::SubscriberFilter wide_left; // "/wide_stereo/left/image_raw"
# image_transport::SubscriberFilter wide_right; // "/wide_stereo/right/image_raw"
# message_filters::Subscriber<CameraInfo> wide_left_info; // "/wide_stereo/left/camera_info"
# message_filters::Subscriber<CameraInfo> wide_right_info; // "/wide_stereo/right/camera_info"
# message_filters::TimeSynchronizer<Image, CameraInfo, Image, CameraInfo> wide;
#
# PersonDataRecorder() :
# wide_left(nh_, "/wide_stereo/left/image_raw", 10),
# wide_right(nh_, "/wide_stereo/right/image_raw", 10),
# wide_left_info(nh_, "/wide_stereo/left/camera_info", 10),
# wide_right_info(nh_, "/wide_stereo/right/camera_info", 10),
# wide(wide_left, wide_left_info, wide_right, wide_right_info, 4),
#
# wide.registerCallback(boost::bind(&PersonDataRecorder::wideCB, this, _1, _2, _3, _4));
import rostest
import rospy
import random
import unittest
from message_filters import SimpleFilter, Subscriber, Cache, TimeSynchronizer
class MockHeader:
pass
class MockMessage:
def __init__(self, stamp, data):
self.header = MockHeader()
self.header.stamp = stamp
self.data = data
class MockFilter(SimpleFilter):
pass
class TestDirected(unittest.TestCase):
def cb_collector_2msg(self, msg1, msg2):
self.collector.append((msg1, msg2))
def test_synchronizer(self):
m0 = MockFilter()
m1 = MockFilter()
ts = TimeSynchronizer([m0, m1], 1)
ts.registerCallback(self.cb_collector_2msg)
if 0:
# Simple case, pairs of messages, make sure that they get combined
for t in range(10):
self.collector = []
msg0 = MockMessage(t, 33)
msg1 = MockMessage(t, 34)
m0.signalMessage(msg0)
self.assertEqual(self.collector, [])
m1.signalMessage(msg1)
self.assertEqual(self.collector, [(msg0, msg1)])
# Scramble sequences of length N. Make sure that TimeSequencer recombines them.
random.seed(0)
for N in range(1, 10):
m0 = MockFilter()
m1 = MockFilter()
seq0 = [MockMessage(t, random.random()) for t in range(N)]
seq1 = [MockMessage(t, random.random()) for t in range(N)]
# random.shuffle(seq0)
ts = TimeSynchronizer([m0, m1], N)
ts.registerCallback(self.cb_collector_2msg)
self.collector = []
for msg in random.sample(seq0, N):
m0.signalMessage(msg)
self.assertEqual(self.collector, [])
for msg in random.sample(seq1, N):
m1.signalMessage(msg)
self.assertEqual(set(self.collector), set(zip(seq0, seq1)))
if __name__ == '__main__':
if 0:
rostest.unitrun('message_filters', 'directed', TestDirected)
else:
suite = unittest.TestSuite()
suite.addTest(TestDirected('test_synchronizer'))
unittest.TextTestRunner(verbosity=2).run(suite)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_approximate_time_policy.cpp |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "message_filters/synchronizer.h"
#include "message_filters/sync_policies/approximate_time.h"
#include <vector>
#include <ros/ros.h>
//#include <pair>
using namespace message_filters;
using namespace message_filters::sync_policies;
struct Header
{
ros::Time stamp;
};
struct Msg
{
Header header;
int data;
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
namespace ros
{
namespace message_traits
{
template<>
struct TimeStamp<Msg>
{
static ros::Time value(const Msg& m)
{
return m.header.stamp;
}
};
}
}
typedef std::pair<ros::Time, ros::Time> TimePair;
typedef std::pair<ros::Time, unsigned int> TimeAndTopic;
struct TimeQuad
{
TimeQuad(ros::Time p, ros::Time q, ros::Time r, ros::Time s)
{
time[0] = p;
time[1] = q;
time[2] = r;
time[3] = s;
}
ros::Time time[4];
};
//----------------------------------------------------------
// Test Class (for 2 inputs)
//----------------------------------------------------------
class ApproximateTimeSynchronizerTest
{
public:
ApproximateTimeSynchronizerTest(const std::vector<TimeAndTopic> &input,
const std::vector<TimePair> &output,
uint32_t queue_size) :
input_(input), output_(output), output_position_(0), sync_(queue_size)
{
sync_.registerCallback(boost::bind(&ApproximateTimeSynchronizerTest::callback, this, _1, _2));
}
void callback(const MsgConstPtr& p, const MsgConstPtr& q)
{
//printf("Call_back called\n");
//printf("Call back: <%f, %f>\n", p->header.stamp.toSec(), q->header.stamp.toSec());
ASSERT_TRUE(p);
ASSERT_TRUE(q);
ASSERT_LT(output_position_, output_.size());
EXPECT_EQ(output_[output_position_].first, p->header.stamp);
EXPECT_EQ(output_[output_position_].second, q->header.stamp);
++output_position_;
}
void run()
{
for (unsigned int i = 0; i < input_.size(); i++)
{
if (input_[i].second == 0)
{
MsgPtr p(boost::make_shared<Msg>());
p->header.stamp = input_[i].first;
sync_.add<0>(p);
}
else
{
MsgPtr q(boost::make_shared<Msg>());
q->header.stamp = input_[i].first;
sync_.add<1>(q);
}
}
//printf("Done running test\n");
EXPECT_EQ(output_.size(), output_position_);
}
private:
const std::vector<TimeAndTopic> &input_;
const std::vector<TimePair> &output_;
unsigned int output_position_;
typedef Synchronizer<ApproximateTime<Msg, Msg> > Sync2;
public:
Sync2 sync_;
};
//----------------------------------------------------------
// Test Class (for 4 inputs)
//----------------------------------------------------------
class ApproximateTimeSynchronizerTestQuad
{
public:
ApproximateTimeSynchronizerTestQuad(const std::vector<TimeAndTopic> &input,
const std::vector<TimeQuad> &output,
uint32_t queue_size) :
input_(input), output_(output), output_position_(0), sync_(queue_size)
{
sync_.registerCallback(boost::bind(&ApproximateTimeSynchronizerTestQuad::callback, this, _1, _2, _3, _4));
}
void callback(const MsgConstPtr& p, const MsgConstPtr& q, const MsgConstPtr& r, const MsgConstPtr& s)
{
//printf("Call_back called\n");
//printf("Call back: <%f, %f>\n", p->header.stamp.toSec(), q->header.stamp.toSec());
ASSERT_TRUE(p);
ASSERT_TRUE(q);
ASSERT_TRUE(r);
ASSERT_TRUE(s);
ASSERT_LT(output_position_, output_.size());
EXPECT_EQ(output_[output_position_].time[0], p->header.stamp);
EXPECT_EQ(output_[output_position_].time[1], q->header.stamp);
EXPECT_EQ(output_[output_position_].time[2], r->header.stamp);
EXPECT_EQ(output_[output_position_].time[3], s->header.stamp);
++output_position_;
}
void run()
{
for (unsigned int i = 0; i < input_.size(); i++)
{
MsgPtr p(boost::make_shared<Msg>());
p->header.stamp = input_[i].first;
switch (input_[i].second)
{
case 0:
sync_.add<0>(p);
break;
case 1:
sync_.add<1>(p);
break;
case 2:
sync_.add<2>(p);
break;
case 3:
sync_.add<3>(p);
break;
}
}
//printf("Done running test\n");
EXPECT_EQ(output_.size(), output_position_);
}
private:
const std::vector<TimeAndTopic> &input_;
const std::vector<TimeQuad> &output_;
unsigned int output_position_;
typedef Synchronizer<ApproximateTime<Msg, Msg, Msg, Msg> > Sync4;
public:
Sync4 sync_;
};
//----------------------------------------------------------
// Test Suite
//----------------------------------------------------------
TEST(ApproxTimeSync, ExactMatch) {
// Input A: a..b..c
// Input B: A..B..C
// Output: a..b..c
// A..B..C
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t,1)); // A
input.push_back(TimeAndTopic(t+s*3,0)); // b
input.push_back(TimeAndTopic(t+s*3,1)); // B
input.push_back(TimeAndTopic(t+s*6,0)); // c
input.push_back(TimeAndTopic(t+s*6,1)); // C
output.push_back(TimePair(t, t));
output.push_back(TimePair(t+s*3, t+s*3));
output.push_back(TimePair(t+s*6, t+s*6));
ApproximateTimeSynchronizerTest sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, PerfectMatch) {
// Input A: a..b..c.
// Input B: .A..B..C
// Output: ...a..b.
// ...A..B.
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // A
input.push_back(TimeAndTopic(t+s*3,0)); // b
input.push_back(TimeAndTopic(t+s*4,1)); // B
input.push_back(TimeAndTopic(t+s*6,0)); // c
input.push_back(TimeAndTopic(t+s*7,1)); // C
output.push_back(TimePair(t, t+s));
output.push_back(TimePair(t+s*3, t+s*4));
ApproximateTimeSynchronizerTest sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, ImperfectMatch) {
// Input A: a.xb..c.
// Input B: .A...B.C
// Output: ..a...c.
// ..A...B.
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // A
input.push_back(TimeAndTopic(t+s*2,0)); // x
input.push_back(TimeAndTopic(t+s*3,0)); // b
input.push_back(TimeAndTopic(t+s*5,1)); // B
input.push_back(TimeAndTopic(t+s*6,0)); // c
input.push_back(TimeAndTopic(t+s*7,1)); // C
output.push_back(TimePair(t, t+s));
output.push_back(TimePair(t+s*6, t+s*5));
ApproximateTimeSynchronizerTest sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, Acceleration) {
// Time: 0123456789012345678
// Input A: a...........b....c.
// Input B: .......A.......B..C
// Output: ............b.....c
// ............A.....C
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s*7,1)); // A
input.push_back(TimeAndTopic(t+s*12,0)); // b
input.push_back(TimeAndTopic(t+s*15,1)); // B
input.push_back(TimeAndTopic(t+s*17,0)); // c
input.push_back(TimeAndTopic(t+s*18,1)); // C
output.push_back(TimePair(t+s*12, t+s*7));
output.push_back(TimePair(t+s*17, t+s*18));
ApproximateTimeSynchronizerTest sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, DroppedMessages) {
// Queue size 1 (too small)
// Time: 012345678901234
// Input A: a...b...c.d..e.
// Input B: .A.B...C...D..E
// Output: .......b.....d.
// .......B.....D.
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // A
input.push_back(TimeAndTopic(t+s*3,1)); // B
input.push_back(TimeAndTopic(t+s*4,0)); // b
input.push_back(TimeAndTopic(t+s*7,1)); // C
input.push_back(TimeAndTopic(t+s*8,0)); // c
input.push_back(TimeAndTopic(t+s*10,0)); // d
input.push_back(TimeAndTopic(t+s*11,1)); // D
input.push_back(TimeAndTopic(t+s*13,0)); // e
input.push_back(TimeAndTopic(t+s*14,1)); // E
output.push_back(TimePair(t+s*4, t+s*3));
output.push_back(TimePair(t+s*10, t+s*11));
ApproximateTimeSynchronizerTest sync_test(input, output, 1);
sync_test.run();
// Queue size 2 (just enough)
// Time: 012345678901234
// Input A: a...b...c.d..e.
// Input B: .A.B...C...D..E
// Output: ....a..b...c.d.
// ....A..B...C.D.
std::vector<TimePair> output2;
output2.push_back(TimePair(t, t+s));
output2.push_back(TimePair(t+s*4, t+s*3));
output2.push_back(TimePair(t+s*8, t+s*7));
output2.push_back(TimePair(t+s*10, t+s*11));
ApproximateTimeSynchronizerTest sync_test2(input, output2, 2);
sync_test2.run();
}
TEST(ApproxTimeSync, LongQueue) {
// Queue size 5
// Time: 012345678901234
// Input A: abcdefghiklmnp.
// Input B: ...j......o....
// Output: ..........l....
// ..........o....
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,0)); // b
input.push_back(TimeAndTopic(t+s*2,0)); // c
input.push_back(TimeAndTopic(t+s*3,0)); // d
input.push_back(TimeAndTopic(t+s*4,0)); // e
input.push_back(TimeAndTopic(t+s*5,0)); // f
input.push_back(TimeAndTopic(t+s*6,0)); // g
input.push_back(TimeAndTopic(t+s*7,0)); // h
input.push_back(TimeAndTopic(t+s*8,0)); // i
input.push_back(TimeAndTopic(t+s*3,1)); // j
input.push_back(TimeAndTopic(t+s*9,0)); // k
input.push_back(TimeAndTopic(t+s*10,0)); // l
input.push_back(TimeAndTopic(t+s*11,0)); // m
input.push_back(TimeAndTopic(t+s*12,0)); // n
input.push_back(TimeAndTopic(t+s*10,1)); // o
input.push_back(TimeAndTopic(t+s*13,0)); // l
output.push_back(TimePair(t+s*10, t+s*10));
ApproximateTimeSynchronizerTest sync_test(input, output, 5);
sync_test.run();
}
TEST(ApproxTimeSync, DoublePublish) {
// Input A: a..b
// Input B: .A.B
// Output: ...b
// ...B
// +
// a
// A
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // A
input.push_back(TimeAndTopic(t+s*3,1)); // B
input.push_back(TimeAndTopic(t+s*3,0)); // b
output.push_back(TimePair(t, t+s));
output.push_back(TimePair(t+s*3, t+s*3));
ApproximateTimeSynchronizerTest sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, FourTopics) {
// Time: 012345678901234
// Input A: a....e..i.m..n.
// Input B: .b....g..j....o
// Input C: ..c...h...k....
// Input D: ...d.f.....l...
// Output: ......a....e..m
// ......b....g..j
// ......c....h..k
// ......d....f..l
std::vector<TimeAndTopic> input;
std::vector<TimeQuad> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // b
input.push_back(TimeAndTopic(t+s*2,2)); // c
input.push_back(TimeAndTopic(t+s*3,3)); // d
input.push_back(TimeAndTopic(t+s*5,0)); // e
input.push_back(TimeAndTopic(t+s*5,3)); // f
input.push_back(TimeAndTopic(t+s*6,1)); // g
input.push_back(TimeAndTopic(t+s*6,2)); // h
input.push_back(TimeAndTopic(t+s*8,0)); // i
input.push_back(TimeAndTopic(t+s*9,1)); // j
input.push_back(TimeAndTopic(t+s*10,2)); // k
input.push_back(TimeAndTopic(t+s*11,3)); // l
input.push_back(TimeAndTopic(t+s*10,0)); // m
input.push_back(TimeAndTopic(t+s*13,0)); // n
input.push_back(TimeAndTopic(t+s*14,1)); // o
output.push_back(TimeQuad(t, t+s, t+s*2, t+s*3));
output.push_back(TimeQuad(t+s*5, t+s*6, t+s*6, t+s*5));
output.push_back(TimeQuad(t+s*10, t+s*9, t+s*10, t+s*11));
ApproximateTimeSynchronizerTestQuad sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, EarlyPublish) {
// Time: 012345678901234
// Input A: a......e
// Input B: .b......
// Input C: ..c.....
// Input D: ...d....
// Output: .......a
// .......b
// .......c
// .......d
std::vector<TimeAndTopic> input;
std::vector<TimeQuad> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // b
input.push_back(TimeAndTopic(t+s*2,2)); // c
input.push_back(TimeAndTopic(t+s*3,3)); // d
input.push_back(TimeAndTopic(t+s*7,0)); // e
output.push_back(TimeQuad(t, t+s, t+s*2, t+s*3));
ApproximateTimeSynchronizerTestQuad sync_test(input, output, 10);
sync_test.run();
}
TEST(ApproxTimeSync, RateBound) {
// Rate bound A: 1.5
// Input A: a..b..c.
// Input B: .A..B..C
// Output: .a..b...
// .A..B...
std::vector<TimeAndTopic> input;
std::vector<TimePair> output;
ros::Time t(0, 0);
ros::Duration s(1, 0);
input.push_back(TimeAndTopic(t,0)); // a
input.push_back(TimeAndTopic(t+s,1)); // A
input.push_back(TimeAndTopic(t+s*3,0)); // b
input.push_back(TimeAndTopic(t+s*4,1)); // B
input.push_back(TimeAndTopic(t+s*6,0)); // c
input.push_back(TimeAndTopic(t+s*7,1)); // C
output.push_back(TimePair(t, t+s));
output.push_back(TimePair(t+s*3, t+s*4));
ApproximateTimeSynchronizerTest sync_test(input, output, 10);
sync_test.sync_.setInterMessageLowerBound(0, s*1.5);
sync_test.run();
// Rate bound A: 2
// Input A: a..b..c.
// Input B: .A..B..C
// Output: .a..b..c
// .A..B..C
output.push_back(TimePair(t+s*6, t+s*7));
ApproximateTimeSynchronizerTest sync_test2(input, output, 10);
sync_test2.sync_.setInterMessageLowerBound(0, s*2);
sync_test2.run();
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_simple.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include <ros/init.h>
#include "message_filters/simple_filter.h"
using namespace message_filters;
struct Msg
{
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
struct Filter : public SimpleFilter<Msg>
{
typedef ros::MessageEvent<Msg const> EventType;
void add(const EventType& evt)
{
signalMessage(evt);
}
};
class Helper
{
public:
Helper()
{
counts_.assign(0);
}
void cb0(const MsgConstPtr&)
{
++counts_[0];
}
void cb1(const Msg&)
{
++counts_[1];
}
void cb2(MsgConstPtr)
{
++counts_[2];
}
void cb3(const ros::MessageEvent<Msg const>&)
{
++counts_[3];
}
void cb4(Msg)
{
++counts_[4];
}
void cb5(const MsgPtr&)
{
++counts_[5];
}
void cb6(MsgPtr)
{
++counts_[6];
}
void cb7(const ros::MessageEvent<Msg>&)
{
++counts_[7];
}
boost::array<int32_t, 30> counts_;
};
TEST(SimpleFilter, callbackTypes)
{
Helper h;
Filter f;
f.registerCallback(boost::bind(&Helper::cb0, &h, _1));
f.registerCallback<const Msg&>(boost::bind(&Helper::cb1, &h, _1));
f.registerCallback<MsgConstPtr>(boost::bind(&Helper::cb2, &h, _1));
f.registerCallback<const ros::MessageEvent<Msg const>&>(boost::bind(&Helper::cb3, &h, _1));
f.registerCallback<Msg>(boost::bind(&Helper::cb4, &h, _1));
f.registerCallback<const MsgPtr&>(boost::bind(&Helper::cb5, &h, _1));
f.registerCallback<MsgPtr>(boost::bind(&Helper::cb6, &h, _1));
f.registerCallback<const ros::MessageEvent<Msg>&>(boost::bind(&Helper::cb7, &h, _1));
f.add(Filter::EventType(boost::make_shared<Msg>()));
EXPECT_EQ(h.counts_[0], 1);
EXPECT_EQ(h.counts_[1], 1);
EXPECT_EQ(h.counts_[2], 1);
EXPECT_EQ(h.counts_[3], 1);
EXPECT_EQ(h.counts_[4], 1);
EXPECT_EQ(h.counts_[5], 1);
EXPECT_EQ(h.counts_[6], 1);
EXPECT_EQ(h.counts_[7], 1);
}
struct OldFilter
{
Connection registerCallback(const boost::function<void(const MsgConstPtr&)>&)
{
return Connection();
}
};
TEST(SimpleFilter, oldRegisterWithNewFilter)
{
OldFilter f;
Helper h;
f.registerCallback(boost::bind(&Helper::cb3, &h, _1));
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_message_filters_cache.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright 2015 Martin Llofriu, Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Willow Garage nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import rospy
import unittest
from std_msgs.msg import String
from message_filters import Cache, Subscriber
PKG = 'message_filters'
class AnonymMsg:
class AnonymHeader:
stamp = None
def __init__(self):
self.stamp = rospy.Time()
header = None
def __init__(self):
self.header = AnonymMsg.AnonymHeader()
class TestCache(unittest.TestCase):
def test_all_funcs(self):
sub = Subscriber("/empty", String)
cache = Cache(sub, 5)
msg = AnonymMsg()
msg.header.stamp = rospy.Time(0)
cache.add(msg)
msg = AnonymMsg()
msg.header.stamp = rospy.Time(1)
cache.add(msg)
msg = AnonymMsg()
msg.header.stamp = rospy.Time(2)
cache.add(msg)
msg = AnonymMsg()
msg.header.stamp = rospy.Time(3)
cache.add(msg)
msg = AnonymMsg()
msg.header.stamp = rospy.Time(4)
cache.add(msg)
l = len(cache.getInterval(rospy.Time(2.5),
rospy.Time(3.5)))
self.assertEquals(l, 1, "invalid number of messages" +
" returned in getInterval 1")
l = len(cache.getInterval(rospy.Time(2),
rospy.Time(3)))
self.assertEquals(l, 2, "invalid number of messages" +
" returned in getInterval 2")
l = len(cache.getInterval(rospy.Time(0),
rospy.Time(4)))
self.assertEquals(l, 5, "invalid number of messages" +
" returned in getInterval 3")
s = cache.getElemAfterTime(rospy.Time(0)).header.stamp
self.assertEqual(s, rospy.Time(0),
"invalid msg return by getElemAfterTime")
s = cache.getElemBeforeTime(rospy.Time(3.5)).header.stamp
self.assertEqual(s, rospy.Time(3),
"invalid msg return by getElemBeforeTime")
s = cache.getLastestTime()
self.assertEqual(s, rospy.Time(4),
"invalid stamp return by getLastestTime")
s = cache.getOldestTime()
self.assertEqual(s, rospy.Time(0),
"invalid stamp return by getOldestTime")
# Add another msg to fill the buffer
msg = AnonymMsg()
msg.header.stamp = rospy.Time(5)
cache.add(msg)
# Test that it discarded the right one
s = cache.getOldestTime()
self.assertEqual(s, rospy.Time(1),
"wrong message discarded")
if __name__ == '__main__':
import rosunit
rosunit.unitrun(PKG, 'test_message_filters_cache', TestCache)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/msg_cache_unittest.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include <ros/init.h>
#include "message_filters/cache.h"
using namespace std ;
using namespace message_filters ;
struct Header
{
ros::Time stamp ;
} ;
struct Msg
{
Header header ;
int data ;
} ;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
namespace ros
{
namespace message_traits
{
template<>
struct TimeStamp<Msg>
{
static ros::Time value(const Msg& m)
{
return m.header.stamp;
}
};
}
}
void fillCacheEasy(Cache<Msg>& cache, unsigned int start, unsigned int end)
{
for (unsigned int i=start; i < end; i++)
{
Msg* msg = new Msg ;
msg->data = i ;
msg->header.stamp.fromSec(i*10) ;
boost::shared_ptr<Msg const> msg_ptr(msg) ;
cache.add(msg_ptr) ;
}
}
TEST(Cache, easyInterval)
{
Cache<Msg> cache(10) ;
fillCacheEasy(cache, 0, 5) ;
vector<boost::shared_ptr<Msg const> > interval_data = cache.getInterval(ros::Time().fromSec(5), ros::Time().fromSec(35)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 3) ;
EXPECT_EQ(interval_data[0]->data, 1) ;
EXPECT_EQ(interval_data[1]->data, 2) ;
EXPECT_EQ(interval_data[2]->data, 3) ;
// Look for an interval past the end of the cache
interval_data = cache.getInterval(ros::Time().fromSec(55), ros::Time().fromSec(65)) ;
EXPECT_EQ(interval_data.size(), (unsigned int) 0) ;
// Look for an interval that fell off the back of the cache
fillCacheEasy(cache, 5, 20) ;
interval_data = cache.getInterval(ros::Time().fromSec(5), ros::Time().fromSec(35)) ;
EXPECT_EQ(interval_data.size(), (unsigned int) 0) ;
}
TEST(Cache, easySurroundingInterval)
{
Cache<Msg> cache(10);
fillCacheEasy(cache, 1, 6);
vector<boost::shared_ptr<Msg const> > interval_data;
interval_data = cache.getSurroundingInterval(ros::Time(15,0), ros::Time(35,0)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 4);
EXPECT_EQ(interval_data[0]->data, 1);
EXPECT_EQ(interval_data[1]->data, 2);
EXPECT_EQ(interval_data[2]->data, 3);
EXPECT_EQ(interval_data[3]->data, 4);
interval_data = cache.getSurroundingInterval(ros::Time(0,0), ros::Time(35,0)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 4);
EXPECT_EQ(interval_data[0]->data, 1);
interval_data = cache.getSurroundingInterval(ros::Time(35,0), ros::Time(35,0)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 2);
EXPECT_EQ(interval_data[0]->data, 3);
EXPECT_EQ(interval_data[1]->data, 4);
interval_data = cache.getSurroundingInterval(ros::Time(55,0), ros::Time(55,0)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 1);
EXPECT_EQ(interval_data[0]->data, 5);
}
boost::shared_ptr<Msg const> buildMsg(double time, int data)
{
Msg* msg = new Msg ;
msg->data = data ;
msg->header.stamp.fromSec(time) ;
boost::shared_ptr<Msg const> msg_ptr(msg) ;
return msg_ptr ;
}
TEST(Cache, easyUnsorted)
{
Cache<Msg> cache(10) ;
cache.add(buildMsg(10.0, 1)) ;
cache.add(buildMsg(30.0, 3)) ;
cache.add(buildMsg(70.0, 7)) ;
cache.add(buildMsg( 5.0, 0)) ;
cache.add(buildMsg(20.0, 2)) ;
vector<boost::shared_ptr<Msg const> > interval_data = cache.getInterval(ros::Time().fromSec(3), ros::Time().fromSec(15)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 2) ;
EXPECT_EQ(interval_data[0]->data, 0) ;
EXPECT_EQ(interval_data[1]->data, 1) ;
// Grab all the data
interval_data = cache.getInterval(ros::Time().fromSec(0), ros::Time().fromSec(80)) ;
ASSERT_EQ(interval_data.size(), (unsigned int) 5) ;
EXPECT_EQ(interval_data[0]->data, 0) ;
EXPECT_EQ(interval_data[1]->data, 1) ;
EXPECT_EQ(interval_data[2]->data, 2) ;
EXPECT_EQ(interval_data[3]->data, 3) ;
EXPECT_EQ(interval_data[4]->data, 7) ;
}
TEST(Cache, easyElemBeforeAfter)
{
Cache<Msg> cache(10) ;
boost::shared_ptr<Msg const> elem_ptr ;
fillCacheEasy(cache, 5, 10) ;
elem_ptr = cache.getElemAfterTime( ros::Time().fromSec(85.0)) ;
ASSERT_FALSE(!elem_ptr) ;
EXPECT_EQ(elem_ptr->data, 9) ;
elem_ptr = cache.getElemBeforeTime( ros::Time().fromSec(85.0)) ;
ASSERT_FALSE(!elem_ptr) ;
EXPECT_EQ(elem_ptr->data, 8) ;
elem_ptr = cache.getElemBeforeTime( ros::Time().fromSec(45.0)) ;
EXPECT_TRUE(!elem_ptr) ;
}
struct EventHelper
{
public:
void cb(const ros::MessageEvent<Msg const>& evt)
{
event_ = evt;
}
ros::MessageEvent<Msg const> event_;
};
TEST(Cache, eventInEventOut)
{
Cache<Msg> c0(10);
Cache<Msg> c1(c0, 10);
EventHelper h;
c1.registerCallback(&EventHelper::cb, &h);
ros::MessageEvent<Msg const> evt(boost::make_shared<Msg const>(), ros::Time(4));
c0.add(evt);
EXPECT_EQ(h.event_.getReceiptTime(), evt.getReceiptTime());
EXPECT_EQ(h.event_.getMessage(), evt.getMessage());
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "blah");
ros::Time::init();
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/time_sequencer_unittest.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include "ros/time.h"
#include "message_filters/time_sequencer.h"
using namespace message_filters;
struct Header
{
ros::Time stamp;
};
struct Msg
{
Header header;
int data;
};
typedef boost::shared_ptr<Msg> MsgPtr;
typedef boost::shared_ptr<Msg const> MsgConstPtr;
namespace ros
{
namespace message_traits
{
template<>
struct TimeStamp<Msg>
{
static ros::Time value(const Msg& m)
{
return m.header.stamp;
}
};
}
}
class Helper
{
public:
Helper()
: count_(0)
{}
void cb(const MsgConstPtr&)
{
++count_;
}
int32_t count_;
};
TEST(TimeSequencer, simple)
{
TimeSequencer<Msg> seq(ros::Duration(1.0), ros::Duration(0.01), 10);
Helper h;
seq.registerCallback(boost::bind(&Helper::cb, &h, _1));
MsgPtr msg(boost::make_shared<Msg>());
msg->header.stamp = ros::Time::now();
seq.add(msg);
ros::WallDuration(0.1).sleep();
ros::spinOnce();
ASSERT_EQ(h.count_, 0);
ros::Time::setNow(ros::Time::now() + ros::Duration(2.0));
ros::WallDuration(0.1).sleep();
ros::spinOnce();
ASSERT_EQ(h.count_, 1);
}
TEST(TimeSequencer, compilation)
{
TimeSequencer<Msg> seq(ros::Duration(1.0), ros::Duration(0.01), 10);
TimeSequencer<Msg> seq2(ros::Duration(1.0), ros::Duration(0.01), 10);
seq2.connectInput(seq);
}
struct EventHelper
{
public:
void cb(const ros::MessageEvent<Msg const>& evt)
{
event_ = evt;
}
ros::MessageEvent<Msg const> event_;
};
TEST(TimeSequencer, eventInEventOut)
{
TimeSequencer<Msg> seq(ros::Duration(1.0), ros::Duration(0.01), 10);
TimeSequencer<Msg> seq2(seq, ros::Duration(1.0), ros::Duration(0.01), 10);
EventHelper h;
seq2.registerCallback(&EventHelper::cb, &h);
ros::MessageEvent<Msg const> evt(boost::make_shared<Msg const>(), ros::Time::now());
seq.add(evt);
ros::Time::setNow(ros::Time::now() + ros::Duration(2));
while (!h.event_.getMessage())
{
ros::WallDuration(0.01).sleep();
ros::spinOnce();
}
EXPECT_EQ(h.event_.getReceiptTime(), evt.getReceiptTime());
EXPECT_EQ(h.event_.getMessage(), evt.getMessage());
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "time_sequencer_test");
ros::NodeHandle nh;
ros::Time::setNow(ros::Time());
return RUN_ALL_TESTS();
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/test/test_subscriber.xml | <launch>
<test test-name="test_subscriber" pkg="message_filters" type="message_filters-test_subscriber"/>
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/chain.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_CHAIN_H
#define MESSAGE_FILTERS_CHAIN_H
#include "simple_filter.h"
#include "pass_through.h"
#include <vector>
namespace message_filters
{
/**
* \brief Base class for Chain, allows you to store multiple chains in the same container. Provides filter retrieval
* by index.
*/
class ChainBase
{
public:
virtual ~ChainBase() {}
/**
* \brief Retrieve a filter from this chain by index. Returns an empty shared_ptr if the index is greater than
* the size of the chain. \b NOT type-safe
*
* \param F [template] The type of the filter
* \param index The index of the filter (returned by addFilter())
*/
template<typename F>
boost::shared_ptr<F> getFilter(size_t index) const
{
boost::shared_ptr<void> filter = getFilterForIndex(index);
if (filter)
{
return boost::static_pointer_cast<F>(filter);
}
return boost::shared_ptr<F>();
}
protected:
virtual boost::shared_ptr<void> getFilterForIndex(size_t index) const = 0;
};
typedef boost::shared_ptr<ChainBase> ChainBasePtr;
/**
* \brief Chains a dynamic number of simple filters together. Allows retrieval of filters by index after they are added.
*
* The Chain filter provides a container for simple filters. It allows you to store an N-long set of filters inside a single
* structure, making it much easier to manage them.
*
* Adding filters to the chain is done by adding shared_ptrs of them to the filter. They are automatically connected to each other
* and the output of the last filter in the chain is forwarded to the callback you've registered with Chain::registerCallback
*
* Example:
\verbatim
void myCallback(const MsgConstPtr& msg)
{
}
Chain<Msg> c;
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.addFilter(boost::make_shared<PassThrough<Msg> >());
c.registerCallback(myCallback);
\endverbatim
*
* It is also possible to pass bare pointers in, which will not be automatically deleted when Chain is destructed:
\verbatim
Chain<Msg> c;
PassThrough<Msg> p;
c.addFilter(&p);
c.registerCallback(myCallback);
\endverbatim
*
*/
template<typename M>
class Chain : public ChainBase, public SimpleFilter<M>
{
public:
typedef boost::shared_ptr<M const> MConstPtr;
typedef ros::MessageEvent<M const> EventType;
/**
* \brief Default constructor
*/
Chain()
{
}
/**
* \brief Constructor with filter. Calls connectInput(f)
*/
template<typename F>
Chain(F& f)
{
connectInput(f);
}
struct NullDeleter
{
void operator()(void const*) const
{
}
};
/**
* \brief Add a filter to this chain, by bare pointer. Returns the index of that filter in the chain.
*/
template<class F>
size_t addFilter(F* filter)
{
boost::shared_ptr<F> ptr(filter, NullDeleter());
return addFilter(ptr);
}
/**
* \brief Add a filter to this chain, by shared_ptr. Returns the index of that filter in the chain
*/
template<class F>
size_t addFilter(const boost::shared_ptr<F>& filter)
{
FilterInfo info;
info.add_func = boost::bind((void(F::*)(const EventType&))&F::add, filter.get(), _1);
info.filter = filter;
info.passthrough = boost::make_shared<PassThrough<M> >();
last_filter_connection_.disconnect();
info.passthrough->connectInput(*filter);
last_filter_connection_ = info.passthrough->registerCallback(typename SimpleFilter<M>::EventCallback(boost::bind(&Chain::lastFilterCB, this, _1)));
if (!filters_.empty())
{
filter->connectInput(*filters_.back().passthrough);
}
uint32_t count = filters_.size();
filters_.push_back(info);
return count;
}
/**
* \brief Retrieve a filter from this chain by index. Returns an empty shared_ptr if the index is greater than
* the size of the chain. \b NOT type-safe
*
* \param F [template] The type of the filter
* \param index The index of the filter (returned by addFilter())
*/
template<typename F>
boost::shared_ptr<F> getFilter(size_t index) const
{
if (index >= filters_.size())
{
return boost::shared_ptr<F>();
}
return boost::static_pointer_cast<F>(filters_[index].filter);
}
/**
* \brief Connect this filter's input to another filter's output.
*/
template<class F>
void connectInput(F& f)
{
incoming_connection_.disconnect();
incoming_connection_ = f.registerCallback(typename SimpleFilter<M>::EventCallback(boost::bind(&Chain::incomingCB, this, _1)));
}
/**
* \brief Add a message to the start of this chain
*/
void add(const MConstPtr& msg)
{
add(EventType(msg));
}
void add(const EventType& evt)
{
if (!filters_.empty())
{
filters_[0].add_func(evt);
}
}
protected:
virtual boost::shared_ptr<void> getFilterForIndex(size_t index) const
{
if (index >= filters_.size())
{
return boost::shared_ptr<void>();
}
return filters_[index].filter;
}
private:
void incomingCB(const EventType& evt)
{
add(evt);
}
void lastFilterCB(const EventType& evt)
{
this->signalMessage(evt);
}
struct FilterInfo
{
boost::function<void(const EventType&)> add_func;
boost::shared_ptr<void> filter;
boost::shared_ptr<PassThrough<M> > passthrough;
};
typedef std::vector<FilterInfo> V_FilterInfo;
V_FilterInfo filters_;
Connection incoming_connection_;
Connection last_filter_connection_;
};
}
#endif // MESSAGE_FILTERS_CHAIN_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/connection.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_CONNECTION_H
#define MESSAGE_FILTERS_CONNECTION_H
#include <boost/function.hpp>
#include <boost/signals2/connection.hpp>
#include "macros.h"
namespace message_filters
{
/**
* \brief Encapsulates a connection from one filter to another (or to a user-specified callback)
*/
class MESSAGE_FILTERS_DECL Connection
{
public:
typedef boost::function<void(void)> VoidDisconnectFunction;
typedef boost::function<void(const Connection&)> WithConnectionDisconnectFunction;
Connection() {}
Connection(const VoidDisconnectFunction& func);
Connection(const WithConnectionDisconnectFunction& func, boost::signals2::connection conn);
/**
* \brief disconnects this connection
*/
void disconnect();
boost::signals2::connection getBoostConnection() const { return connection_; }
private:
VoidDisconnectFunction void_disconnect_;
WithConnectionDisconnectFunction connection_disconnect_;
boost::signals2::connection connection_;
};
}
#endif // MESSAGE_FILTERS_CONNECTION_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/pass_through.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_PASSTHROUGH_H
#define MESSAGE_FILTERS_PASSTHROUGH_H
#include "simple_filter.h"
#include <vector>
namespace message_filters
{
/**
* \brief Simple passthrough filter. What comes in goes out immediately.
*/
template<typename M>
class PassThrough : public SimpleFilter<M>
{
public:
typedef boost::shared_ptr<M const> MConstPtr;
typedef ros::MessageEvent<M const> EventType;
PassThrough()
{
}
template<typename F>
PassThrough(F& f)
{
connectInput(f);
}
template<class F>
void connectInput(F& f)
{
incoming_connection_.disconnect();
incoming_connection_ = f.registerCallback(typename SimpleFilter<M>::EventCallback(boost::bind(&PassThrough::cb, this, _1)));
}
void add(const MConstPtr& msg)
{
add(EventType(msg));
}
void add(const EventType& evt)
{
this->signalMessage(evt);
}
private:
void cb(const EventType& evt)
{
add(evt);
}
Connection incoming_connection_;
};
} // namespace message_filters
#endif // MESSAGE_FILTERS_PASSTHROUGH_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/synchronizer.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SYNCHRONIZER_H
#define MESSAGE_FILTERS_SYNCHRONIZER_H
#include <boost/tuple/tuple.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/noncopyable.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/function_types/function_arity.hpp>
#include <boost/function_types/is_nonmember_callable_builtin.hpp>
#include "connection.h"
#include "null_types.h"
#include "signal9.h"
#include <ros/message_traits.h>
#include <ros/message_event.h>
#include <deque>
#include <vector>
#include <string>
namespace message_filters
{
namespace mpl = boost::mpl;
template<class Policy>
class Synchronizer : public boost::noncopyable, public Policy
{
public:
typedef typename Policy::Messages Messages;
typedef typename Policy::Events Events;
typedef typename Policy::Signal Signal;
typedef typename mpl::at_c<Messages, 0>::type M0;
typedef typename mpl::at_c<Messages, 1>::type M1;
typedef typename mpl::at_c<Messages, 2>::type M2;
typedef typename mpl::at_c<Messages, 3>::type M3;
typedef typename mpl::at_c<Messages, 4>::type M4;
typedef typename mpl::at_c<Messages, 5>::type M5;
typedef typename mpl::at_c<Messages, 6>::type M6;
typedef typename mpl::at_c<Messages, 7>::type M7;
typedef typename mpl::at_c<Messages, 8>::type M8;
typedef typename mpl::at_c<Events, 0>::type M0Event;
typedef typename mpl::at_c<Events, 1>::type M1Event;
typedef typename mpl::at_c<Events, 2>::type M2Event;
typedef typename mpl::at_c<Events, 3>::type M3Event;
typedef typename mpl::at_c<Events, 4>::type M4Event;
typedef typename mpl::at_c<Events, 5>::type M5Event;
typedef typename mpl::at_c<Events, 6>::type M6Event;
typedef typename mpl::at_c<Events, 7>::type M7Event;
typedef typename mpl::at_c<Events, 8>::type M8Event;
static const uint8_t MAX_MESSAGES = 9;
template<class F0, class F1>
Synchronizer(F0& f0, F1& f1)
{
connectInput(f0, f1);
init();
}
template<class F0, class F1, class F2>
Synchronizer(F0& f0, F1& f1, F2& f2)
{
connectInput(f0, f1, f2);
init();
}
template<class F0, class F1, class F2, class F3>
Synchronizer(F0& f0, F1& f1, F2& f2, F3& f3)
{
connectInput(f0, f1, f2, f3);
init();
}
template<class F0, class F1, class F2, class F3, class F4>
Synchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4)
{
connectInput(f0, f1, f2, f3, f4);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5>
Synchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5)
{
connectInput(f0, f1, f2, f3, f4, f5);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6>
Synchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6)
{
connectInput(f0, f1, f2, f3, f4, f5, f6);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7>
Synchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7)
{
connectInput(f0, f1, f2, f3, f4, f5, f6, f7);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7, class F8>
Synchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7, F8& f8)
{
connectInput(f0, f1, f2, f3, f4, f5, f6, f7, f8);
init();
}
Synchronizer()
{
init();
}
template<class F0, class F1>
Synchronizer(const Policy& policy, F0& f0, F1& f1)
: Policy(policy)
{
connectInput(f0, f1);
init();
}
template<class F0, class F1, class F2>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2)
: Policy(policy)
{
connectInput(f0, f1, f2);
init();
}
template<class F0, class F1, class F2, class F3>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2, F3& f3)
: Policy(policy)
{
connectInput(f0, f1, f2, f3);
init();
}
template<class F0, class F1, class F2, class F3, class F4>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2, F3& f3, F4& f4)
: Policy(policy)
{
connectInput(f0, f1, f2, f3, f4);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5)
: Policy(policy)
{
connectInput(f0, f1, f2, f3, f4, f5);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6)
: Policy(policy)
{
connectInput(f0, f1, f2, f3, f4, f5, f6);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7)
: Policy(policy)
{
connectInput(f0, f1, f2, f3, f4, f5, f6, f7);
init();
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7, class F8>
Synchronizer(const Policy& policy, F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7, F8& f8)
: Policy(policy)
{
connectInput(f0, f1, f2, f3, f4, f5, f6, f7, f8);
init();
}
Synchronizer(const Policy& policy)
: Policy(policy)
{
init();
}
~Synchronizer()
{
disconnectAll();
}
void init()
{
Policy::initParent(this);
}
template<class F0, class F1>
void connectInput(F0& f0, F1& f1)
{
NullFilter<M2> f2;
connectInput(f0, f1, f2);
}
template<class F0, class F1, class F2>
void connectInput(F0& f0, F1& f1, F2& f2)
{
NullFilter<M3> f3;
connectInput(f0, f1, f2, f3);
}
template<class F0, class F1, class F2, class F3>
void connectInput(F0& f0, F1& f1, F2& f2, F3& f3)
{
NullFilter<M4> f4;
connectInput(f0, f1, f2, f3, f4);
}
template<class F0, class F1, class F2, class F3, class F4>
void connectInput(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4)
{
NullFilter<M5> f5;
connectInput(f0, f1, f2, f3, f4, f5);
}
template<class F0, class F1, class F2, class F3, class F4, class F5>
void connectInput(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5)
{
NullFilter<M6> f6;
connectInput(f0, f1, f2, f3, f4, f5, f6);
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6>
void connectInput(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6)
{
NullFilter<M7> f7;
connectInput(f0, f1, f2, f3, f4, f5, f6, f7);
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7>
void connectInput(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7)
{
NullFilter<M8> f8;
connectInput(f0, f1, f2, f3, f4, f5, f6, f7, f8);
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7, class F8>
void connectInput(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7, F8& f8)
{
disconnectAll();
input_connections_[0] = f0.registerCallback(boost::function<void(const M0Event&)>(boost::bind(&Synchronizer::template cb<0>, this, _1)));
input_connections_[1] = f1.registerCallback(boost::function<void(const M1Event&)>(boost::bind(&Synchronizer::template cb<1>, this, _1)));
input_connections_[2] = f2.registerCallback(boost::function<void(const M2Event&)>(boost::bind(&Synchronizer::template cb<2>, this, _1)));
input_connections_[3] = f3.registerCallback(boost::function<void(const M3Event&)>(boost::bind(&Synchronizer::template cb<3>, this, _1)));
input_connections_[4] = f4.registerCallback(boost::function<void(const M4Event&)>(boost::bind(&Synchronizer::template cb<4>, this, _1)));
input_connections_[5] = f5.registerCallback(boost::function<void(const M5Event&)>(boost::bind(&Synchronizer::template cb<5>, this, _1)));
input_connections_[6] = f6.registerCallback(boost::function<void(const M6Event&)>(boost::bind(&Synchronizer::template cb<6>, this, _1)));
input_connections_[7] = f7.registerCallback(boost::function<void(const M7Event&)>(boost::bind(&Synchronizer::template cb<7>, this, _1)));
input_connections_[8] = f8.registerCallback(boost::function<void(const M8Event&)>(boost::bind(&Synchronizer::template cb<8>, this, _1)));
}
template<class C>
Connection registerCallback(C& callback)
{
return signal_.addCallback(callback);
}
template<class C>
Connection registerCallback(const C& callback)
{
return signal_.addCallback(callback);
}
template<class C, typename T>
Connection registerCallback(const C& callback, T* t)
{
return signal_.addCallback(callback, t);
}
template<class C, typename T>
Connection registerCallback(C& callback, T* t)
{
return signal_.addCallback(callback, t);
}
void setName(const std::string& name) { name_ = name; }
const std::string& getName() { return name_; }
void signal(const M0Event& e0, const M1Event& e1, const M2Event& e2, const M3Event& e3, const M4Event& e4,
const M5Event& e5, const M6Event& e6, const M7Event& e7, const M8Event& e8)
{
signal_.call(e0, e1, e2, e3, e4, e5, e6, e7, e8);
}
Policy* getPolicy() { return static_cast<Policy*>(this); }
using Policy::add;
template<int i>
void add(const boost::shared_ptr<typename mpl::at_c<Messages, i>::type const>& msg)
{
this->template add<i>(typename mpl::at_c<Events, i>::type(msg));
}
private:
void disconnectAll()
{
for (int i = 0; i < MAX_MESSAGES; ++i)
{
input_connections_[i].disconnect();
}
}
template<int i>
void cb(const typename mpl::at_c<Events, i>::type& evt)
{
this->add<i>(evt);
}
uint32_t queue_size_;
Signal signal_;
Connection input_connections_[MAX_MESSAGES];
std::string name_;
};
template<typename M0, typename M1, typename M2, typename M3, typename M4,
typename M5, typename M6, typename M7, typename M8>
struct PolicyBase
{
typedef mpl::vector<M0, M1, M2, M3, M4, M5, M6, M7, M8> Messages;
typedef Signal9<M0, M1, M2, M3, M4, M5, M6, M7, M8> Signal;
typedef mpl::vector<ros::MessageEvent<M0 const>, ros::MessageEvent<M1 const>, ros::MessageEvent<M2 const>, ros::MessageEvent<M3 const>,
ros::MessageEvent<M4 const>, ros::MessageEvent<M5 const>, ros::MessageEvent<M6 const>, ros::MessageEvent<M7 const>,
ros::MessageEvent<M8 const> > Events;
typedef typename mpl::fold<Messages, mpl::int_<0>, mpl::if_<mpl::not_<boost::is_same<mpl::_2, NullType> >, mpl::next<mpl::_1>, mpl::_1> >::type RealTypeCount;
typedef typename mpl::at_c<Events, 0>::type M0Event;
typedef typename mpl::at_c<Events, 1>::type M1Event;
typedef typename mpl::at_c<Events, 2>::type M2Event;
typedef typename mpl::at_c<Events, 3>::type M3Event;
typedef typename mpl::at_c<Events, 4>::type M4Event;
typedef typename mpl::at_c<Events, 5>::type M5Event;
typedef typename mpl::at_c<Events, 6>::type M6Event;
typedef typename mpl::at_c<Events, 7>::type M7Event;
typedef typename mpl::at_c<Events, 8>::type M8Event;
};
} // namespace message_filters
#endif // MESSAGE_FILTERS_SYNCHRONIZER_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/simple_filter.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SIMPLE_FILTER_H
#define MESSAGE_FILTERS_SIMPLE_FILTER_H
#include <boost/noncopyable.hpp>
#include "connection.h"
#include "signal1.h"
#include <ros/message_event.h>
#include <ros/subscription_callback_helper.h>
#include <boost/bind.hpp>
#include <string>
namespace message_filters
{
/**
* \brief Convenience base-class for simple filters which output a single message
*
* SimpleFilter provides some of the tricky callback registering functionality, so that
* simple filters do not have to duplicate it. It also provides getName()/setName() for debugging
* purposes.
*/
template<class M>
class SimpleFilter : public boost::noncopyable
{
public:
typedef boost::shared_ptr<M const> MConstPtr;
typedef boost::function<void(const MConstPtr&)> Callback;
typedef ros::MessageEvent<M const> EventType;
typedef boost::function<void(const EventType&)> EventCallback;
/**
* \brief Register a callback to be called when this filter has passed
* \param callback The callback to call
*/
template<typename C>
Connection registerCallback(const C& callback)
{
typename CallbackHelper1<M>::Ptr helper = signal_.addCallback(Callback(callback));
return Connection(boost::bind(&Signal::removeCallback, &signal_, helper));
}
/**
* \brief Register a callback to be called when this filter has passed
* \param callback The callback to call
*/
template<typename P>
Connection registerCallback(const boost::function<void(P)>& callback)
{
return Connection(boost::bind(&Signal::removeCallback, &signal_, signal_.addCallback(callback)));
}
/**
* \brief Register a callback to be called when this filter has passed
* \param callback The callback to call
*/
template<typename P>
Connection registerCallback(void(*callback)(P))
{
return Connection(boost::bind(&Signal::removeCallback, &signal_, signal_.addCallback(callback)));
}
/**
* \brief Register a callback to be called when this filter has passed
* \param callback The callback to call
*/
template<typename T, typename P>
Connection registerCallback(void(T::*callback)(P), T* t)
{
typename CallbackHelper1<M>::Ptr helper = signal_.template addCallback<P>(boost::bind(callback, t, _1));
return Connection(boost::bind(&Signal::removeCallback, &signal_, helper));
}
/**
* \brief Set the name of this filter. For debugging use.
*/
void setName(const std::string& name) { name_ = name; }
/**
* \brief Get the name of this filter. For debugging use.
*/
const std::string& getName() { return name_; }
protected:
/**
* \brief Call all registered callbacks, passing them the specified message
*/
void signalMessage(const MConstPtr& msg)
{
ros::MessageEvent<M const> event(msg);
signal_.call(event);
}
/**
* \brief Call all registered callbacks, passing them the specified message
*/
void signalMessage(const ros::MessageEvent<M const>& event)
{
signal_.call(event);
}
private:
typedef Signal1<M> Signal;
Signal signal_;
std::string name_;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/cache.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_CACHE_H_
#define MESSAGE_FILTERS_CACHE_H_
#include <deque>
#include "boost/thread.hpp"
#include "boost/shared_ptr.hpp"
#include "ros/time.h"
#include "connection.h"
#include "simple_filter.h"
namespace message_filters
{
/**
* \brief Stores a time history of messages
*
* Given a stream of messages, the most recent N messages are cached in a ring buffer,
* from which time intervals of the cache can then be retrieved by the client.
*
* Cache immediately passes messages through to its output connections.
*
* \section connections CONNECTIONS
*
* Cache's input and output connections are both of the same signature as roscpp subscription callbacks, ie.
\verbatim
void callback(const boost::shared_ptr<M const>&);
\endverbatim
*/
template<class M>
class Cache : public SimpleFilter<M>
{
public:
typedef boost::shared_ptr<M const> MConstPtr;
typedef ros::MessageEvent<M const> EventType;
template<class F>
Cache(F& f, unsigned int cache_size = 1)
{
setCacheSize(cache_size) ;
connectInput(f) ;
}
/**
* Initializes a Message Cache without specifying a parent filter. This implies that in
* order to populate the cache, the user then has to call add themselves, or connectInput() is
* called later
*/
Cache(unsigned int cache_size = 1)
{
setCacheSize(cache_size);
}
template<class F>
void connectInput(F& f)
{
incoming_connection_ = f.registerCallback(typename SimpleFilter<M>::EventCallback(boost::bind(&Cache::callback, this, _1)));
}
~Cache()
{
incoming_connection_.disconnect();
}
/**
* Set the size of the cache.
* \param cache_size The new size the cache should be. Must be > 0
*/
void setCacheSize(unsigned int cache_size)
{
if (cache_size == 0)
{
//ROS_ERROR("Cannot set max_size to 0") ;
return ;
}
cache_size_ = cache_size ;
}
/**
* \brief Add a message to the cache, and pop off any elements that are too old.
* This method is registered with a data provider when connectTo is called.
*/
void add(const MConstPtr& msg)
{
add(EventType(msg));
}
/**
* \brief Add a message to the cache, and pop off any elements that are too old.
* This method is registered with a data provider when connectTo is called.
*/
void add(const EventType& evt)
{
namespace mt = ros::message_traits;
//printf(" Cache Size: %u\n", cache_.size()) ;
{
boost::mutex::scoped_lock lock(cache_lock_);
while (cache_.size() >= cache_size_) // Keep popping off old data until we have space for a new msg
cache_.pop_front() ; // The front of the deque has the oldest elem, so we can get rid of it
// No longer naively pushing msgs to back. Want to make sure they're sorted correctly
//cache_.push_back(msg) ; // Add the newest message to the back of the deque
typename std::deque<EventType >::reverse_iterator rev_it = cache_.rbegin();
// Keep walking backwards along deque until we hit the beginning,
// or until we find a timestamp that's smaller than (or equal to) msg's timestamp
ros::Time evt_stamp = mt::TimeStamp<M>::value(*evt.getMessage());
while(rev_it != cache_.rend() && mt::TimeStamp<M>::value(*(*rev_it).getMessage()) > evt_stamp)
rev_it++;
// Add msg to the cache
cache_.insert(rev_it.base(), evt);
}
this->signalMessage(evt);
}
/**
* \brief Receive a vector of messages that occur between a start and end time (inclusive).
*
* This call is non-blocking, and only aggregates messages it has already received.
* It will not wait for messages have not yet been received, but occur in the interval.
* \param start The start of the requested interval
* \param end The end of the requested interval
*/
std::vector<MConstPtr> getInterval(const ros::Time& start, const ros::Time& end) const
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(cache_lock_);
// Find the starting index. (Find the first index after [or at] the start of the interval)
unsigned int start_index = 0 ;
while(start_index < cache_.size() &&
mt::TimeStamp<M>::value(*cache_[start_index].getMessage()) < start)
{
start_index++ ;
}
// Find the ending index. (Find the first index after the end of interval)
unsigned int end_index = start_index ;
while(end_index < cache_.size() &&
mt::TimeStamp<M>::value(*cache_[end_index].getMessage()) <= end)
{
end_index++ ;
}
std::vector<MConstPtr> interval_elems ;
interval_elems.reserve(end_index - start_index) ;
for (unsigned int i=start_index; i<end_index; i++)
{
interval_elems.push_back(cache_[i].getMessage()) ;
}
return interval_elems ;
}
/**
* \brief Retrieve the smallest interval of messages that surrounds an interval from start to end.
*
* If the messages in the cache do not surround (start,end), then this will return the interval
* that gets closest to surrounding (start,end)
*/
std::vector<MConstPtr> getSurroundingInterval(const ros::Time& start, const ros::Time& end) const
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(cache_lock_);
// Find the starting index. (Find the first index after [or at] the start of the interval)
unsigned int start_index = cache_.size()-1;
while(start_index > 0 &&
mt::TimeStamp<M>::value(*cache_[start_index].getMessage()) > start)
{
start_index--;
}
unsigned int end_index = start_index;
while(end_index < cache_.size()-1 &&
mt::TimeStamp<M>::value(*cache_[end_index].getMessage()) < end)
{
end_index++;
}
std::vector<MConstPtr> interval_elems;
interval_elems.reserve(end_index - start_index + 1) ;
for (unsigned int i=start_index; i<=end_index; i++)
{
interval_elems.push_back(cache_[i].getMessage()) ;
}
return interval_elems;
}
/**
* \brief Grab the newest element that occurs right before the specified time.
* \param time Time that must occur right after the returned elem
* \returns shared_ptr to the newest elem that occurs before 'time'. NULL if doesn't exist
*/
MConstPtr getElemBeforeTime(const ros::Time& time) const
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(cache_lock_);
MConstPtr out ;
unsigned int i=0 ;
int elem_index = -1 ;
while (i<cache_.size() &&
mt::TimeStamp<M>::value(*cache_[i].getMessage()) < time)
{
elem_index = i ;
i++ ;
}
if (elem_index >= 0)
out = cache_[elem_index].getMessage() ;
return out ;
}
/**
* \brief Grab the oldest element that occurs right after the specified time.
* \param time Time that must occur right before the returned elem
* \returns shared_ptr to the oldest elem that occurs after 'time'. NULL if doesn't exist
*/
MConstPtr getElemAfterTime(const ros::Time& time) const
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(cache_lock_);
MConstPtr out ;
int i=cache_.size()-1 ;
int elem_index = -1 ;
while (i>=0 &&
mt::TimeStamp<M>::value(*cache_[i].getMessage()) > time)
{
elem_index = i ;
i-- ;
}
if (elem_index >= 0)
out = cache_[elem_index].getMessage() ;
else
out.reset() ;
return out ;
}
/**
* \brief Returns the timestamp associated with the newest packet cache
*/
ros::Time getLatestTime() const
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(cache_lock_);
ros::Time latest_time;
if (cache_.size() > 0)
latest_time = mt::TimeStamp<M>::value(*cache_.back().getMessage());
return latest_time ;
}
/**
* \brief Returns the timestamp associated with the oldest packet cache
*/
ros::Time getOldestTime() const
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(cache_lock_);
ros::Time oldest_time;
if (cache_.size() > 0)
oldest_time = mt::TimeStamp<M>::value(*cache_.front().getMessage());
return oldest_time ;
}
private:
void callback(const EventType& evt)
{
add(evt);
}
mutable boost::mutex cache_lock_ ; //!< Lock for cache_
std::deque<EventType> cache_ ; //!< Cache for the messages
unsigned int cache_size_ ; //!< Maximum number of elements allowed in the cache.
Connection incoming_connection_;
};
}
#endif /* MESSAGE_FILTERS_CACHE_H_ */
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/signal1.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SIGNAL1_H
#define MESSAGE_FILTERS_SIGNAL1_H
#include <boost/noncopyable.hpp>
#include "connection.h"
#include <ros/message_event.h>
#include <ros/parameter_adapter.h>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
namespace message_filters
{
template<class M>
class CallbackHelper1
{
public:
virtual ~CallbackHelper1() {}
virtual void call(const ros::MessageEvent<M const>& event, bool nonconst_need_copy) = 0;
typedef boost::shared_ptr<CallbackHelper1<M> > Ptr;
};
template<typename P, typename M>
class CallbackHelper1T : public CallbackHelper1<M>
{
public:
typedef ros::ParameterAdapter<P> Adapter;
typedef boost::function<void(typename Adapter::Parameter)> Callback;
typedef typename Adapter::Event Event;
CallbackHelper1T(const Callback& cb)
: callback_(cb)
{
}
virtual void call(const ros::MessageEvent<M const>& event, bool nonconst_force_copy)
{
Event my_event(event, nonconst_force_copy || event.nonConstWillCopy());
callback_(Adapter::getParameter(my_event));
}
private:
Callback callback_;
};
template<class M>
class Signal1
{
typedef boost::shared_ptr<CallbackHelper1<M> > CallbackHelper1Ptr;
typedef std::vector<CallbackHelper1Ptr> V_CallbackHelper1;
public:
template<typename P>
CallbackHelper1Ptr addCallback(const boost::function<void(P)>& callback)
{
CallbackHelper1T<P, M>* helper = new CallbackHelper1T<P, M>(callback);
boost::mutex::scoped_lock lock(mutex_);
callbacks_.push_back(CallbackHelper1Ptr(helper));
return callbacks_.back();
}
void removeCallback(const CallbackHelper1Ptr& helper)
{
boost::mutex::scoped_lock lock(mutex_);
typename V_CallbackHelper1::iterator it = std::find(callbacks_.begin(), callbacks_.end(), helper);
if (it != callbacks_.end())
{
callbacks_.erase(it);
}
}
void call(const ros::MessageEvent<M const>& event)
{
boost::mutex::scoped_lock lock(mutex_);
bool nonconst_force_copy = callbacks_.size() > 1;
typename V_CallbackHelper1::iterator it = callbacks_.begin();
typename V_CallbackHelper1::iterator end = callbacks_.end();
for (; it != end; ++it)
{
const CallbackHelper1Ptr& helper = *it;
helper->call(event, nonconst_force_copy);
}
}
private:
boost::mutex mutex_;
V_CallbackHelper1 callbacks_;
};
} // message_filters
#endif // MESSAGE_FILTERS_SIGNAL1_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/time_synchronizer.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_TIME_SYNCHRONIZER_H
#define MESSAGE_FILTERS_TIME_SYNCHRONIZER_H
#include "synchronizer.h"
#include "sync_policies/exact_time.h"
#include <boost/shared_ptr.hpp>
#include <ros/message_event.h>
namespace message_filters
{
namespace mpl = boost::mpl;
/**
* \brief Synchronizes up to 9 messages by their timestamps.
*
* TimeSynchronizer synchronizes up to 9 incoming channels by the timestamps contained in their messages' headers.
* TimeSynchronizer takes anywhere from 2 to 9 message types as template parameters, and passes them through to a
* callback which takes a shared pointer of each.
*
* The required queue size parameter when constructing the TimeSynchronizer tells it how many sets of messages it should
* store (by timestamp) while waiting for messages to arrive and complete their "set"
*
* \section connections CONNECTIONS
*
* The input connections for the TimeSynchronizer object is the same signature as for roscpp subscription callbacks, ie.
\verbatim
void callback(const boost::shared_ptr<M const>&);
\endverbatim
* The output connection for the TimeSynchronizer object is dependent on the number of messages being synchronized. For
* a 3-message synchronizer for example, it would be:
\verbatim
void callback(const boost::shared_ptr<M0 const>&, const boost::shared_ptr<M1 const>&, const boost::shared_ptr<M2 const>&);
\endverbatim
* \section usage USAGE
* Example usage would be:
\verbatim
TimeSynchronizer<sensor_msgs::CameraInfo, sensor_msgs::Image, sensor_msgs::Image> sync_policies(caminfo_sub, limage_sub, rimage_sub, 3);
sync_policies.registerCallback(callback);
\endverbatim
* The callback is then of the form:
\verbatim
void callback(const sensor_msgs::CameraInfo::ConstPtr&, const sensor_msgs::Image::ConstPtr&, const sensor_msgs::Image::ConstPtr&);
\endverbatim
*
*/
template<class M0, class M1, class M2 = NullType, class M3 = NullType, class M4 = NullType,
class M5 = NullType, class M6 = NullType, class M7 = NullType, class M8 = NullType>
class TimeSynchronizer : public Synchronizer<sync_policies::ExactTime<M0, M1, M2, M3, M4, M5, M6, M7, M8> >
{
public:
typedef sync_policies::ExactTime<M0, M1, M2, M3, M4, M5, M6, M7, M8> Policy;
typedef Synchronizer<Policy> Base;
typedef boost::shared_ptr<M0 const> M0ConstPtr;
typedef boost::shared_ptr<M1 const> M1ConstPtr;
typedef boost::shared_ptr<M2 const> M2ConstPtr;
typedef boost::shared_ptr<M3 const> M3ConstPtr;
typedef boost::shared_ptr<M4 const> M4ConstPtr;
typedef boost::shared_ptr<M5 const> M5ConstPtr;
typedef boost::shared_ptr<M6 const> M6ConstPtr;
typedef boost::shared_ptr<M7 const> M7ConstPtr;
typedef boost::shared_ptr<M8 const> M8ConstPtr;
using Base::add;
using Base::connectInput;
using Base::registerCallback;
using Base::setName;
using Base::getName;
using Policy::registerDropCallback;
typedef typename Base::M0Event M0Event;
typedef typename Base::M1Event M1Event;
typedef typename Base::M2Event M2Event;
typedef typename Base::M3Event M3Event;
typedef typename Base::M4Event M4Event;
typedef typename Base::M5Event M5Event;
typedef typename Base::M6Event M6Event;
typedef typename Base::M7Event M7Event;
typedef typename Base::M8Event M8Event;
template<class F0, class F1>
TimeSynchronizer(F0& f0, F1& f1, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1);
}
template<class F0, class F1, class F2>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2);
}
template<class F0, class F1, class F2, class F3>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, F3& f3, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2, f3);
}
template<class F0, class F1, class F2, class F3, class F4>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2, f3, f4);
}
template<class F0, class F1, class F2, class F3, class F4, class F5>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2, f3, f4, f5);
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2, f3, f4, f5, f6);
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2, f3, f4, f5, f6, f7);
}
template<class F0, class F1, class F2, class F3, class F4, class F5, class F6, class F7, class F8>
TimeSynchronizer(F0& f0, F1& f1, F2& f2, F3& f3, F4& f4, F5& f5, F6& f6, F7& f7, F8& f8, uint32_t queue_size)
: Base(Policy(queue_size))
{
connectInput(f0, f1, f2, f3, f4, f5, f6, f7, f8);
}
TimeSynchronizer(uint32_t queue_size)
: Base(Policy(queue_size))
{
}
////////////////////////////////////////////////////////////////
// For backwards compatibility
////////////////////////////////////////////////////////////////
void add0(const M0ConstPtr& msg)
{
this->template add<0>(M0Event(msg));
}
void add1(const M1ConstPtr& msg)
{
this->template add<1>(M1Event(msg));
}
void add2(const M2ConstPtr& msg)
{
this->template add<2>(M2Event(msg));
}
void add3(const M3ConstPtr& msg)
{
this->template add<3>(M3Event(msg));
}
void add4(const M4ConstPtr& msg)
{
this->template add<4>(M4Event(msg));
}
void add5(const M5ConstPtr& msg)
{
this->template add<5>(M5Event(msg));
}
void add6(const M6ConstPtr& msg)
{
this->template add<6>(M6Event(msg));
}
void add7(const M7ConstPtr& msg)
{
this->template add<7>(M7Event(msg));
}
void add8(const M8ConstPtr& msg)
{
this->template add<8>(M8Event(msg));
}
};
}
#endif // MESSAGE_FILTERS_TIME_SYNCHRONIZER_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/subscriber.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SUBSCRIBER_H
#define MESSAGE_FILTERS_SUBSCRIBER_H
#include <ros/ros.h>
#include <boost/thread/mutex.hpp>
#include "connection.h"
#include "simple_filter.h"
namespace message_filters
{
class SubscriberBase
{
public:
virtual ~SubscriberBase() {}
/**
* \brief Subscribe to a topic.
*
* If this Subscriber is already subscribed to a topic, this function will first unsubscribe.
*
* \param nh The ros::NodeHandle to use to subscribe.
* \param topic The topic to subscribe to.
* \param queue_size The subscription queue size
* \param transport_hints The transport hints to pass along
* \param callback_queue The callback queue to pass along
*/
virtual void subscribe(ros::NodeHandle& nh, const std::string& topic, uint32_t queue_size, const ros::TransportHints& transport_hints = ros::TransportHints(), ros::CallbackQueueInterface* callback_queue = 0) = 0;
/**
* \brief Re-subscribe to a topic. Only works if this subscriber has previously been subscribed to a topic.
*/
virtual void subscribe() = 0;
/**
* \brief Force immediate unsubscription of this subscriber from its topic
*/
virtual void unsubscribe() = 0;
};
typedef boost::shared_ptr<SubscriberBase> SubscriberBasePtr;
/**
* \brief ROS subscription filter.
*
* This class acts as a highest-level filter, simply passing messages from a ROS subscription through to the
* filters which have connected to it.
*
* When this object is destroyed it will unsubscribe from the ROS subscription.
*
* The Subscriber object is templated on the type of message being subscribed to.
*
* \section connections CONNECTIONS
*
* Subscriber has no input connection.
*
* The output connection for the Subscriber object is the same signature as for roscpp subscription callbacks, ie.
\verbatim
void callback(const boost::shared_ptr<M const>&);
\endverbatim
*/
template<class M>
class Subscriber : public SubscriberBase, public SimpleFilter<M>
{
public:
typedef boost::shared_ptr<M const> MConstPtr;
typedef ros::MessageEvent<M const> EventType;
/**
* \brief Constructor
*
* See the ros::NodeHandle::subscribe() variants for more information on the parameters
*
* \param nh The ros::NodeHandle to use to subscribe.
* \param topic The topic to subscribe to.
* \param queue_size The subscription queue size
* \param transport_hints The transport hints to pass along
* \param callback_queue The callback queue to pass along
*/
Subscriber(ros::NodeHandle& nh, const std::string& topic, uint32_t queue_size, const ros::TransportHints& transport_hints = ros::TransportHints(), ros::CallbackQueueInterface* callback_queue = 0)
{
subscribe(nh, topic, queue_size, transport_hints, callback_queue);
}
/**
* \brief Empty constructor, use subscribe() to subscribe to a topic
*/
Subscriber()
{
}
~Subscriber()
{
unsubscribe();
}
/**
* \brief Subscribe to a topic.
*
* If this Subscriber is already subscribed to a topic, this function will first unsubscribe.
*
* \param nh The ros::NodeHandle to use to subscribe.
* \param topic The topic to subscribe to.
* \param queue_size The subscription queue size
* \param transport_hints The transport hints to pass along
* \param callback_queue The callback queue to pass along
*/
void subscribe(ros::NodeHandle& nh, const std::string& topic, uint32_t queue_size, const ros::TransportHints& transport_hints = ros::TransportHints(), ros::CallbackQueueInterface* callback_queue = 0)
{
unsubscribe();
if (!topic.empty())
{
ops_.template initByFullCallbackType<const EventType&>(topic, queue_size, boost::bind(&Subscriber<M>::cb, this, _1));
ops_.callback_queue = callback_queue;
ops_.transport_hints = transport_hints;
sub_ = nh.subscribe(ops_);
nh_ = nh;
}
}
/**
* \brief Re-subscribe to a topic. Only works if this subscriber has previously been subscribed to a topic.
*/
void subscribe()
{
unsubscribe();
if (!ops_.topic.empty())
{
sub_ = nh_.subscribe(ops_);
}
}
/**
* \brief Force immediate unsubscription of this subscriber from its topic
*/
void unsubscribe()
{
sub_.shutdown();
}
std::string getTopic() const
{
return ops_.topic;
}
/**
* \brief Returns the internal ros::Subscriber object
*/
const ros::Subscriber& getSubscriber() const { return sub_; }
/**
* \brief Does nothing. Provided so that Subscriber may be used in a message_filters::Chain
*/
template<typename F>
void connectInput(F& f)
{
(void)f;
}
/**
* \brief Does nothing. Provided so that Subscriber may be used in a message_filters::Chain
*/
void add(const EventType& e)
{
(void)e;
}
private:
void cb(const EventType& e)
{
this->signalMessage(e);
}
ros::Subscriber sub_;
ros::SubscribeOptions ops_;
ros::NodeHandle nh_;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/null_types.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_NULL_TYPES_H
#define MESSAGE_FILTERS_NULL_TYPES_H
#include "connection.h"
#include <boost/shared_ptr.hpp>
#include <ros/time.h>
#include <ros/message_traits.h>
namespace message_filters
{
struct NullType
{
};
typedef boost::shared_ptr<NullType const> NullTypeConstPtr;
template<class M>
struct NullFilter
{
template<typename C>
Connection registerCallback(const C&)
{
return Connection();
}
template<typename P>
Connection registerCallback(const boost::function<void(P)>&)
{
return Connection();
}
};
}
namespace ros
{
namespace message_traits
{
template<>
struct TimeStamp<message_filters::NullType>
{
static ros::Time value(const message_filters::NullType&)
{
return ros::Time();
}
};
}
}
#endif // MESSAGE_FILTERS_NULL_TYPES_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/macros.h | /*
* Copyright (C) 2008, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MESSAGE_FILTERS_MACROS_H_
#define MESSAGE_FILTERS_MACROS_H_
#include <ros/macros.h> // for the DECL's
// Import/export for windows dll's and visibility for gcc shared libraries.
#ifdef ROS_BUILD_SHARED_LIBS // ros is being built around shared libraries
#ifdef message_filters_EXPORTS // we are building a shared lib/dll
#define MESSAGE_FILTERS_DECL ROS_HELPER_EXPORT
#else // we are using shared lib/dll
#define MESSAGE_FILTERS_DECL ROS_HELPER_IMPORT
#endif
#else // ros is being built around static libraries
#define MESSAGE_FILTERS_DECL
#endif
#endif /* MESSAGE_FILTERS_MACROS_H_ */
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/time_sequencer.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_TIME_SEQUENCER_H
#define MESSAGE_FILTERS_TIME_SEQUENCER_H
#include <ros/ros.h>
#include "connection.h"
#include "simple_filter.h"
namespace message_filters
{
/**
* \class TimeSequencer
*
* \brief Sequences messages based on the timestamp of their header.
*
* The TimeSequencer object is templated on the type of message being sequenced.
*
* \section behavior BEHAVIOR
* At construction, the TimeSequencer takes a ros::Duration
* "delay" which specifies how long to queue up messages to
* provide a time sequencing over them. As messages arrive they are
* sorted according to their time stamps. A callback for a message is
* never invoked until the messages' time stamp is out of date by at
* least delay. However, for all messages which are out of date
* by at least delay, their callback are invoked and guaranteed
* to be in temporal order. If a message arrives from a time \b prior
* to a message which has already had its callback invoked, it is
* thrown away.
*
* \section connections CONNECTIONS
*
* TimeSequencer's input and output connections are both of the same signature as roscpp subscription callbacks, ie.
\verbatim
void callback(const boost::shared_ptr<M const>&);
\endverbatim
*
*/
template<class M>
class TimeSequencer : public SimpleFilter<M>
{
public:
typedef boost::shared_ptr<M const> MConstPtr;
typedef ros::MessageEvent<M const> EventType;
/**
* \brief Constructor
* \param f A filter to connect this sequencer's input to
* \param delay The minimum time to hold a message before passing it through.
* \param update_rate The rate at which to check for messages which have passed "delay"
* \param queue_size The number of messages to store
* \param nh (optional) The NodeHandle to use to create the ros::Timer that runs at update_rate
*/
template<class F>
TimeSequencer(F& f, ros::Duration delay, ros::Duration update_rate, uint32_t queue_size, ros::NodeHandle nh = ros::NodeHandle())
: delay_(delay)
, update_rate_(update_rate)
, queue_size_(queue_size)
, nh_(nh)
{
init();
connectInput(f);
}
/**
* \brief Constructor
*
* This version of the constructor does not take a filter immediately. You can connect to a filter later with the connectInput() function
*
* \param delay The minimum time to hold a message before passing it through.
* \param update_rate The rate at which to check for messages which have passed "delay"
* \param queue_size The number of messages to store
* \param nh (optional) The NodeHandle to use to create the ros::Timer that runs at update_rate
*/
TimeSequencer(ros::Duration delay, ros::Duration update_rate, uint32_t queue_size, ros::NodeHandle nh = ros::NodeHandle())
: delay_(delay)
, update_rate_(update_rate)
, queue_size_(queue_size)
, nh_(nh)
{
init();
}
/**
* \brief Connect this filter's input to another filter's output.
*/
template<class F>
void connectInput(F& f)
{
incoming_connection_.disconnect();
incoming_connection_ = f.registerCallback(typename SimpleFilter<M>::EventCallback(boost::bind(&TimeSequencer::cb, this, _1)));
}
~TimeSequencer()
{
update_timer_.stop();
incoming_connection_.disconnect();
}
void add(const EventType& evt)
{
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(messages_mutex_);
if (mt::TimeStamp<M>::value(*evt.getMessage()) < last_time_)
{
return;
}
messages_.insert(evt);
if (queue_size_ != 0 && messages_.size() > queue_size_)
{
messages_.erase(*messages_.begin());
}
}
/**
* \brief Manually add a message to the cache.
*/
void add(const MConstPtr& msg)
{
EventType evt(msg);
add(evt);
}
private:
class MessageSort
{
public:
bool operator()(const EventType& lhs, const EventType& rhs) const
{
namespace mt = ros::message_traits;
return mt::TimeStamp<M>::value(*lhs.getMessage()) < mt::TimeStamp<M>::value(*rhs.getMessage());
}
};
typedef std::multiset<EventType, MessageSort> S_Message;
typedef std::vector<EventType> V_Message;
void cb(const EventType& evt)
{
add(evt);
}
void dispatch()
{
namespace mt = ros::message_traits;
V_Message to_call;
{
boost::mutex::scoped_lock lock(messages_mutex_);
while (!messages_.empty())
{
const EventType& e = *messages_.begin();
ros::Time stamp = mt::TimeStamp<M>::value(*e.getMessage());
if (stamp + delay_ <= ros::Time::now())
{
last_time_ = stamp;
to_call.push_back(e);
messages_.erase(messages_.begin());
}
else
{
break;
}
}
}
{
typename V_Message::iterator it = to_call.begin();
typename V_Message::iterator end = to_call.end();
for (; it != end; ++it)
{
this->signalMessage(*it);
}
}
}
void update(const ros::TimerEvent&)
{
dispatch();
}
void init()
{
update_timer_ = nh_.createTimer(update_rate_, &TimeSequencer::update, this);
}
ros::Duration delay_;
ros::Duration update_rate_;
uint32_t queue_size_;
ros::NodeHandle nh_;
ros::Timer update_timer_;
Connection incoming_connection_;
S_Message messages_;
boost::mutex messages_mutex_;
ros::Time last_time_;
};
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/signal9.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SIGNAL9_H
#define MESSAGE_FILTERS_SIGNAL9_H
#include <boost/noncopyable.hpp>
#include "connection.h"
#include "null_types.h"
#include <ros/message_event.h>
#include <ros/parameter_adapter.h>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
namespace message_filters
{
using ros::ParameterAdapter;
template<typename M0, typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8>
class CallbackHelper9
{
public:
typedef ros::MessageEvent<M0 const> M0Event;
typedef ros::MessageEvent<M1 const> M1Event;
typedef ros::MessageEvent<M2 const> M2Event;
typedef ros::MessageEvent<M3 const> M3Event;
typedef ros::MessageEvent<M4 const> M4Event;
typedef ros::MessageEvent<M5 const> M5Event;
typedef ros::MessageEvent<M6 const> M6Event;
typedef ros::MessageEvent<M7 const> M7Event;
typedef ros::MessageEvent<M8 const> M8Event;
virtual ~CallbackHelper9() {}
virtual void call(bool nonconst_force_copy, const M0Event& e0, const M1Event& e1, const M2Event& e2, const M3Event& e3,
const M4Event& e4, const M5Event& e5, const M6Event& e6, const M7Event& e7, const M8Event& e8) = 0;
typedef boost::shared_ptr<CallbackHelper9> Ptr;
};
template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8>
class CallbackHelper9T :
public CallbackHelper9<typename ParameterAdapter<P0>::Message,
typename ParameterAdapter<P1>::Message,
typename ParameterAdapter<P2>::Message,
typename ParameterAdapter<P3>::Message,
typename ParameterAdapter<P4>::Message,
typename ParameterAdapter<P5>::Message,
typename ParameterAdapter<P6>::Message,
typename ParameterAdapter<P7>::Message,
typename ParameterAdapter<P8>::Message>
{
private:
typedef ParameterAdapter<P0> A0;
typedef ParameterAdapter<P1> A1;
typedef ParameterAdapter<P2> A2;
typedef ParameterAdapter<P3> A3;
typedef ParameterAdapter<P4> A4;
typedef ParameterAdapter<P5> A5;
typedef ParameterAdapter<P6> A6;
typedef ParameterAdapter<P7> A7;
typedef ParameterAdapter<P8> A8;
typedef typename A0::Event M0Event;
typedef typename A1::Event M1Event;
typedef typename A2::Event M2Event;
typedef typename A3::Event M3Event;
typedef typename A4::Event M4Event;
typedef typename A5::Event M5Event;
typedef typename A6::Event M6Event;
typedef typename A7::Event M7Event;
typedef typename A8::Event M8Event;
public:
typedef boost::function<void(typename A0::Parameter, typename A1::Parameter, typename A2::Parameter,
typename A3::Parameter, typename A4::Parameter, typename A5::Parameter,
typename A6::Parameter, typename A7::Parameter, typename A8::Parameter)> Callback;
CallbackHelper9T(const Callback& cb)
: callback_(cb)
{
}
virtual void call(bool nonconst_force_copy, const M0Event& e0, const M1Event& e1, const M2Event& e2, const M3Event& e3,
const M4Event& e4, const M5Event& e5, const M6Event& e6, const M7Event& e7, const M8Event& e8)
{
M0Event my_e0(e0, nonconst_force_copy || e0.nonConstWillCopy());
M1Event my_e1(e1, nonconst_force_copy || e0.nonConstWillCopy());
M2Event my_e2(e2, nonconst_force_copy || e0.nonConstWillCopy());
M3Event my_e3(e3, nonconst_force_copy || e0.nonConstWillCopy());
M4Event my_e4(e4, nonconst_force_copy || e0.nonConstWillCopy());
M5Event my_e5(e5, nonconst_force_copy || e0.nonConstWillCopy());
M6Event my_e6(e6, nonconst_force_copy || e0.nonConstWillCopy());
M7Event my_e7(e7, nonconst_force_copy || e0.nonConstWillCopy());
M8Event my_e8(e8, nonconst_force_copy || e0.nonConstWillCopy());
callback_(A0::getParameter(e0),
A1::getParameter(e1),
A2::getParameter(e2),
A3::getParameter(e3),
A4::getParameter(e4),
A5::getParameter(e5),
A6::getParameter(e6),
A7::getParameter(e7),
A8::getParameter(e8));
}
private:
Callback callback_;
};
template<typename M0, typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8>
class Signal9
{
typedef boost::shared_ptr<CallbackHelper9<M0, M1, M2, M3, M4, M5, M6, M7, M8> > CallbackHelper9Ptr;
typedef std::vector<CallbackHelper9Ptr> V_CallbackHelper9;
public:
typedef ros::MessageEvent<M0 const> M0Event;
typedef ros::MessageEvent<M1 const> M1Event;
typedef ros::MessageEvent<M2 const> M2Event;
typedef ros::MessageEvent<M3 const> M3Event;
typedef ros::MessageEvent<M4 const> M4Event;
typedef ros::MessageEvent<M5 const> M5Event;
typedef ros::MessageEvent<M6 const> M6Event;
typedef ros::MessageEvent<M7 const> M7Event;
typedef ros::MessageEvent<M8 const> M8Event;
typedef boost::shared_ptr<M0 const> M0ConstPtr;
typedef boost::shared_ptr<M1 const> M1ConstPtr;
typedef boost::shared_ptr<M2 const> M2ConstPtr;
typedef boost::shared_ptr<M3 const> M3ConstPtr;
typedef boost::shared_ptr<M4 const> M4ConstPtr;
typedef boost::shared_ptr<M5 const> M5ConstPtr;
typedef boost::shared_ptr<M6 const> M6ConstPtr;
typedef boost::shared_ptr<M7 const> M7ConstPtr;
typedef boost::shared_ptr<M8 const> M8ConstPtr;
typedef const boost::shared_ptr<NullType const>& NullP;
template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8>
Connection addCallback(const boost::function<void(P0, P1, P2, P3, P4, P5, P6, P7, P8)>& callback)
{
CallbackHelper9T<P0, P1, P2, P3, P4, P5, P6, P7, P8>* helper = new CallbackHelper9T<P0, P1, P2, P3, P4, P5, P6, P7, P8>(callback);
boost::mutex::scoped_lock lock(mutex_);
callbacks_.push_back(CallbackHelper9Ptr(helper));
return Connection(boost::bind(&Signal9::removeCallback, this, callbacks_.back()));
}
template<typename P0, typename P1>
Connection addCallback(void(*callback)(P0, P1))
{
return addCallback(boost::function<void(P0, P1, NullP, NullP, NullP, NullP, NullP, NullP, NullP)>(boost::bind(callback, _1, _2)));
}
template<typename P0, typename P1, typename P2>
Connection addCallback(void(*callback)(P0, P1, P2))
{
return addCallback(boost::function<void(P0, P1, P2, NullP, NullP, NullP, NullP, NullP, NullP)>(boost::bind(callback, _1, _2, _3)));
}
template<typename P0, typename P1, typename P2, typename P3>
Connection addCallback(void(*callback)(P0, P1, P2, P3))
{
return addCallback(boost::function<void(P0, P1, P2, P3, NullP, NullP, NullP, NullP, NullP)>(boost::bind(callback, _1, _2, _3, _4)));
}
template<typename P0, typename P1, typename P2, typename P3, typename P4>
Connection addCallback(void(*callback)(P0, P1, P2, P3, P4))
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, NullP, NullP, NullP, NullP)>(boost::bind(callback, _1, _2, _3, _4, _5)));
}
template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5>
Connection addCallback(void(*callback)(P0, P1, P2, P3, P4, P5))
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, NullP, NullP, NullP)>(boost::bind(callback, _1, _2, _3, _4, _5, _6)));
}
template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6>
Connection addCallback(void(*callback)(P0, P1, P2, P3, P4, P5, P6))
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, P6, NullP, NullP)>(boost::bind(callback, _1, _2, _3, _4, _5, _6, _7)));
}
template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7>
Connection addCallback(void(*callback)(P0, P1, P2, P3, P4, P5, P6, P7))
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, P6, P7, NullP)>(boost::bind(callback, _1, _2, _3, _4, _5, _6, _7, _8)));
}
template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8>
Connection addCallback(void(*callback)(P0, P1, P2, P3, P4, P5, P6, P7, P8))
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, P6, P7, P8)>(boost::bind(callback, _1, _2, _3, _4, _5, _6, _7, _8, _9)));
}
template<typename T, typename P0, typename P1>
Connection addCallback(void(T::*callback)(P0, P1), T* t)
{
return addCallback(boost::function<void(P0, P1, NullP, NullP, NullP, NullP, NullP, NullP, NullP)>(boost::bind(callback, t, _1, _2)));
}
template<typename T, typename P0, typename P1, typename P2>
Connection addCallback(void(T::*callback)(P0, P1, P2), T* t)
{
return addCallback(boost::function<void(P0, P1, P2, NullP, NullP, NullP, NullP, NullP, NullP)>(boost::bind(callback, t, _1, _2, _3)));
}
template<typename T, typename P0, typename P1, typename P2, typename P3>
Connection addCallback(void(T::*callback)(P0, P1, P2, P3), T* t)
{
return addCallback(boost::function<void(P0, P1, P2, P3, NullP, NullP, NullP, NullP, NullP)>(boost::bind(callback, t, _1, _2, _3, _4)));
}
template<typename T, typename P0, typename P1, typename P2, typename P3, typename P4>
Connection addCallback(void(T::*callback)(P0, P1, P2, P3, P4), T* t)
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, NullP, NullP, NullP, NullP)>(boost::bind(callback, t, _1, _2, _3, _4, _5)));
}
template<typename T, typename P0, typename P1, typename P2, typename P3, typename P4, typename P5>
Connection addCallback(void(T::*callback)(P0, P1, P2, P3, P4, P5), T* t)
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, NullP, NullP, NullP)>(boost::bind(callback, t, _1, _2, _3, _4, _5, _6)));
}
template<typename T, typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6>
Connection addCallback(void(T::*callback)(P0, P1, P2, P3, P4, P5, P6), T* t)
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, P6, NullP, NullP)>(boost::bind(callback, t, _1, _2, _3, _4, _5, _6, _7)));
}
template<typename T, typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7>
Connection addCallback(void(T::*callback)(P0, P1, P2, P3, P4, P5, P6, P7), T* t)
{
return addCallback(boost::function<void(P0, P1, P2, P3, P4, P5, P6, P7, NullP)>(boost::bind(callback, t, _1, _2, _3, _4, _5, _6, _7, _8)));
}
template<typename C>
Connection addCallback( C& callback)
{
return addCallback<const M0ConstPtr&,
const M1ConstPtr&,
const M2ConstPtr&,
const M3ConstPtr&,
const M4ConstPtr&,
const M5ConstPtr&,
const M6ConstPtr&,
const M7ConstPtr&,
const M8ConstPtr&>(boost::bind(callback, _1, _2, _3, _4, _5, _6, _7, _8, _9));
}
void removeCallback(const CallbackHelper9Ptr& helper)
{
boost::mutex::scoped_lock lock(mutex_);
typename V_CallbackHelper9::iterator it = std::find(callbacks_.begin(), callbacks_.end(), helper);
if (it != callbacks_.end())
{
callbacks_.erase(it);
}
}
void call(const M0Event& e0, const M1Event& e1, const M2Event& e2, const M3Event& e3, const M4Event& e4,
const M5Event& e5, const M6Event& e6, const M7Event& e7, const M8Event& e8)
{
boost::mutex::scoped_lock lock(mutex_);
bool nonconst_force_copy = callbacks_.size() > 1;
typename V_CallbackHelper9::iterator it = callbacks_.begin();
typename V_CallbackHelper9::iterator end = callbacks_.end();
for (; it != end; ++it)
{
const CallbackHelper9Ptr& helper = *it;
helper->call(nonconst_force_copy, e0, e1, e2, e3, e4, e5, e6, e7, e8);
}
}
private:
boost::mutex mutex_;
V_CallbackHelper9 callbacks_;
};
} // message_filters
#endif // MESSAGE_FILTERS_SIGNAL9_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/sync_policies/exact_time.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SYNC_EXACT_TIME_H
#define MESSAGE_FILTERS_SYNC_EXACT_TIME_H
#include "message_filters/synchronizer.h"
#include "message_filters/connection.h"
#include "message_filters/null_types.h"
#include "message_filters/signal9.h"
#include <boost/tuple/tuple.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/noncopyable.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/vector.hpp>
#include <ros/assert.h>
#include <ros/message_traits.h>
#include <ros/message_event.h>
#include <deque>
#include <vector>
#include <string>
namespace message_filters
{
namespace sync_policies
{
namespace mpl = boost::mpl;
template<typename M0, typename M1, typename M2 = NullType, typename M3 = NullType, typename M4 = NullType,
typename M5 = NullType, typename M6 = NullType, typename M7 = NullType, typename M8 = NullType>
struct ExactTime : public PolicyBase<M0, M1, M2, M3, M4, M5, M6, M7, M8>
{
typedef Synchronizer<ExactTime> Sync;
typedef PolicyBase<M0, M1, M2, M3, M4, M5, M6, M7, M8> Super;
typedef typename Super::Messages Messages;
typedef typename Super::Signal Signal;
typedef typename Super::Events Events;
typedef typename Super::RealTypeCount RealTypeCount;
typedef typename Super::M0Event M0Event;
typedef typename Super::M1Event M1Event;
typedef typename Super::M2Event M2Event;
typedef typename Super::M3Event M3Event;
typedef typename Super::M4Event M4Event;
typedef typename Super::M5Event M5Event;
typedef typename Super::M6Event M6Event;
typedef typename Super::M7Event M7Event;
typedef typename Super::M8Event M8Event;
typedef boost::tuple<M0Event, M1Event, M2Event, M3Event, M4Event, M5Event, M6Event, M7Event, M8Event> Tuple;
ExactTime(uint32_t queue_size)
: parent_(0)
, queue_size_(queue_size)
{
}
ExactTime(const ExactTime& e)
{
*this = e;
}
ExactTime& operator=(const ExactTime& rhs)
{
parent_ = rhs.parent_;
queue_size_ = rhs.queue_size_;
last_signal_time_ = rhs.last_signal_time_;
tuples_ = rhs.tuples_;
return *this;
}
void initParent(Sync* parent)
{
parent_ = parent;
}
template<int i>
void add(const typename mpl::at_c<Events, i>::type& evt)
{
ROS_ASSERT(parent_);
namespace mt = ros::message_traits;
boost::mutex::scoped_lock lock(mutex_);
Tuple& t = tuples_[mt::TimeStamp<typename mpl::at_c<Messages, i>::type>::value(*evt.getMessage())];
boost::get<i>(t) = evt;
checkTuple(t);
}
template<class C>
Connection registerDropCallback(const C& callback)
{
return drop_signal_.template addCallback(callback);
}
template<class C>
Connection registerDropCallback(C& callback)
{
return drop_signal_.template addCallback(callback);
}
template<class C, typename T>
Connection registerDropCallback(const C& callback, T* t)
{
return drop_signal_.template addCallback(callback, t);
}
template<class C, typename T>
Connection registerDropCallback(C& callback, T* t)
{
return drop_signal_.template addCallback(callback, t);
}
private:
// assumes mutex_ is already locked
void checkTuple(Tuple& t)
{
namespace mt = ros::message_traits;
bool full = true;
full = full && (bool)boost::get<0>(t).getMessage();
full = full && (bool)boost::get<1>(t).getMessage();
full = full && (RealTypeCount::value > 2 ? (bool)boost::get<2>(t).getMessage() : true);
full = full && (RealTypeCount::value > 3 ? (bool)boost::get<3>(t).getMessage() : true);
full = full && (RealTypeCount::value > 4 ? (bool)boost::get<4>(t).getMessage() : true);
full = full && (RealTypeCount::value > 5 ? (bool)boost::get<5>(t).getMessage() : true);
full = full && (RealTypeCount::value > 6 ? (bool)boost::get<6>(t).getMessage() : true);
full = full && (RealTypeCount::value > 7 ? (bool)boost::get<7>(t).getMessage() : true);
full = full && (RealTypeCount::value > 8 ? (bool)boost::get<8>(t).getMessage() : true);
if (full)
{
parent_->signal(boost::get<0>(t), boost::get<1>(t), boost::get<2>(t),
boost::get<3>(t), boost::get<4>(t), boost::get<5>(t),
boost::get<6>(t), boost::get<7>(t), boost::get<8>(t));
last_signal_time_ = mt::TimeStamp<M0>::value(*boost::get<0>(t).getMessage());
tuples_.erase(last_signal_time_);
clearOldTuples();
}
if (queue_size_ > 0)
{
while (tuples_.size() > queue_size_)
{
Tuple& t2 = tuples_.begin()->second;
drop_signal_.call(boost::get<0>(t2), boost::get<1>(t2), boost::get<2>(t2),
boost::get<3>(t2), boost::get<4>(t2), boost::get<5>(t2),
boost::get<6>(t2), boost::get<7>(t2), boost::get<8>(t2));
tuples_.erase(tuples_.begin());
}
}
}
// assumes mutex_ is already locked
void clearOldTuples()
{
typename M_TimeToTuple::iterator it = tuples_.begin();
typename M_TimeToTuple::iterator end = tuples_.end();
for (; it != end;)
{
if (it->first <= last_signal_time_)
{
typename M_TimeToTuple::iterator old = it;
++it;
Tuple& t = old->second;
drop_signal_.call(boost::get<0>(t), boost::get<1>(t), boost::get<2>(t),
boost::get<3>(t), boost::get<4>(t), boost::get<5>(t),
boost::get<6>(t), boost::get<7>(t), boost::get<8>(t));
tuples_.erase(old);
}
else
{
// the map is sorted by time, so we can ignore anything after this if this one's time is ok
break;
}
}
}
private:
Sync* parent_;
uint32_t queue_size_;
typedef std::map<ros::Time, Tuple> M_TimeToTuple;
M_TimeToTuple tuples_;
ros::Time last_signal_time_;
Signal drop_signal_;
boost::mutex mutex_;
};
} // namespace sync
} // namespace message_filters
#endif // MESSAGE_FILTERS_SYNC_EXACT_TIME_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/include/message_filters/sync_policies/approximate_time.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef MESSAGE_FILTERS_SYNC_APPROXIMATE_TIME_H
#define MESSAGE_FILTERS_SYNC_APPROXIMATE_TIME_H
#include "message_filters/synchronizer.h"
#include "message_filters/connection.h"
#include "message_filters/null_types.h"
#include "message_filters/signal9.h"
#include <boost/tuple/tuple.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/noncopyable.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/vector.hpp>
#include <ros/assert.h>
#include <ros/message_traits.h>
#include <ros/message_event.h>
#include <deque>
#include <vector>
#include <string>
namespace message_filters
{
namespace sync_policies
{
namespace mpl = boost::mpl;
template<typename M0, typename M1, typename M2 = NullType, typename M3 = NullType, typename M4 = NullType,
typename M5 = NullType, typename M6 = NullType, typename M7 = NullType, typename M8 = NullType>
struct ApproximateTime : public PolicyBase<M0, M1, M2, M3, M4, M5, M6, M7, M8>
{
typedef Synchronizer<ApproximateTime> Sync;
typedef PolicyBase<M0, M1, M2, M3, M4, M5, M6, M7, M8> Super;
typedef typename Super::Messages Messages;
typedef typename Super::Signal Signal;
typedef typename Super::Events Events;
typedef typename Super::RealTypeCount RealTypeCount;
typedef typename Super::M0Event M0Event;
typedef typename Super::M1Event M1Event;
typedef typename Super::M2Event M2Event;
typedef typename Super::M3Event M3Event;
typedef typename Super::M4Event M4Event;
typedef typename Super::M5Event M5Event;
typedef typename Super::M6Event M6Event;
typedef typename Super::M7Event M7Event;
typedef typename Super::M8Event M8Event;
typedef std::deque<M0Event> M0Deque;
typedef std::deque<M1Event> M1Deque;
typedef std::deque<M2Event> M2Deque;
typedef std::deque<M3Event> M3Deque;
typedef std::deque<M4Event> M4Deque;
typedef std::deque<M5Event> M5Deque;
typedef std::deque<M6Event> M6Deque;
typedef std::deque<M7Event> M7Deque;
typedef std::deque<M8Event> M8Deque;
typedef std::vector<M0Event> M0Vector;
typedef std::vector<M1Event> M1Vector;
typedef std::vector<M2Event> M2Vector;
typedef std::vector<M3Event> M3Vector;
typedef std::vector<M4Event> M4Vector;
typedef std::vector<M5Event> M5Vector;
typedef std::vector<M6Event> M6Vector;
typedef std::vector<M7Event> M7Vector;
typedef std::vector<M8Event> M8Vector;
typedef boost::tuple<M0Event, M1Event, M2Event, M3Event, M4Event, M5Event, M6Event, M7Event, M8Event> Tuple;
typedef boost::tuple<M0Deque, M1Deque, M2Deque, M3Deque, M4Deque, M5Deque, M6Deque, M7Deque, M8Deque> DequeTuple;
typedef boost::tuple<M0Vector, M1Vector, M2Vector, M3Vector, M4Vector, M5Vector, M6Vector, M7Vector, M8Vector> VectorTuple;
ApproximateTime(uint32_t queue_size)
: parent_(0)
, queue_size_(queue_size)
, num_non_empty_deques_(0)
, pivot_(NO_PIVOT)
, max_interval_duration_(ros::DURATION_MAX)
, age_penalty_(0.1)
, has_dropped_messages_(9, false)
, inter_message_lower_bounds_(9, ros::Duration(0))
, warned_about_incorrect_bound_(9, false)
{
ROS_ASSERT(queue_size_ > 0); // The synchronizer will tend to drop many messages with a queue size of 1. At least 2 is recommended.
}
ApproximateTime(const ApproximateTime& e)
{
*this = e;
}
ApproximateTime& operator=(const ApproximateTime& rhs)
{
parent_ = rhs.parent_;
queue_size_ = rhs.queue_size_;
num_non_empty_deques_ = rhs.num_non_empty_deques_;
pivot_time_ = rhs.pivot_time_;
pivot_ = rhs.pivot_;
max_interval_duration_ = rhs.max_interval_duration_;
age_penalty_ = rhs.age_penalty_;
candidate_start_ = rhs.candidate_start_;
candidate_end_ = rhs.candidate_end_;
deques_ = rhs.deques_;
past_ = rhs.past_;
has_dropped_messages_ = rhs.has_dropped_messages_;
inter_message_lower_bounds_ = rhs.inter_message_lower_bounds_;
warned_about_incorrect_bound_ = rhs.warned_about_incorrect_bound_;
return *this;
}
void initParent(Sync* parent)
{
parent_ = parent;
}
template<int i>
void checkInterMessageBound()
{
namespace mt = ros::message_traits;
if (warned_about_incorrect_bound_[i])
{
return;
}
std::deque<typename mpl::at_c<Events, i>::type>& deque = boost::get<i>(deques_);
std::vector<typename mpl::at_c<Events, i>::type>& v = boost::get<i>(past_);
ROS_ASSERT(!deque.empty());
const typename mpl::at_c<Messages, i>::type &msg = *(deque.back()).getMessage();
ros::Time msg_time = mt::TimeStamp<typename mpl::at_c<Messages, i>::type>::value(msg);
ros::Time previous_msg_time;
if (deque.size() == (size_t) 1)
{
if (v.empty())
{
// We have already published (or have never received) the previous message, we cannot check the bound
return;
}
const typename mpl::at_c<Messages, i>::type &previous_msg = *(v.back()).getMessage();
previous_msg_time = mt::TimeStamp<typename mpl::at_c<Messages, i>::type>::value(previous_msg);
}
else
{
// There are at least 2 elements in the deque. Check that the gap respects the bound if it was provided.
const typename mpl::at_c<Messages, i>::type &previous_msg = *(deque[deque.size()-2]).getMessage();
previous_msg_time = mt::TimeStamp<typename mpl::at_c<Messages, i>::type>::value(previous_msg);
}
if (msg_time < previous_msg_time)
{
ROS_WARN_STREAM("Messages of type " << i << " arrived out of order (will print only once)");
warned_about_incorrect_bound_[i] = true;
}
else if ((msg_time - previous_msg_time) < inter_message_lower_bounds_[i])
{
ROS_WARN_STREAM("Messages of type " << i << " arrived closer (" << (msg_time - previous_msg_time)
<< ") than the lower bound you provided (" << inter_message_lower_bounds_[i]
<< ") (will print only once)");
warned_about_incorrect_bound_[i] = true;
}
}
template<int i>
void add(const typename mpl::at_c<Events, i>::type& evt)
{
boost::mutex::scoped_lock lock(data_mutex_);
std::deque<typename mpl::at_c<Events, i>::type>& deque = boost::get<i>(deques_);
deque.push_back(evt);
if (deque.size() == (size_t)1) {
// We have just added the first message, so it was empty before
++num_non_empty_deques_;
if (num_non_empty_deques_ == (uint32_t)RealTypeCount::value)
{
// All deques have messages
process();
}
}
else
{
checkInterMessageBound<i>();
}
// Check whether we have more messages than allowed in the queue.
// Note that during the above call to process(), queue i may contain queue_size_+1 messages.
std::vector<typename mpl::at_c<Events, i>::type>& past = boost::get<i>(past_);
if (deque.size() + past.size() > queue_size_)
{
// Cancel ongoing candidate search, if any:
num_non_empty_deques_ = 0; // We will recompute it from scratch
recover<0>();
recover<1>();
recover<2>();
recover<3>();
recover<4>();
recover<5>();
recover<6>();
recover<7>();
recover<8>();
// Drop the oldest message in the offending topic
ROS_ASSERT(!deque.empty());
deque.pop_front();
has_dropped_messages_[i] = true;
if (pivot_ != NO_PIVOT)
{
// The candidate is no longer valid. Destroy it.
candidate_ = Tuple();
pivot_ = NO_PIVOT;
// There might still be enough messages to create a new candidate:
process();
}
}
}
void setAgePenalty(double age_penalty)
{
// For correctness we only need age_penalty > -1.0, but most likely a negative age_penalty is a mistake.
ROS_ASSERT(age_penalty >= 0);
age_penalty_ = age_penalty;
}
void setInterMessageLowerBound(int i, ros::Duration lower_bound) {
// For correctness we only need age_penalty > -1.0, but most likely a negative age_penalty is a mistake.
ROS_ASSERT(lower_bound >= ros::Duration(0,0));
inter_message_lower_bounds_[i] = lower_bound;
}
void setMaxIntervalDuration(ros::Duration max_interval_duration) {
// For correctness we only need age_penalty > -1.0, but most likely a negative age_penalty is a mistake.
ROS_ASSERT(max_interval_duration >= ros::Duration(0,0));
max_interval_duration_ = max_interval_duration;
}
private:
// Assumes that deque number <index> is non empty
template<int i>
void dequeDeleteFront()
{
std::deque<typename mpl::at_c<Events, i>::type>& deque = boost::get<i>(deques_);
ROS_ASSERT(!deque.empty());
deque.pop_front();
if (deque.empty())
{
--num_non_empty_deques_;
}
}
// Assumes that deque number <index> is non empty
void dequeDeleteFront(uint32_t index)
{
switch (index)
{
case 0:
dequeDeleteFront<0>();
break;
case 1:
dequeDeleteFront<1>();
break;
case 2:
dequeDeleteFront<2>();
break;
case 3:
dequeDeleteFront<3>();
break;
case 4:
dequeDeleteFront<4>();
break;
case 5:
dequeDeleteFront<5>();
break;
case 6:
dequeDeleteFront<6>();
break;
case 7:
dequeDeleteFront<7>();
break;
case 8:
dequeDeleteFront<8>();
break;
default:
ROS_BREAK();
}
}
// Assumes that deque number <index> is non empty
template<int i>
void dequeMoveFrontToPast()
{
std::deque<typename mpl::at_c<Events, i>::type>& deque = boost::get<i>(deques_);
std::vector<typename mpl::at_c<Events, i>::type>& vector = boost::get<i>(past_);
ROS_ASSERT(!deque.empty());
vector.push_back(deque.front());
deque.pop_front();
if (deque.empty())
{
--num_non_empty_deques_;
}
}
// Assumes that deque number <index> is non empty
void dequeMoveFrontToPast(uint32_t index)
{
switch (index)
{
case 0:
dequeMoveFrontToPast<0>();
break;
case 1:
dequeMoveFrontToPast<1>();
break;
case 2:
dequeMoveFrontToPast<2>();
break;
case 3:
dequeMoveFrontToPast<3>();
break;
case 4:
dequeMoveFrontToPast<4>();
break;
case 5:
dequeMoveFrontToPast<5>();
break;
case 6:
dequeMoveFrontToPast<6>();
break;
case 7:
dequeMoveFrontToPast<7>();
break;
case 8:
dequeMoveFrontToPast<8>();
break;
default:
ROS_BREAK();
}
}
void makeCandidate()
{
//printf("Creating candidate\n");
// Create candidate tuple
candidate_ = Tuple(); // Discards old one if any
boost::get<0>(candidate_) = boost::get<0>(deques_).front();
boost::get<1>(candidate_) = boost::get<1>(deques_).front();
if (RealTypeCount::value > 2)
{
boost::get<2>(candidate_) = boost::get<2>(deques_).front();
if (RealTypeCount::value > 3)
{
boost::get<3>(candidate_) = boost::get<3>(deques_).front();
if (RealTypeCount::value > 4)
{
boost::get<4>(candidate_) = boost::get<4>(deques_).front();
if (RealTypeCount::value > 5)
{
boost::get<5>(candidate_) = boost::get<5>(deques_).front();
if (RealTypeCount::value > 6)
{
boost::get<6>(candidate_) = boost::get<6>(deques_).front();
if (RealTypeCount::value > 7)
{
boost::get<7>(candidate_) = boost::get<7>(deques_).front();
if (RealTypeCount::value > 8)
{
boost::get<8>(candidate_) = boost::get<8>(deques_).front();
}
}
}
}
}
}
}
// Delete all past messages, since we have found a better candidate
boost::get<0>(past_).clear();
boost::get<1>(past_).clear();
boost::get<2>(past_).clear();
boost::get<3>(past_).clear();
boost::get<4>(past_).clear();
boost::get<5>(past_).clear();
boost::get<6>(past_).clear();
boost::get<7>(past_).clear();
boost::get<8>(past_).clear();
//printf("Candidate created\n");
}
// ASSUMES: num_messages <= past_[i].size()
template<int i>
void recover(size_t num_messages)
{
if (i >= RealTypeCount::value)
{
return;
}
std::vector<typename mpl::at_c<Events, i>::type>& v = boost::get<i>(past_);
std::deque<typename mpl::at_c<Events, i>::type>& q = boost::get<i>(deques_);
ROS_ASSERT(num_messages <= v.size());
while (num_messages > 0)
{
q.push_front(v.back());
v.pop_back();
num_messages--;
}
if (!q.empty())
{
++num_non_empty_deques_;
}
}
template<int i>
void recover()
{
if (i >= RealTypeCount::value)
{
return;
}
std::vector<typename mpl::at_c<Events, i>::type>& v = boost::get<i>(past_);
std::deque<typename mpl::at_c<Events, i>::type>& q = boost::get<i>(deques_);
while (!v.empty())
{
q.push_front(v.back());
v.pop_back();
}
if (!q.empty())
{
++num_non_empty_deques_;
}
}
template<int i>
void recoverAndDelete()
{
if (i >= RealTypeCount::value)
{
return;
}
std::vector<typename mpl::at_c<Events, i>::type>& v = boost::get<i>(past_);
std::deque<typename mpl::at_c<Events, i>::type>& q = boost::get<i>(deques_);
while (!v.empty())
{
q.push_front(v.back());
v.pop_back();
}
ROS_ASSERT(!q.empty());
q.pop_front();
if (!q.empty())
{
++num_non_empty_deques_;
}
}
// Assumes: all deques are non empty, i.e. num_non_empty_deques_ == RealTypeCount::value
void publishCandidate()
{
//printf("Publishing candidate\n");
// Publish
parent_->signal(boost::get<0>(candidate_), boost::get<1>(candidate_), boost::get<2>(candidate_), boost::get<3>(candidate_),
boost::get<4>(candidate_), boost::get<5>(candidate_), boost::get<6>(candidate_), boost::get<7>(candidate_),
boost::get<8>(candidate_));
// Delete this candidate
candidate_ = Tuple();
pivot_ = NO_PIVOT;
// Recover hidden messages, and delete the ones corresponding to the candidate
num_non_empty_deques_ = 0; // We will recompute it from scratch
recoverAndDelete<0>();
recoverAndDelete<1>();
recoverAndDelete<2>();
recoverAndDelete<3>();
recoverAndDelete<4>();
recoverAndDelete<5>();
recoverAndDelete<6>();
recoverAndDelete<7>();
recoverAndDelete<8>();
}
// Assumes: all deques are non empty, i.e. num_non_empty_deques_ == RealTypeCount::value
// Returns: the oldest message on the deques
void getCandidateStart(uint32_t &start_index, ros::Time &start_time)
{
return getCandidateBoundary(start_index, start_time, false);
}
// Assumes: all deques are non empty, i.e. num_non_empty_deques_ == RealTypeCount::value
// Returns: the latest message among the heads of the deques, i.e. the minimum
// time to end an interval started at getCandidateStart_index()
void getCandidateEnd(uint32_t &end_index, ros::Time &end_time)
{
return getCandidateBoundary(end_index, end_time, true);
}
// ASSUMES: all deques are non-empty
// end = true: look for the latest head of deque
// false: look for the earliest head of deque
void getCandidateBoundary(uint32_t &index, ros::Time &time, bool end)
{
namespace mt = ros::message_traits;
M0Event& m0 = boost::get<0>(deques_).front();
time = mt::TimeStamp<M0>::value(*m0.getMessage());
index = 0;
if (RealTypeCount::value > 1)
{
M1Event& m1 = boost::get<1>(deques_).front();
if ((mt::TimeStamp<M1>::value(*m1.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M1>::value(*m1.getMessage());
index = 1;
}
}
if (RealTypeCount::value > 2)
{
M2Event& m2 = boost::get<2>(deques_).front();
if ((mt::TimeStamp<M2>::value(*m2.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M2>::value(*m2.getMessage());
index = 2;
}
}
if (RealTypeCount::value > 3)
{
M3Event& m3 = boost::get<3>(deques_).front();
if ((mt::TimeStamp<M3>::value(*m3.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M3>::value(*m3.getMessage());
index = 3;
}
}
if (RealTypeCount::value > 4)
{
M4Event& m4 = boost::get<4>(deques_).front();
if ((mt::TimeStamp<M4>::value(*m4.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M4>::value(*m4.getMessage());
index = 4;
}
}
if (RealTypeCount::value > 5)
{
M5Event& m5 = boost::get<5>(deques_).front();
if ((mt::TimeStamp<M5>::value(*m5.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M5>::value(*m5.getMessage());
index = 5;
}
}
if (RealTypeCount::value > 6)
{
M6Event& m6 = boost::get<6>(deques_).front();
if ((mt::TimeStamp<M6>::value(*m6.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M6>::value(*m6.getMessage());
index = 6;
}
}
if (RealTypeCount::value > 7)
{
M7Event& m7 = boost::get<7>(deques_).front();
if ((mt::TimeStamp<M7>::value(*m7.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M7>::value(*m7.getMessage());
index = 7;
}
}
if (RealTypeCount::value > 8)
{
M8Event& m8 = boost::get<8>(deques_).front();
if ((mt::TimeStamp<M8>::value(*m8.getMessage()) < time) ^ end)
{
time = mt::TimeStamp<M8>::value(*m8.getMessage());
index = 8;
}
}
}
// ASSUMES: we have a pivot and candidate
template<int i>
ros::Time getVirtualTime()
{
namespace mt = ros::message_traits;
if (i >= RealTypeCount::value)
{
return ros::Time(0,0); // Dummy return value
}
ROS_ASSERT(pivot_ != NO_PIVOT);
std::vector<typename mpl::at_c<Events, i>::type>& v = boost::get<i>(past_);
std::deque<typename mpl::at_c<Events, i>::type>& q = boost::get<i>(deques_);
if (q.empty())
{
ROS_ASSERT(!v.empty()); // Because we have a candidate
ros::Time last_msg_time = mt::TimeStamp<typename mpl::at_c<Messages, i>::type>::value(*(v.back()).getMessage());
ros::Time msg_time_lower_bound = last_msg_time + inter_message_lower_bounds_[i];
if (msg_time_lower_bound > pivot_time_) // Take the max
{
return msg_time_lower_bound;
}
return pivot_time_;
}
ros::Time current_msg_time = mt::TimeStamp<typename mpl::at_c<Messages, i>::type>::value(*(q.front()).getMessage());
return current_msg_time;
}
// ASSUMES: we have a pivot and candidate
void getVirtualCandidateStart(uint32_t &start_index, ros::Time &start_time)
{
return getVirtualCandidateBoundary(start_index, start_time, false);
}
// ASSUMES: we have a pivot and candidate
void getVirtualCandidateEnd(uint32_t &end_index, ros::Time &end_time)
{
return getVirtualCandidateBoundary(end_index, end_time, true);
}
// ASSUMES: we have a pivot and candidate
// end = true: look for the latest head of deque
// false: look for the earliest head of deque
void getVirtualCandidateBoundary(uint32_t &index, ros::Time &time, bool end)
{
namespace mt = ros::message_traits;
std::vector<ros::Time> virtual_times(9);
virtual_times[0] = getVirtualTime<0>();
virtual_times[1] = getVirtualTime<1>();
virtual_times[2] = getVirtualTime<2>();
virtual_times[3] = getVirtualTime<3>();
virtual_times[4] = getVirtualTime<4>();
virtual_times[5] = getVirtualTime<5>();
virtual_times[6] = getVirtualTime<6>();
virtual_times[7] = getVirtualTime<7>();
virtual_times[8] = getVirtualTime<8>();
time = virtual_times[0];
index = 0;
for (int i = 0; i < RealTypeCount::value; i++)
{
if ((virtual_times[i] < time) ^ end)
{
time = virtual_times[i];
index = i;
}
}
}
// assumes data_mutex_ is already locked
void process()
{
// While no deque is empty
while (num_non_empty_deques_ == (uint32_t)RealTypeCount::value)
{
// Find the start and end of the current interval
//printf("Entering while loop in this state [\n");
//show_internal_state();
//printf("]\n");
ros::Time end_time, start_time;
uint32_t end_index, start_index;
getCandidateEnd(end_index, end_time);
getCandidateStart(start_index, start_time);
for (uint32_t i = 0; i < (uint32_t)RealTypeCount::value; i++)
{
if (i != end_index)
{
// No dropped message could have been better to use than the ones we have,
// so it becomes ok to use this topic as pivot in the future
has_dropped_messages_[i] = false;
}
}
if (pivot_ == NO_PIVOT)
{
// We do not have a candidate
// INVARIANT: the past_ vectors are empty
// INVARIANT: (candidate_ has no filled members)
if (end_time - start_time > max_interval_duration_)
{
// This interval is too big to be a valid candidate, move to the next
dequeDeleteFront(start_index);
continue;
}
if (has_dropped_messages_[end_index])
{
// The topic that would become pivot has dropped messages, so it is not a good pivot
dequeDeleteFront(start_index);
continue;
}
// This is a valid candidate, and we don't have any, so take it
makeCandidate();
candidate_start_ = start_time;
candidate_end_ = end_time;
pivot_ = end_index;
pivot_time_ = end_time;
dequeMoveFrontToPast(start_index);
}
else
{
// We already have a candidate
// Is this one better than the current candidate?
// INVARIANT: has_dropped_messages_ is all false
if ((end_time - candidate_end_) * (1 + age_penalty_) >= (start_time - candidate_start_))
{
// This is not a better candidate, move to the next
dequeMoveFrontToPast(start_index);
}
else
{
// This is a better candidate
makeCandidate();
candidate_start_ = start_time;
candidate_end_ = end_time;
dequeMoveFrontToPast(start_index);
// Keep the same pivot (and pivot time)
}
}
// INVARIANT: we have a candidate and pivot
ROS_ASSERT(pivot_ != NO_PIVOT);
//printf("start_index == %d, pivot_ == %d\n", start_index, pivot_);
if (start_index == pivot_) // TODO: replace with start_time == pivot_time_
{
// We have exhausted all possible candidates for this pivot, we now can output the best one
publishCandidate();
}
else if ((end_time - candidate_end_) * (1 + age_penalty_) >= (pivot_time_ - candidate_start_))
{
// We have not exhausted all candidates, but this candidate is already provably optimal
// Indeed, any future candidate must contain the interval [pivot_time_ end_time], which
// is already too big.
// Note: this case is subsumed by the next, but it may save some unnecessary work and
// it makes things (a little) easier to understand
publishCandidate();
}
else if (num_non_empty_deques_ < (uint32_t)RealTypeCount::value)
{
uint32_t num_non_empty_deques_before_virtual_search = num_non_empty_deques_;
// Before giving up, use the rate bounds, if provided, to further try to prove optimality
std::vector<int> num_virtual_moves(9,0);
while (1)
{
ros::Time end_time, start_time;
uint32_t end_index, start_index;
getVirtualCandidateEnd(end_index, end_time);
getVirtualCandidateStart(start_index, start_time);
if ((end_time - candidate_end_) * (1 + age_penalty_) >= (pivot_time_ - candidate_start_))
{
// We have proved optimality
// As above, any future candidate must contain the interval [pivot_time_ end_time], which
// is already too big.
publishCandidate(); // This cleans up the virtual moves as a byproduct
break; // From the while(1) loop only
}
if ((end_time - candidate_end_) * (1 + age_penalty_) < (start_time - candidate_start_))
{
// We cannot prove optimality
// Indeed, we have a virtual (i.e. optimistic) candidate that is better than the current
// candidate
// Cleanup the virtual search:
num_non_empty_deques_ = 0; // We will recompute it from scratch
recover<0>(num_virtual_moves[0]);
recover<1>(num_virtual_moves[1]);
recover<2>(num_virtual_moves[2]);
recover<3>(num_virtual_moves[3]);
recover<4>(num_virtual_moves[4]);
recover<5>(num_virtual_moves[5]);
recover<6>(num_virtual_moves[6]);
recover<7>(num_virtual_moves[7]);
recover<8>(num_virtual_moves[8]);
(void)num_non_empty_deques_before_virtual_search; // unused variable warning stopper
ROS_ASSERT(num_non_empty_deques_before_virtual_search == num_non_empty_deques_);
break;
}
// Note: we cannot reach this point with start_index == pivot_ since in that case we would
// have start_time == pivot_time, in which case the two tests above are the negation
// of each other, so that one must be true. Therefore the while loop always terminates.
ROS_ASSERT(start_index != pivot_);
ROS_ASSERT(start_time < pivot_time_);
dequeMoveFrontToPast(start_index);
num_virtual_moves[start_index]++;
} // while(1)
}
} // while(num_non_empty_deques_ == (uint32_t)RealTypeCount::value)
}
Sync* parent_;
uint32_t queue_size_;
static const uint32_t NO_PIVOT = 9; // Special value for the pivot indicating that no pivot has been selected
DequeTuple deques_;
uint32_t num_non_empty_deques_;
VectorTuple past_;
Tuple candidate_; // NULL if there is no candidate, in which case there is no pivot.
ros::Time candidate_start_;
ros::Time candidate_end_;
ros::Time pivot_time_;
uint32_t pivot_; // Equal to NO_PIVOT if there is no candidate
boost::mutex data_mutex_; // Protects all of the above
ros::Duration max_interval_duration_; // TODO: initialize with a parameter
double age_penalty_;
std::vector<bool> has_dropped_messages_;
std::vector<ros::Duration> inter_message_lower_bounds_;
std::vector<bool> warned_about_incorrect_bound_;
};
} // namespace sync
} // namespace message_filters
#endif // MESSAGE_FILTERS_SYNC_APPROXIMATE_TIME_H
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/src/connection.cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include "message_filters/connection.h"
namespace message_filters
{
Connection::Connection(const VoidDisconnectFunction& func)
: void_disconnect_(func)
{
}
Connection::Connection(const WithConnectionDisconnectFunction& func, boost::signals2::connection c)
: connection_disconnect_(func)
, connection_(c)
{
}
void Connection::disconnect()
{
if (void_disconnect_)
{
void_disconnect_();
}
else if (connection_disconnect_)
{
connection_disconnect_(*this);
}
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/src | apollo_public_repos/apollo-platform/ros/ros_comm/message_filters/src/message_filters/__init__.py | # Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Message Filter Objects
======================
"""
import itertools
import threading
import rospy
class SimpleFilter(object):
def __init__(self):
self.callbacks = {}
def registerCallback(self, cb, *args):
"""
Register a callback function `cb` to be called when this filter
has output.
The filter calls the function ``cb`` with a filter-dependent list of arguments,
followed by the call-supplied arguments ``args``.
"""
conn = len(self.callbacks)
self.callbacks[conn] = (cb, args)
return conn
def signalMessage(self, *msg):
for (cb, args) in self.callbacks.values():
cb(*(msg + args))
class Subscriber(SimpleFilter):
"""
ROS subscription filter. Identical arguments as :class:`rospy.Subscriber`.
This class acts as a highest-level filter, simply passing messages
from a ROS subscription through to the filters which have connected
to it.
"""
def __init__(self, *args, **kwargs):
SimpleFilter.__init__(self)
self.topic = args[0]
kwargs['callback'] = self.callback
self.sub = rospy.Subscriber(*args, **kwargs)
def callback(self, msg):
self.signalMessage(msg)
def getTopic(self):
return self.topic
def __getattr__(self, key):
"""Serve same API as rospy.Subscriber"""
return self.sub.__getattribute__(key)
class Cache(SimpleFilter):
"""
Stores a time history of messages.
Given a stream of messages, the most recent ``cache_size`` messages
are cached in a ring buffer, from which time intervals of the cache
can then be retrieved by the client.
"""
def __init__(self, f, cache_size = 1):
SimpleFilter.__init__(self)
self.connectInput(f)
self.cache_size = cache_size
# Array to store messages
self.cache_msgs = []
# Array to store msgs times, auxiliary structure to facilitate
# sorted insertion
self.cache_times = []
def connectInput(self, f):
self.incoming_connection = f.registerCallback(self.add)
def add(self, msg):
# Cannot use message filters with non-stamped messages
if not hasattr(msg, 'header') or not hasattr(msg.header, 'stamp'):
rospy.logwarn("Cannot use message filters with non-stamped messages")
return
# Insert sorted
stamp = msg.header.stamp
self.cache_times.append(stamp)
self.cache_msgs.append(msg)
# Implement a ring buffer, discard older if oversized
if (len(self.cache_msgs) > self.cache_size):
del self.cache_msgs[0]
del self.cache_times[0]
# Signal new input
self.signalMessage(msg)
def getInterval(self, from_stamp, to_stamp):
"""Query the current cache content between from_stamp to to_stamp."""
assert from_stamp <= to_stamp
return [m for m in self.cache_msgs
if m.header.stamp >= from_stamp and m.header.stamp <= to_stamp]
def getElemAfterTime(self, stamp):
"""Return the oldest element after or equal the passed time stamp."""
newer = [m for m in self.cache_msgs if m.header.stamp >= stamp]
if not newer:
return None
return newer[0]
def getElemBeforeTime(self, stamp):
"""Return the newest element before or equal the passed time stamp."""
older = [m for m in self.cache_msgs if m.header.stamp <= stamp]
if not older:
return None
return older[-1]
def getLastestTime(self):
"""Return the newest recorded timestamp."""
if not self.cache_times:
return None
return self.cache_times[-1]
def getOldestTime(self):
"""Return the oldest recorded timestamp."""
if not self.cache_times:
return None
return self.cache_times[0]
class TimeSynchronizer(SimpleFilter):
"""
Synchronizes messages by their timestamps.
:class:`TimeSynchronizer` synchronizes incoming message filters by the
timestamps contained in their messages' headers. TimeSynchronizer
listens on multiple input message filters ``fs``, and invokes the callback
when it has a collection of messages with matching timestamps.
The signature of the callback function is::
def callback(msg1, ... msgN):
where N is the number of input message filters, and each message is
the output of the corresponding filter in ``fs``.
The required ``queue size`` parameter specifies how many sets of
messages it should store from each input filter (by timestamp)
while waiting for messages to arrive and complete their "set".
"""
def __init__(self, fs, queue_size):
SimpleFilter.__init__(self)
self.connectInput(fs)
self.queue_size = queue_size
self.lock = threading.Lock()
def connectInput(self, fs):
self.queues = [{} for f in fs]
self.input_connections = [f.registerCallback(self.add, q) for (f, q) in zip(fs, self.queues)]
def add(self, msg, my_queue):
self.lock.acquire()
my_queue[msg.header.stamp] = msg
while len(my_queue) > self.queue_size:
del my_queue[min(my_queue)]
# common is the set of timestamps that occur in all queues
common = reduce(set.intersection, [set(q) for q in self.queues])
for t in sorted(common):
# msgs is list of msgs (one from each queue) with stamp t
msgs = [q[t] for q in self.queues]
self.signalMessage(*msgs)
for q in self.queues:
del q[t]
self.lock.release()
class ApproximateTimeSynchronizer(TimeSynchronizer):
"""
Approximately synchronizes messages by their timestamps.
:class:`ApproximateTimeSynchronizer` synchronizes incoming message filters by the
timestamps contained in their messages' headers. The API is the same as TimeSynchronizer
except for an extra `slop` parameter in the constructor that defines the delay (in seconds)
with which messages can be synchronized
"""
def __init__(self, fs, queue_size, slop):
TimeSynchronizer.__init__(self, fs, queue_size)
self.slop = rospy.Duration.from_sec(slop)
def add(self, msg, my_queue):
self.lock.acquire()
my_queue[msg.header.stamp] = msg
while len(my_queue) > self.queue_size:
del my_queue[min(my_queue)]
for vv in itertools.product(*[list(q.keys()) for q in self.queues]):
qt = list(zip(self.queues, vv))
if ( ((max(vv) - min(vv)) < self.slop) and
(len([1 for q,t in qt if t not in q]) == 0) ):
msgs = [q[t] for q,t in qt]
self.signalMessage(*msgs)
for q,t in qt:
del q[t]
self.lock.release()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rosnode)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
if(CATKIN_ENABLE_TESTING)
find_package(rostest)
add_rostest(test/rosnode.test)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/package.xml | <package>
<name>rosnode</name>
<version>1.11.21</version>
<description>
rosnode is a command-line tool for displaying debug information
about ROS <a href="http://www.ros.org/wiki/Nodes">Nodes</a>,
including publications, subscriptions and connections. It also
contains an experimental library for retrieving node
information. This library is intended for internal use only.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/rosnode</url>
<author>Ken Conley</author>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>rostest</build_depend>
<run_depend>rosgraph</run_depend>
<run_depend>rostopic</run_depend>
<export>
<rosdoc config="rosdoc.yaml"/>
<architecture_independent/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/rosdoc.yaml | - builder: epydoc
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/setup.py | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['rosnode'],
package_dir={'': 'src'},
scripts=['scripts/rosnode'],
requires=['genmsg', 'genpy', 'roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosnode/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rosnode-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package rosnode
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.21 (2017-03-06)
--------------------
1.11.20 (2016-06-27)
--------------------
1.11.19 (2016-04-18)
--------------------
1.11.18 (2016-03-17)
--------------------
1.11.17 (2016-03-11)
--------------------
1.11.16 (2015-11-09)
--------------------
1.11.15 (2015-10-13)
--------------------
1.11.14 (2015-09-19)
--------------------
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
1.11.10 (2014-12-22)
--------------------
1.11.9 (2014-08-18)
-------------------
1.11.8 (2014-08-04)
-------------------
1.11.7 (2014-07-18)
-------------------
1.11.6 (2014-07-10)
-------------------
1.11.5 (2014-06-24)
-------------------
1.11.4 (2014-06-16)
-------------------
* Python 3 compatibility (`#426 <https://github.com/ros/ros_comm/issues/426>`_, `#427 <https://github.com/ros/ros_comm/issues/427>`_)
1.11.3 (2014-05-21)
-------------------
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* add architecture_independent flag in package.xml (`#391 <https://github.com/ros/ros_comm/issues/391>`_)
1.11.0 (2014-03-04)
-------------------
* make rostest in CMakeLists optional (`ros/rosdistro#3010 <https://github.com/ros/rosdistro/issues/3010>`_)
1.10.0 (2014-02-11)
-------------------
1.9.54 (2014-01-27)
-------------------
1.9.53 (2014-01-14)
-------------------
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
1.9.50 (2013-10-04)
-------------------
1.9.49 (2013-09-16)
-------------------
1.9.48 (2013-08-21)
-------------------
1.9.47 (2013-07-03)
-------------------
* check for CATKIN_ENABLE_TESTING to enable configure without tests
1.9.46 (2013-06-18)
-------------------
* fix rosnode_ping to check if new node uri is valid before using it (`#235 <https://github.com/ros/ros_comm/issues/235>`_)
1.9.45 (2013-06-06)
-------------------
* modify rosnode_ping to check for changed node uri if connection is refused (`#221 <https://github.com/ros/ros_comm/issues/221>`_)
1.9.44 (2013-03-21)
-------------------
1.9.43 (2013-03-13)
-------------------
1.9.42 (2013-03-08)
-------------------
1.9.41 (2013-01-24)
-------------------
1.9.40 (2013-01-13)
-------------------
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosnode | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/test/test_rosnode_command_offline.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import unittest
import time
from subprocess import Popen, PIPE, check_call, call
class TestRosnodeOffline(unittest.TestCase):
def setUp(self):
pass
## test that the rosmsg command works
def test_cmd_help(self):
cmd = 'rosnode'
sub = ['ping', 'machine', 'list', 'info', 'kill']
output = Popen([cmd], stdout=PIPE).communicate()[0]
self.assert_('Commands' in output)
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
self.assert_('Commands' in output)
for c in sub:
# make sure command is in usage statement
self.assert_("%s %s"%(cmd, c) in output)
for c in sub:
output = Popen([cmd, c, '-h'], stdout=PIPE, stderr=PIPE).communicate()
self.assert_("Usage:" in output[0], "[%s]: %s"%(c, output))
self.assert_("%s %s"%(cmd, c) in output[0], "%s: %s"%(c, output[0]))
# test no args on commands that require args
for c in ['ping', 'info']:
output = Popen([cmd, c], stdout=PIPE, stderr=PIPE).communicate()
self.assert_("Usage:" in output[0] or "Usage:" in output[1], "[%s]: %s"%(c, output))
def test_offline(self):
cmd = 'rosnode'
# point at a different 'master'
env = os.environ.copy()
env['ROS_MASTER_URI'] = 'http://localhost:11312'
kwds = { 'env': env, 'stdout': PIPE, 'stderr': PIPE}
msg = "ERROR: Unable to communicate with master!\n"
output = Popen([cmd, 'list',], **kwds).communicate()
self.assert_(msg in output[1])
output = Popen([cmd, 'ping', 'talker'], **kwds).communicate()
self.assertEquals(msg, output[1])
output = Popen([cmd, 'info', 'talker'], **kwds).communicate()
self.assert_(msg in output[1])
output = Popen([cmd, 'kill', 'talker'], **kwds).communicate()
self.assert_(msg in output[1])
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosnode | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/test/rosnode.test | <launch>
<node name="talker" pkg="rospy" type="talker.py" />
<group ns="foo">
<node name="talker" pkg="rospy" type="talker.py" />
</group>
<group ns="bar">
<node name="talker" pkg="rospy" type="talker.py" />
</group>
<group ns="baz">
<node name="talker1" pkg="rospy" type="talker.py" />
<node name="talker2" pkg="rospy" type="talker.py" />
<node name="talker3" pkg="rospy" type="talker.py" />
</group>
<group ns="listeners">
<node name="listener" pkg="rospy" type="listener.py" />
</group>
<group ns="to_kill">
<node name="kill1" pkg="rospy" type="talker.py" />
<node name="kill2" pkg="rospy" type="talker.py" />
<node name="kill3" pkg="rospy" type="talker.py" />
<node name="kill4" pkg="rospy" type="talker.py" />
</group>
<test test-name="rosnode_command_line_online" pkg="rosnode" type="check_rosnode_command_online.py" />
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosnode | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/test/test_rosnode.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import time
import unittest
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from subprocess import Popen, PIPE, check_call, call
from contextlib import contextmanager
@contextmanager
def fakestdout():
realstdout = sys.stdout
fakestdout = StringIO()
sys.stdout = fakestdout
yield fakestdout
sys.stdout = realstdout
def tolist(b):
return [x.strip() for x in b.getvalue().split('\n') if x.strip()]
class TestRosnode(unittest.TestCase):
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
self.vals = set()
# wait for network to initialize
import rospy
import std_msgs.msg
rospy.init_node('test')
topics = ['/chatter', '/foo/chatter', '/bar/chatter']
subs = [rospy.Subscriber(t, std_msgs.msg.String, self.callback, i) for i, t in enumerate(topics)]
all = set(range(0, len(topics)))
timeout_t = time.time() + 10.
while time.time() < timeout_t and self.vals != all:
time.sleep(0.1)
[s.unregister() for s in subs]
def setUp(self):
self.vals = set()
self.msgs = {}
def callback(self, msg, val):
self.vals.add(val)
def _check(self, expected, actual):
"""
Make sure all elements of expected are present in actual
"""
for t in expected:
self.assert_(t in actual)
def _notcheck(self, not_expected, actual):
"""
Make sure all elements of not_expected are not present in actual
"""
for t in not_expected:
self.failIf(t in actual)
def test_rosnode_info(self):
import rosnode
cmd = 'rosnode'
nodes = ['/talker',
'/foo/talker',
'/bar/talker',
'/baz/talker1',
'/baz/talker2',
'/baz/talker3',
'/listeners/listener',
'/rosout',
]
try:
rosnode._rosnode_cmd_info([cmd, 'info'])
self.fail("should have failed")
except SystemExit as e:
self.assertNotEquals(0, e.code)
for n in nodes:
with fakestdout() as b:
rosnode._rosnode_cmd_info([cmd, 'info', n])
s = b.getvalue()
self.assert_("Node [%s]"%n in s)
self.assert_("Pid: " in s, s)
def test_rosnode_list(self):
import rosnode
cmd = 'rosnode'
nodes = ['/talker',
'/foo/talker',
'/bar/talker',
'/baz/talker1',
'/baz/talker2',
'/baz/talker3',
'/rosout',
]
l = rosnode.get_node_names()
for t in nodes:
self.assert_(t in l)
try:
rosnode._rosnode_cmd_list([cmd, 'list', 'one', 'two'])
self.fail("should have failed")
except SystemExit as e:
self.assertNotEquals(0, e.code)
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list'])
self._check(nodes, tolist(b))
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list', '/'])
l = tolist(b)
self._check(nodes, l)
num_nodes = len(l)
# test -u uris
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list', '-u', '/'])
l = tolist(b)
self.assertEquals(num_nodes, len(l))
self.failIf([n for n in l if not n.startswith('http://')])
# test -a all
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list', '-a', '/'])
l = tolist(b)
uris = [x.split()[0] for x in l if x]
names = [x.split()[1] for x in l if x]
self._check(nodes, names)
self.assertEquals(num_nodes, len(uris))
self.failIf([n for n in uris if not n.startswith('http://')])
# test with namespace
foon = [p for p in nodes if p.startswith('/foo/')]
not_foon = [p for p in nodes if not p.startswith('/foo/')]
for ns in ['foo', '/foo', '/foo/']:
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list', ns])
self._check(foon, tolist(b))
self._notcheck(not_foon, tolist(b))
bazn = [p for p in nodes if p.startswith('/baz/')]
not_bazn = [p for p in nodes if not p.startswith('/baz/')]
for ns in ['baz', '/baz', '/baz/']:
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list', ns])
self._check(bazn, tolist(b))
self._notcheck(not_bazn, tolist(b))
# test with no match
with fakestdout() as b:
rosnode._rosnode_cmd_list([cmd, 'list', '/not/a/namespace/'])
self.assertEquals([], tolist(b))
def test_rosnode_usage(self):
import rosnode
cmd = 'rosnode'
for c in ['ping', 'list', 'info', 'machine', 'cleanup', 'kill']:
try:
with fakestdout() as b:
rosnode.rosnodemain([cmd, c, '-h'])
self.assert_("usage" in b.getvalue())
self.fail("should have exited on usage")
except SystemExit as e:
self.assertEquals(0, e.code)
def test_rosnode_ping(self):
import rosnode
cmd = 'rosnode'
self.failIf(rosnode.rosnode_ping('/fake_node', max_count=1))
self.assert_(rosnode.rosnode_ping('/rosout', max_count=1))
self.assert_(rosnode.rosnode_ping('/rosout', max_count=2))
with fakestdout() as b:
self.assert_(rosnode.rosnode_ping('/rosout', max_count=2, verbose=True))
s = b.getvalue()
self.assert_('xmlrpc reply' in s, s)
self.assert_('ping average:' in s, s)
# test via command-line API
rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '1', '/fake_node'])
with fakestdout() as b:
rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '1', '/rosout'])
s = b.getvalue()
self.assert_('xmlrpc reply' in s, s)
with fakestdout() as b:
rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '1', 'rosout'])
s = b.getvalue()
self.assert_('xmlrpc reply' in s, s)
with fakestdout() as b:
rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '2', 'rosout'])
s = b.getvalue()
self.assertEquals(2, s.count('xmlrpc reply'))
def test_rosnode_ping_all(self):
import rosnode
cmd = 'rosnode'
pinged, unpinged = rosnode.rosnode_ping_all(verbose=False)
self.assert_('/rosout' in pinged)
with fakestdout() as b:
pinged, unpinged = rosnode.rosnode_ping_all(verbose=True)
self.assert_('xmlrpc reply' in b.getvalue())
self.assert_('/rosout' in pinged)
def test_rosnode_kill(self):
import rosnode
cmd = 'rosnode'
for n in ['to_kill/kill1', '/to_kill/kill2']:
self.assert_(rosnode.rosnode_ping(n, max_count=1))
rosnode._rosnode_cmd_kill([cmd, 'kill', n])
self.failIf(rosnode.rosnode_ping(n, max_count=1))
def test_fullusage(self):
import rosnode
try:
rosnode._fullusage()
except SystemExit: pass
try:
rosnode.rosnodemain(['rosnode'])
except SystemExit: pass
try:
rosnode.rosnodemain(['rosnode', 'invalid'])
except SystemExit: pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosnode | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/test/check_rosnode_command_online.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import signal
import sys
import time
import unittest
import rospy
import std_msgs.msg
import rostest
from subprocess import Popen, PIPE, check_call, call
def run_for(cmd, secs):
popen = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True)
timeout_t = time.time() + secs
while time.time() < timeout_t:
time.sleep(0.1)
os.kill(popen.pid, signal.SIGKILL)
class TestRosnodeOnline(unittest.TestCase):
def setUp(self):
self.vals = set()
self.msgs = {}
def callback(self, msg, val):
self.vals.add(val)
self.msgs[val] = msg
def test_rosnode(self):
topics = ['/chatter', '/foo/chatter', '/bar/chatter']
# wait for network to initialize
rospy.init_node('test')
nodes = ['/talker', '/foo/talker', '/bar/talker', rospy.get_caller_id()]
for i, t in enumerate(topics):
rospy.Subscriber(t, std_msgs.msg.String, self.callback, i)
all = set(range(0, len(topics)))
timeout_t = time.time() + 10.
while time.time() < timeout_t and self.vals != all:
time.sleep(0.1)
self.assertEquals(self.vals, all, "failed to initialize graph correctly")
# network is initialized
cmd = 'rosnode'
# list
# - we aren't matching against the core services as those can make the test suites brittle
output = Popen([cmd, 'list'], stdout=PIPE).communicate()[0]
output = output.decode()
l = set(output.split())
for t in nodes:
self.assert_(t in l, "%s not in %s"%(t, l))
output = Popen([cmd, 'list', '-a'], stdout=PIPE).communicate()[0]
output = output.decode()
l = set(output.split())
for t in nodes:
for e in l:
if t in e:
break
else:
self.fail("did not find [%s] in list [%s]"%(t, l))
output = Popen([cmd, 'list', '-u'], stdout=PIPE).communicate()[0]
output = output.decode()
l = set(output.split())
self.assert_(len(l), "list -u is empty")
for e in l:
self.assert_(e.startswith('http://'))
for name in nodes:
# type
output = Popen([cmd, 'info', name], stdout=PIPE).communicate()[0]
output = output.decode()
# not really validating output as much as making sure it's not broken
self.assert_(name in output)
self.assert_('chatter' in output)
self.assert_('Publications' in output)
self.assert_('Subscriptions' in output)
if 0:
#ping
stdout, stderr = run_for([cmd, 'ping', name], 3.)
PKG = 'test_rosnode'
NAME = 'test_rosnode_command_line_online'
if __name__ == '__main__':
rostest.run(PKG, NAME, TestRosnodeOnline, sys.argv)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosnode | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/scripts/rosnode | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import rosnode
rosnode.rosnodemain()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosnode/src/rosnode/__init__.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
rosnode implements the rosnode command-line tool and also provides a
library for retrieving ROS Node information.
"""
from __future__ import print_function
import os
import errno
import sys
import socket
import time
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
try: #py3k
import urllib.parse as urlparse
except ImportError:
import urlparse
from optparse import OptionParser
import rosgraph
import rosgraph.names
import rostopic
NAME='rosnode'
ID = '/rosnode'
class ROSNodeException(Exception):
"""
rosnode base exception type
"""
pass
class ROSNodeIOException(ROSNodeException):
"""
Exceptions for communication-related (i/o) errors, generally due to Master or Node network communication issues.
"""
pass
# need for calling node APIs
def _succeed(args):
code, msg, val = args
if code != 1:
raise ROSNodeException("remote call failed: %s"%msg)
return val
_caller_apis = {}
def get_api_uri(master, caller_id, skip_cache=False):
"""
@param master: XMLRPC handle to ROS Master
@type master: rosgraph.Master
@param caller_id: node name
@type caller_id: str
@param skip_cache: flag to skip cached data and force to lookup node from master
@type skip_cache: bool
@return: xmlrpc URI of caller_id
@rtype: str
@raise ROSNodeIOException: if unable to communicate with master
"""
caller_api = _caller_apis.get(caller_id, None)
if not caller_api or skip_cache:
try:
caller_api = master.lookupNode(caller_id)
_caller_apis[caller_id] = caller_api
except rosgraph.MasterError:
return None
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
return caller_api
def lookup_uri(master, system_state, topic, uri):
for l in system_state[0:2]:
for entry in l:
if entry[0] == topic:
for n in entry[1]:
if rostopic.get_api(master, n) == uri:
return '%s (%s)' % (n, uri)
return uri
def get_node_names(namespace=None):
"""
@param namespace: optional namespace to scope return values by. Namespace must already be resolved.
@type namespace: str
@return: list of node caller IDs
@rtype: [str]
@raise ROSNodeIOException: if unable to communicate with master
"""
master = rosgraph.Master(ID)
try:
state = master.getSystemState()
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
nodes = []
if namespace:
# canonicalize namespace with leading/trailing slash
g_ns = rosgraph.names.make_global_ns(namespace)
for s in state:
for t, l in s:
nodes.extend([n for n in l if n.startswith(g_ns) or n == namespace])
else:
for s in state:
for t, l in s:
nodes.extend(l)
return list(set(nodes))
def get_machines_by_nodes():
"""
Find machines connected to nodes. This is a very costly procedure as it
must do N lookups with the Master, where N is the number of nodes.
@return: list of machines connected
@rtype: [str]
@raise ROSNodeIOException: if unable to communicate with master
"""
master = rosgraph.Master(ID)
# get all the node names, lookup their uris, parse the hostname
# from the uris, and then compare the resolved hostname against
# the requested machine name.
machines = []
node_names = get_node_names()
for n in node_names:
try:
uri = master.lookupNode(n)
h = urlparse.urlparse(uri).hostname
if h not in machines:
machines.append(h)
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
except rosgraph.MasterError:
# it's possible that the state changes as we are doing lookups. this is a soft-fail
continue
return machines
def get_nodes_by_machine(machine):
"""
Find nodes by machine name. This is a very costly procedure as it
must do N lookups with the Master, where N is the number of nodes.
@return: list of nodes on the specified machine
@rtype: [str]
@raise ROSNodeException: if machine name cannot be resolved to an address
@raise ROSNodeIOException: if unable to communicate with master
"""
import urlparse
master = rosgraph.Master(ID)
try:
machine_actual = [host[4][0] for host in socket.getaddrinfo(machine, 0, 0, 0, socket.SOL_TCP)]
except:
raise ROSNodeException("cannot resolve machine name [%s] to address"%machine)
# get all the node names, lookup their uris, parse the hostname
# from the uris, and then compare the resolved hostname against
# the requested machine name.
matches = [machine] + machine_actual
not_matches = [] # cache lookups
node_names = get_node_names()
retval = []
for n in node_names:
try:
try:
uri = master.lookupNode(n)
except rosgraph.MasterError:
# it's possible that the state changes as we are doing lookups. this is a soft-fail
continue
h = urlparse.urlparse(uri).hostname
if h in matches:
retval.append(n)
elif h in not_matches:
continue
else:
r = [host[4][0] for host in socket.getaddrinfo(h, 0, 0, 0, socket.SOL_TCP)]
if set(r) & set(machine_actual):
matches.append(r)
retval.append(n)
else:
not_matches.append(r)
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
return retval
def kill_nodes(node_names):
"""
Call shutdown on the specified nodes
@return: list of nodes that shutdown was called on successfully and list of failures
@rtype: ([str], [str])
"""
master = rosgraph.Master(ID)
success = []
fail = []
tocall = []
try:
# lookup all nodes keeping track of lookup failures for return value
for n in node_names:
try:
uri = master.lookupNode(n)
tocall.append([n, uri])
except:
fail.append(n)
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
for n, uri in tocall:
# the shutdown call can sometimes fail to succeed if the node
# tears down during the request handling, so we assume success
try:
p = ServerProxy(uri)
_succeed(p.shutdown(ID, 'user request'))
except:
pass
success.append(n)
return success, fail
def _sub_rosnode_listnodes(namespace=None, list_uri=False, list_all=False):
"""
Subroutine for rosnode_listnodes(). Composes list of strings to print to screen.
@param namespace: (default None) namespace to scope list to.
@type namespace: str
@param list_uri: (default False) return uris of nodes instead of names.
@type list_uri: bool
@param list_all: (default False) return names and uris of nodes as combined strings
@type list_all: bool
@return: new-line separated string containing list of all nodes
@rtype: str
"""
master = rosgraph.Master(ID)
nodes = get_node_names(namespace)
nodes.sort()
if list_all:
return '\n'.join(["%s \t%s"%(get_api_uri(master, n) or 'unknown address', n) for n in nodes])
elif list_uri:
return '\n'.join([(get_api_uri(master, n) or 'unknown address') for n in nodes])
else:
return '\n'.join(nodes)
def rosnode_listnodes(namespace=None, list_uri=False, list_all=False):
"""
Print list of all ROS nodes to screen.
@param namespace: namespace to scope list to
@type namespace: str
@param list_uri: print uris of nodes instead of names
@type list_uri: bool
@param list_all: print node names and uris
@param list_all: bool
"""
print(_sub_rosnode_listnodes(namespace=namespace, list_uri=list_uri, list_all=list_all))
def rosnode_ping(node_name, max_count=None, verbose=False):
"""
Test connectivity to node by calling its XMLRPC API
@param node_name: name of node to ping
@type node_name: str
@param max_count: number of ping requests to make
@type max_count: int
@param verbose: print ping information to screen
@type verbose: bool
@return: True if node pinged
@rtype: bool
@raise ROSNodeIOException: if unable to communicate with master
"""
master = rosgraph.Master(ID)
node_api = get_api_uri(master,node_name)
if not node_api:
print("cannot ping [%s]: unknown node"%node_name, file=sys.stderr)
return False
timeout = 3.
if verbose:
print("pinging %s with a timeout of %ss"%(node_name, timeout))
socket.setdefaulttimeout(timeout)
node = ServerProxy(node_api)
lastcall = 0.
count = 0
acc = 0.
try:
while True:
try:
start = time.time()
pid = _succeed(node.getPid(ID))
end = time.time()
dur = (end-start)*1000.
acc += dur
count += 1
if verbose:
print("xmlrpc reply from %s\ttime=%fms"%(node_api, dur))
# 1s between pings
except socket.error as e:
# 3786: catch ValueError on unpack as socket.error is not always a tuple
try:
# #3659
errnum, msg = e
if errnum == -2: #name/service unknown
p = urlparse.urlparse(node_api)
print("ERROR: Unknown host [%s] for node [%s]"%(p.hostname, node_name), file=sys.stderr)
elif errnum == errno.ECONNREFUSED:
# check if node url has changed
new_node_api = get_api_uri(master,node_name, skip_cache=True)
if not new_node_api:
print("cannot ping [%s]: unknown node"%node_name, file=sys.stderr)
return False
if new_node_api != node_api:
if verbose:
print("node url has changed from [%s] to [%s], retrying to ping"%(node_api, new_node_api))
node_api = new_node_api
node = ServerProxy(node_api)
continue
print("ERROR: connection refused to [%s]"%(node_api), file=sys.stderr)
else:
print("connection to [%s] timed out"%node_name, file=sys.stderr)
return False
except ValueError:
print("unknown network error contacting node: %s"%(str(e)))
if max_count and count >= max_count:
break
time.sleep(1.0)
except KeyboardInterrupt:
pass
if verbose and count > 1:
print("ping average: %fms"%(acc/count))
return True
def rosnode_ping_all(verbose=False):
"""
Ping all running nodes
@return [str], [str]: pinged nodes, un-pingable nodes
@raise ROSNodeIOException: if unable to communicate with master
"""
master = rosgraph.Master(ID)
try:
state = master.getSystemState()
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
nodes = []
for s in state:
for t, l in s:
nodes.extend(l)
nodes = list(set(nodes)) #uniq
if verbose:
print("Will ping the following nodes: \n"+''.join([" * %s\n"%n for n in nodes]))
pinged = []
unpinged = []
for node in nodes:
if rosnode_ping(node, max_count=1, verbose=verbose):
pinged.append(node)
else:
unpinged.append(node)
return pinged, unpinged
def cleanup_master_blacklist(master, blacklist):
"""
Remove registrations from ROS Master that do not match blacklist.
@param master: XMLRPC handle to ROS Master
@type master: xmlrpclib.ServerProxy
@param blacklist: list of nodes to scrub
@type blacklist: [str]
"""
pubs, subs, srvs = master.getSystemState()
for n in blacklist:
print("Unregistering", n)
node_api = get_api_uri(master, n)
for t, l in pubs:
if n in l:
master_n = rosgraph.Master(n)
master_n.unregisterPublisher(t, node_api)
for t, l in subs:
if n in l:
master_n = rosgraph.Master(n)
master_n.unregisterSubscriber(t, node_api)
for s, l in srvs:
if n in l:
service_api = master.lookupServiceCache(s)
master_n = rosgraph.Master(n)
master_n.unregisterService(s, service_api)
def cleanup_master_whitelist(master, whitelist):
"""
Remove registrations from ROS Master that do not match whitelist.
@param master: XMLRPC handle to ROS Master
@type master: xmlrpclib.ServerProxy
@param whitelist: list of nodes to keep
@type whitelist: list of nodes to keep
"""
pubs, subs, srvs = master.getSystemState()
for t, l in pubs:
for n in l:
if n not in whitelist:
node_api = get_api_uri(master, n)
master_n = rosgraph.Master(n)
master_n.unregisterPublisher(t, node_api)
for t, l in subs:
for n in l:
if n not in whitelist:
node_api = get_api_uri(master, n)
master_n = rosgraph.Master(n)
master_n.unregisterSubscriber(t, node_api)
for s, l in srvs:
for n in l:
if n not in whitelist:
service_api = master.lookupServiceCache(s)
master_n = rosgraph.Master(n)
master_n.unregisterService(s, service_api)
def rosnode_cleanup():
"""
This is a semi-hidden routine for cleaning up stale node
registration information on the ROS Master. The intent is to
remove this method once Master TTLs are properly implemented.
"""
pinged, unpinged = rosnode_ping_all()
if unpinged:
master = rosgraph.Master(ID)
print("Unable to contact the following nodes:")
print('\n'.join(' * %s'%n for n in unpinged))
print("Warning: these might include alive and functioning nodes, e.g. in unstable networks.")
print("Cleanup will purge all information about these nodes from the master.")
print("Please type y or n to continue:")
input = sys.stdin.readline()
while not input.strip() in ['y', 'n']:
input = sys.stdin.readline()
if input.strip() == 'n':
print('aborting')
return
cleanup_master_blacklist(master, unpinged)
def get_node_info_description(node_name):
def topic_type(t, pub_topics):
matches = [t_type for t_name, t_type in pub_topics if t_name == t]
if matches:
return matches[0]
return 'unknown type'
master = rosgraph.Master(ID)
# go through the master system state first
try:
state = master.getSystemState()
pub_topics = master.getPublishedTopics('/')
except socket.error:
raise ROSNodeIOException("Unable to communicate with master!")
pubs = [t for t, l in state[0] if node_name in l]
subs = [t for t, l in state[1] if node_name in l]
srvs = [t for t, l in state[2] if node_name in l]
buff = "Node [%s]"%node_name
if pubs:
buff += "\nPublications: \n"
buff += '\n'.join([" * %s [%s]"%(l, topic_type(l, pub_topics)) for l in pubs]) + '\n'
else:
buff += "\nPublications: None\n"
if subs:
buff += "\nSubscriptions: \n"
buff += '\n'.join([" * %s [%s]"%(l, topic_type(l, pub_topics)) for l in subs]) + '\n'
else:
buff += "\nSubscriptions: None\n"
if srvs:
buff += "\nServices: \n"
buff += '\n'.join([" * %s"%l for l in srvs]) + '\n'
else:
buff += "\nServices: None\n"
return buff
def get_node_connection_info_description(node_api, master):
#turn down timeout on socket library
socket.setdefaulttimeout(5.0)
node = ServerProxy(node_api)
system_state = master.getSystemState()
try:
pid = _succeed(node.getPid(ID))
buff = "Pid: %s\n"%pid
#master_uri = _succeed(node.getMasterUri(ID))
businfo = _succeed(node.getBusInfo(ID))
if businfo:
buff += "Connections:\n"
for info in businfo:
dest_id = info[1]
direction = info[2]
transport = info[3]
topic = info[4]
if len(info) > 5:
connected = info[5]
else:
connected = True #backwards compatibility
if connected:
buff += " * topic: %s\n"%topic
# older ros publisher implementations don't report a URI
buff += " * to: %s\n"%lookup_uri(master, system_state, topic, dest_id)
if direction == 'i':
buff += " * direction: inbound\n"
elif direction == 'o':
buff += " * direction: outbound\n"
else:
buff += " * direction: unknown\n"
buff += " * transport: %s\n"%transport
except socket.error:
raise ROSNodeIOException("Communication with node[%s] failed!"%(node_api))
return buff
def rosnode_info(node_name):
"""
Print information about node, including subscriptions and other debugging information. This will query the node over the network.
@param node_name: name of ROS node
@type node_name: str
@raise ROSNodeIOException: if unable to communicate with master
"""
def topic_type(t, pub_topics):
matches = [t_type for t_name, t_type in pub_topics if t_name == t]
if matches:
return matches[0]
return 'unknown type'
master = rosgraph.Master(ID)
node_name = rosgraph.names.script_resolve_name('rosnode', node_name)
print(get_node_info_description(node_name))
node_api = get_api_uri(master, node_name)
if not node_api:
print("cannot contact [%s]: unknown node"%node_name, file=sys.stderr)
return
print("\ncontacting node %s ..."%node_api)
print(get_node_connection_info_description(node_api, master))
# backwards compatibility (deprecated)
rosnode_debugnode = rosnode_info
def _rosnode_cmd_list(argv):
"""
Implements rosnode 'list' command.
"""
args = argv[2:]
parser = OptionParser(usage="usage: %prog list", prog=NAME)
parser.add_option("-u",
dest="list_uri", default=False,
action="store_true",
help="list XML-RPC URIs")
parser.add_option("-a","--all",
dest="list_all", default=False,
action="store_true",
help="list all information")
(options, args) = parser.parse_args(args)
namespace = None
if len(args) > 1:
parser.error("invalid args: you may only specify one namespace")
elif len(args) == 1:
namespace = rosgraph.names.script_resolve_name('rostopic', args[0])
rosnode_listnodes(namespace=namespace, list_uri=options.list_uri, list_all=options.list_all)
def _rosnode_cmd_info(argv):
"""
Implements rosnode 'info' command.
"""
args = argv[2:]
parser = OptionParser(usage="usage: %prog info node1 [node2...]", prog=NAME)
(options, args) = parser.parse_args(args)
if not args:
parser.error("You must specify at least one node name")
for node in args:
rosnode_info(node)
def _rosnode_cmd_machine(argv):
"""
Implements rosnode 'machine' command.
@raise ROSNodeException: if user enters in unrecognized machine name
"""
args = argv[2:]
parser = OptionParser(usage="usage: %prog machine [machine-name]", prog=NAME)
(options, args) = parser.parse_args(args)
if len(args) > 1:
parser.error("please enter only one machine name")
elif len(args) == 0:
machines = get_machines_by_nodes()
machines.sort()
print('\n'.join(machines))
else:
nodes = get_nodes_by_machine(args[0])
nodes.sort()
print('\n'.join(nodes))
def _rosnode_cmd_kill(argv):
"""
Implements rosnode 'kill' command.
@raise ROSNodeException: if user enters in unrecognized nodes
"""
args = argv[2:]
parser = OptionParser(usage="usage: %prog kill [node]...", prog=NAME)
parser.add_option("-a","--all",
dest="kill_all", default=False,
action="store_true",
help="kill all nodes")
(options, args) = parser.parse_args(args)
if options.kill_all:
if args:
parser.error("invalid arguments with kill all (-a) option")
args = get_node_names()
args.sort()
elif not args:
node_list = get_node_names()
node_list.sort()
if not node_list:
print("No nodes running", file=sys.stderr)
return 0
sys.stdout.write('\n'.join(["%s. %s"%(i+1, n) for i,n in enumerate(node_list)]))
sys.stdout.write("\n\nPlease enter the number of the node you wish to kill.\n> ")
selection = ''
while not selection:
selection = sys.stdin.readline().strip()
try:
selection = int(selection)
if selection <= 0:
print("ERROR: invalid selection. Please enter a number (ctrl-C to cancel)")
except:
print("ERROR: please enter a number (ctrl-C to cancel)")
sys.stdout.flush()
selection = ''
args = [node_list[selection - 1]]
else:
# validate args
args = [rosgraph.names.script_resolve_name(ID, n) for n in args]
node_list = get_node_names()
unknown = [n for n in args if not n in node_list]
if unknown:
raise ROSNodeException("Unknown node(s):\n"+'\n'.join([" * %s"%n for n in unknown]))
if len(args) > 1:
print("killing:\n"+'\n'.join([" * %s"%n for n in args]))
else:
print("killing %s"%(args[0]))
success, fail = kill_nodes(args)
if fail:
print("ERROR: Failed to kill:\n"+'\n'.join([" * %s"%n for n in fail]), file=sys.stderr)
return 1
print("killed")
return 0
def _rosnode_cmd_cleanup(argv):
"""
Implements rosnode 'cleanup' command.
@param argv: command-line args
@type argv: [str]
"""
args = argv[2:]
parser = OptionParser(usage="usage: %prog cleanup", prog=NAME)
(options, args) = parser.parse_args(args)
rosnode_cleanup()
def _rosnode_cmd_ping(argv):
"""
Implements rosnode 'ping' command.
@param argv: command-line args
@type argv: [str]
"""
args = argv[2:]
parser = OptionParser(usage="usage: %prog ping [options] <node>", prog=NAME)
parser.add_option("--all", "-a",
dest="ping_all", default=False,
action="store_true",
help="ping all nodes")
parser.add_option("-c",
dest="ping_count", default=None, metavar="COUNT",type="int",
help="number of pings to send. Not available with --all")
(options, args) = parser.parse_args(args)
node_name = None
if not options.ping_all:
if not args:
try:
parser.error("Please enter a node to ping. Available nodes are:\n"+_sub_rosnode_listnodes())
except:
# master is offline, but user did have invalid usage, so display correct usage first
parser.error("Please enter a node to ping")
elif len(args) > 1:
parser.error("you may only specify one input node")
elif len(args) == 1:
node_name = rosgraph.names.script_resolve_name('rosnode', args[0])
print("rosnode: node is [%s]"%node_name)
else:
if args:
parser.error("Invalid arguments '%s' used with --all"%(' '.join(args)))
elif options.ping_count:
parser.error("-c may not be used with --all")
if options.ping_all:
rosnode_ping_all(verbose=True)
else:
rosnode_ping(node_name, verbose=True, max_count=options.ping_count)
def _fullusage(return_error=True):
"""
Prints rosnode usage information.
@param return_error whether to exit with error code os.EX_USAGE
"""
print("""rosnode is a command-line tool for printing information about ROS Nodes.
Commands:
\trosnode ping\ttest connectivity to node
\trosnode list\tlist active nodes
\trosnode info\tprint information about node
\trosnode machine\tlist nodes running on a particular machine or list machines
\trosnode kill\tkill a running node
\trosnode cleanup\tpurge registration information of unreachable nodes
Type rosnode <command> -h for more detailed usage, e.g. 'rosnode ping -h'
""")
if return_error:
sys.exit(getattr(os, 'EX_USAGE', 1))
else:
sys.exit(0)
def rosnodemain(argv=None):
"""
Prints rosnode main entrypoint.
@param argv: override sys.argv
@param argv: [str]
"""
if argv == None:
argv = sys.argv
if len(argv) == 1:
_fullusage()
try:
command = argv[1]
if command == 'ping':
sys.exit(_rosnode_cmd_ping(argv) or 0)
elif command == 'list':
sys.exit(_rosnode_cmd_list(argv) or 0)
elif command == 'info':
sys.exit(_rosnode_cmd_info(argv) or 0)
elif command == 'machine':
sys.exit(_rosnode_cmd_machine(argv) or 0)
elif command == 'cleanup':
sys.exit(_rosnode_cmd_cleanup(argv) or 0)
elif command == 'kill':
sys.exit(_rosnode_cmd_kill(argv) or 0)
elif command == '--help':
_fullusage(False)
else:
_fullusage()
except socket.error:
print("Network communication failed. Most likely failed to communicate with master.", file=sys.stderr)
except rosgraph.MasterError as e:
print("ERROR: "+str(e), file=sys.stderr)
except ROSNodeException as e:
print("ERROR: "+str(e), file=sys.stderr)
except KeyboardInterrupt:
pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(roswtf)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
if(CATKIN_ENABLE_TESTING)
find_package(rostest)
add_rostest(test/roswtf.test)
catkin_add_nosetests(test)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/package.xml | <package>
<name>roswtf</name>
<version>1.11.21</version>
<description>
roswtf is a tool for diagnosing issues with a running ROS system. Think of it as a FAQ implemented in code.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/roswtf</url>
<author>Ken Conley</author>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>rostest</build_depend>
<run_depend>python-paramiko</run_depend>
<run_depend>python-rospkg</run_depend>
<run_depend>rosbuild</run_depend>
<run_depend>rosgraph</run_depend>
<run_depend>roslaunch</run_depend>
<run_depend>roslib</run_depend>
<run_depend>rosnode</run_depend>
<run_depend>rosservice</run_depend>
<test_depend>cmake_modules</test_depend> <!-- since the other packages recursively depend on it roswtf needs to find it during its own tests -->
<export>
<rosdoc config="rosdoc.yaml"/>
<architecture_independent/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/rosdoc.yaml | - builder: epydoc
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/setup.py | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['roswtf'],
package_dir={'': 'src'},
scripts=['scripts/roswtf'],
requires=['genmsg', 'genpy', 'roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/roswtf/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-roswtf-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package roswtf
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.21 (2017-03-06)
--------------------
1.11.20 (2016-06-27)
--------------------
1.11.19 (2016-04-18)
--------------------
1.11.18 (2016-03-17)
--------------------
1.11.17 (2016-03-11)
--------------------
1.11.16 (2015-11-09)
--------------------
1.11.15 (2015-10-13)
--------------------
1.11.14 (2015-09-19)
--------------------
* add optional dependency on geneus to make roswtf tests pass in jade
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
* support IPv6 addresses containing percentage symbols (`#585 <https://github.com/ros/ros_comm/issues/585>`_)
1.11.10 (2014-12-22)
--------------------
1.11.9 (2014-08-18)
-------------------
1.11.8 (2014-08-04)
-------------------
1.11.7 (2014-07-18)
-------------------
1.11.6 (2014-07-10)
-------------------
1.11.5 (2014-06-24)
-------------------
1.11.4 (2014-06-16)
-------------------
* Python 3 compatibility (`#426 <https://github.com/ros/ros_comm/issues/426>`_, `#427 <https://github.com/ros/ros_comm/issues/427>`_)
1.11.3 (2014-05-21)
-------------------
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* update roswtf test for upcoming rospack 2.2.3
* add architecture_independent flag in package.xml (`#391 <https://github.com/ros/ros_comm/issues/391>`_)
1.11.0 (2014-03-04)
-------------------
* make rostest in CMakeLists optional (`ros/rosdistro#3010 <https://github.com/ros/rosdistro/issues/3010>`_)
1.10.0 (2014-02-11)
-------------------
1.9.54 (2014-01-27)
-------------------
* fix roswtf checks to not require release-only python packages to be installed
* add missing run/test dependencies on rosbuild to get ROS_ROOT environment variable
1.9.53 (2014-01-14)
-------------------
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
* do not warn about not existing stacks folder in a catkin workspace
1.9.50 (2013-10-04)
-------------------
1.9.49 (2013-09-16)
-------------------
1.9.48 (2013-08-21)
-------------------
1.9.47 (2013-07-03)
-------------------
* check for CATKIN_ENABLE_TESTING to enable configure without tests
1.9.46 (2013-06-18)
-------------------
1.9.45 (2013-06-06)
-------------------
1.9.44 (2013-03-21)
-------------------
* fix ROS_ROOT check to access trailing 'rosbuild'
1.9.43 (2013-03-13)
-------------------
1.9.42 (2013-03-08)
-------------------
1.9.41 (2013-01-24)
-------------------
1.9.40 (2013-01-13)
-------------------
* add checks for pip packages and rosdep
* fix check for catkin_pkg
* fix for thread race condition causes incorrect graph connectivity analysis
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/test/check_roswtf_command_line_online.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
PKG = 'roswtf'
NAME = 'test_roswtf_command_line_online'
import os
import signal
import sys
import time
import unittest
import rospkg
import rospy
import rostest
import std_msgs.msg
from subprocess import Popen, PIPE, check_call, call
def run_for(cmd, secs):
popen = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True)
timeout_t = time.time() + secs
while time.time() < timeout_t:
time.sleep(0.1)
os.kill(popen.pid, signal.SIGKILL)
class TestRostopicOnline(unittest.TestCase):
def setUp(self):
self.vals = set()
self.msgs = {}
## test that the rosmsg command works
def test_cmd_help(self):
cmd = 'roswtf'
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
self.assert_('Options' in output)
def test_offline(self):
# this test is disabled for now; now that test_roswtf is part
# of ros_comm, the tricks before that were used no longer work
cmd = 'roswtf'
# pass in special test key to roswtf for ROS_PACKAGE_PATH
env = os.environ.copy()
rospack = rospkg.RosPack()
# add all dependencies to ros package path
pkgs = ['roswtf',
'rosgraph', 'roslaunch', 'roslib', 'rosnode', 'rosservice',
'rosbag', 'rosbag_storage', 'roslz4', 'rosconsole', 'roscpp', 'rosgraph_msgs', 'roslang', 'rosmaster', 'rosmsg', 'rosout', 'rosparam', 'rospy', 'rostest', 'rostopic', 'topic_tools', 'xmlrpcpp',
'cpp_common', 'roscpp_serialization', 'roscpp_traits', 'rostime', # roscpp_core
'rosbuild', 'rosclean', 'rosunit', # ros
'rospack', 'std_msgs', 'message_runtime', 'message_generation', 'gencpp', 'genlisp', 'genpy', 'genmsg', 'catkin',
]
paths = [rospack.get_path(pkg) for pkg in pkgs]
try:
path = rospack.get_path('cmake_modules')
except rospkg.ResourceNotFound:
pass
else:
paths.append(path)
try:
path = rospack.get_path('geneus')
except rospkg.ResourceNotFound:
pass
else:
paths.append(path)
env['ROS_PACKAGE_PATH'] = os.pathsep.join(paths)
cwd = rospack.get_path('roswtf')
kwds = { 'env': env, 'stdout': PIPE, 'stderr': PIPE, 'cwd': cwd}
# run roswtf nakedly in the roswtf directory. Running in
# ROS_ROOT effectively make roswtf have dependencies on
# every package in the ROS stack, which doesn't work.
output, err = Popen([cmd], **kwds).communicate()
self._check_output([cmd], output, err)
# run roswtf on a simple launch file online
rospack = rospkg.RosPack()
p = os.path.join(rospack.get_path('roswtf'), 'test', 'min.launch')
output = Popen([cmd, p], **kwds).communicate()[0]
self._check_output([cmd, p], output)
def _check_output(self, cmd, output, error=None):
# do both a positive and negative test
self.assert_(
'No errors or warnings' in output or 'Found 1 error' in output,
'CMD[%s] OUTPUT[%s]%s' %
(' '.join(cmd), output, '\nstderr[%s]' % error if error else ''))
if 'No errors or warnings' in output:
self.assert_('ERROR' not in output, 'OUTPUT[%s]' % output)
if 'Found 1 error' in output:
self.assert_(output.count('ERROR') == 1, 'OUTPUT[%s]' % output)
self.assert_(
'Error: the rosdep view is empty' not in output,
'OUTPUT[%s]' % output)
if __name__ == '__main__':
rostest.run(PKG, NAME, TestRostopicOnline, sys.argv)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/test/min.launch | <launch>
<!-- $(anon talker) creates an anonymous name for this node -->
<node name="$(anon talker)" pkg="rospy" type="talker.py" />
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/test/roswtf.test | <launch>
<test test-name="roswtf_command_line_online" pkg="roswtf" type="check_roswtf_command_line_online.py" />
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/test/test_roswtf_command_line_offline.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import unittest
import time
from subprocess import Popen, PIPE, check_call, call
import rospkg
def get_test_path():
return os.path.abspath(os.path.dirname(__file__))
def get_roswtf_path():
return os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
class TestRoswtfOffline(unittest.TestCase):
def setUp(self):
pass
## test that the rosmsg command works
def test_cmd_help(self):
cmd = 'roswtf'
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
output = output.decode()
self.assert_('Options' in output)
def test_offline(self):
cmd = 'roswtf'
# point at a different 'master'
env = os.environ.copy()
env['ROS_MASTER_URI'] = 'http://localhost:11312'
rospack = rospkg.RosPack()
# add all dependencies to ros package path
pkgs = ['roswtf',
'rosgraph', 'roslaunch', 'roslib', 'rosnode', 'rosservice',
'rosbag', 'rosbag_storage', 'roslz4', 'rosconsole', 'roscpp', 'rosgraph_msgs', 'roslang', 'rosmaster', 'rosmsg', 'rosout', 'rosparam', 'rospy', 'rostest', 'rostopic', 'topic_tools', 'xmlrpcpp',
'cpp_common', 'roscpp_serialization', 'roscpp_traits', 'rostime', # roscpp_core
'rosbuild', 'rosclean', 'rosunit', # ros
'rospack', 'std_msgs', 'message_runtime', 'message_generation', 'gencpp', 'genlisp', 'genpy', 'genmsg', 'catkin',
]
paths = [rospack.get_path(pkg) for pkg in pkgs]
try:
path = rospack.get_path('cmake_modules')
except rospkg.ResourceNotFound:
pass
else:
paths.append(path)
try:
path = rospack.get_path('geneus')
except rospkg.ResourceNotFound:
pass
else:
paths.append(path)
env['ROS_PACKAGE_PATH'] = os.pathsep.join(paths)
cwd = get_roswtf_path()
kwds = { 'env': env, 'stdout': PIPE, 'stderr': PIPE, 'cwd': cwd}
# run roswtf nakedly
output = Popen([cmd], **kwds).communicate()
output = [o.decode() for o in output]
# there should either be no errors or warnings or
# there should be exactly one error about rosdep not being initialized
self._check_output(output[0])
# run roswtf on a simple launch file offline
p = os.path.join(get_test_path(), 'min.launch')
output = Popen([cmd, p], **kwds).communicate()[0]
output = output.decode()
self._check_output(output)
def _check_output(self, output):
# do both a positive and negative test
self.assert_(
'No errors or warnings' in output or 'Found 1 error' in output,
'OUTPUT[%s]' % output)
if 'No errors or warnings' in output:
self.assert_('ERROR' not in output, 'OUTPUT[%s]' % output)
if 'Found 1 error' in output:
self.assert_(output.count('ERROR') == 1, 'OUTPUT[%s]' % output)
self.assert_(
'Error: the rosdep view is empty' not in output,
'OUTPUT[%s]' % output)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/scripts/roswtf | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import roswtf
roswtf.roswtf_main()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/plugins.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Plugin loader for roswtf.
"""
from __future__ import print_function
import os
import sys
import roslib
import rospkg
def load_plugins():
"""
@return: list of static roswtf plugins, list of online
roswtf plugins
@rtype: [fn], [fn]
"""
rospack = rospkg.RosPack()
to_check = rospack.get_depends_on('roswtf', implicit=False)
static_plugins = []
online_plugins = []
for pkg in to_check:
m = rospack.get_manifest(pkg)
p_module = m.get_export('roswtf', 'plugin')
if not p_module:
continue
elif len(p_module) != 1:
print("Cannot load plugin [%s]: invalid 'plugin' attribute"%(pkg), file=sys.stderr)
continue
p_module = p_module[0]
try:
# load that packages namespace
roslib.load_manifest(pkg)
# import the specified plugin module
mod = __import__(p_module)
for sub_mod in p_module.split('.')[1:]:
mod = getattr(mod, sub_mod)
# retrieve the roswtf_plugin_static and roswtf_plugin_online functions
s_attr = o_attr = None
try:
s_attr = getattr(mod, 'roswtf_plugin_static')
except AttributeError: pass
try:
o_attr = getattr(mod, 'roswtf_plugin_online')
except AttributeError: pass
if s_attr:
static_plugins.append(s_attr)
if o_attr:
online_plugins.append(o_attr)
if s_attr is None and o_attr is None:
print("Cannot load plugin [%s]: no 'roswtf_plugin_static' or 'roswtf_plugin_online' attributes [%s]"%(p_module), file=sys.stderr)
else:
print("Loaded plugin", p_module)
except Exception:
print("Unable to load plugin [%s] from package [%s]"%(p_module, pkg), file=sys.stderr)
return static_plugins, online_plugins
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/rosdep_db.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Checks if rosdep database has been initialized
"""
import os
def get_user_home_directory():
"""Returns cross-platform user home directory """
return os.path.expanduser("~")
def rosdep_database_initialized_check(ctx):
"""Makes sure rosdep database is initialized"""
if not os.path.exists((os.path.join(get_user_home_directory(), '.ros', 'rosdep', 'sources.cache', 'index'))):
return "Please initialize rosdep database with sudo rosdep init."
warnings = []
errors = [(rosdep_database_initialized_check,
"ROS Dep database not initialized: "),
]
def wtf_check(ctx):
"""Check implementation function for roswtf"""
from roswtf.rules import warning_rule, error_rule
for r in warnings:
warning_rule(r, r[0](ctx), ctx)
for r in errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/py_pip_deb_checks.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Checks to see if core Python scripts have:
1) Been installed
2) Have been installed via Debians on Ubuntu
3) Have not been installed via pip on Ubuntu
"""
from __future__ import print_function
import subprocess
import importlib
import os
import sys
python_prefix = 'python'
if sys.version_info[0] == 3:
python_prefix += '3'
#A dictionary of core ROS python packages and their corresponding .deb packages
py_to_deb_core_packages = {
'catkin_pkg': '%s-catkin-pkg' % python_prefix,
'rospkg': '%s-rospkg' % python_prefix,
'rosdep2': '%s-rosdep' % python_prefix,
}
# optional ROS python packages and their corresponding .deb packages
py_to_deb_optional_packages = {
'rosinstall': '%s-rosinstall' % python_prefix,
}
#A dictionary of release ROS python packages and their corresponding .deb packages
py_to_deb_release_packages = {
'bloom': '%s-bloom' % python_prefix,
'rosrelease': '%s-rosrelease' % python_prefix,
}
def get_host_os():
"""Determines the name of the host operating system"""
import rospkg.os_detect
os_detector = rospkg.os_detect.OsDetect()
return (os_detector.detect_os())[0]
def is_host_os_ubuntu():
"""Indicates if the host operating system is Ubuntu"""
return (get_host_os() == 'ubuntu')
def is_debian_package_installed(deb_pkg):
"""Uses dpkg to determine if a package has been installed"""
return (subprocess.call(
'dpkg -l ' + deb_pkg,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) == 0)
def is_a_pip_path_on_ubuntu(path):
"""Indicates if a path (either directory or file) is in the same place
pip installs Python code"""
return ('/usr/local' in path)
def is_python_package_installed(python_pkg):
"""Indicates if a Python package is importable in the current
environment."""
try:
importlib.import_module(python_pkg)
return True
except ImportError:
return False
def is_python_package_installed_via_pip_on_ubuntu(python_pkg):
"""Indicates if am importable package has been installed through pip on
Ubuntu"""
try:
pkg_handle = importlib.import_module(python_pkg)
return is_a_pip_path_on_ubuntu(pkg_handle.__file__)
except ImportError:
return False
# Error/Warning Rules
def python_module_install_check(ctx):
"""Make sure core Python modules are installed"""
warn_str = ''
for py_pkg in py_to_deb_core_packages:
if not is_python_package_installed(py_pkg):
warn_str = warn_str + py_pkg + ' -- '
if (warn_str != ''):
return warn_str
def deb_install_check_on_ubuntu(ctx):
"""Make sure on Debian python packages are installed"""
if (is_host_os_ubuntu()):
warn_str = ''
for py_pkg in py_to_deb_core_packages:
deb_pkg = py_to_deb_core_packages[py_pkg]
if not is_debian_package_installed(deb_pkg):
warn_str = warn_str + py_pkg + ' (' + deb_pkg + ') -- '
if (warn_str != ''):
return warn_str
def pip_install_check_on_ubuntu(ctx):
"""Make sure on Ubuntu, Python packages are install with apt and not pip"""
if (is_host_os_ubuntu()):
warn_str = ''
pt_to_deb_package_names = list(py_to_deb_core_packages.keys()) + \
list(py_to_deb_optional_packages.keys()) + list(py_to_deb_release_packages.keys())
for py_pkg in pt_to_deb_package_names:
if is_python_package_installed_via_pip_on_ubuntu(py_pkg):
warn_str = warn_str + py_pkg + ' -- '
if (warn_str != ''):
return warn_str
warnings = [
(python_module_install_check,
"You are missing core ROS Python modules: "),
(pip_install_check_on_ubuntu,
"You have pip installed packages on Ubuntu, "
"remove and install using Debian packages: "),
(deb_install_check_on_ubuntu,
"You are missing Debian packages for core ROS Python modules: "),
]
errors = []
def wtf_check(ctx):
"""Check implementation function for roswtf"""
from roswtf.rules import warning_rule, error_rule
for r in warnings:
warning_rule(r, r[0](ctx), ctx)
for r in errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/graph.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
from __future__ import print_function
from __future__ import with_statement
import os
import itertools
import socket
import sys
import time
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
import rospkg.environment
import rosgraph
import rosgraph.rosenv
import rosgraph.network
import rosnode
import rosservice
from roswtf.context import WtfException
from roswtf.environment import paths, is_executable
from roswtf.model import WtfWarning, WtfError
from roswtf.rules import warning_rule, error_rule
def _businfo(ctx, node, bus_info):
# [[connectionId1, destinationId1, direction1, transport1, ...]... ]
edges = []
for info in bus_info:
#connection_id = info[0]
dest_id = info[1]
if dest_id.startswith('http://'):
if dest_id in ctx.uri_node_map:
dest_id = ctx.uri_node_map[dest_id]
else:
dest_id = 'unknown (%s)'%dest_id
direction = info[2]
#transport = info[3]
topic = info[4]
if len(info) > 5:
connected = info[5]
else:
connected = True #backwards compatibility
if connected:
if direction == 'i':
edges.append((topic, dest_id, node))
elif direction == 'o':
edges.append((topic, node, dest_id))
elif direction == 'b':
print("cannot handle bidirectional edges", file=sys.stderr)
else:
raise Exception()
return edges
def unexpected_edges(ctx):
if not ctx.system_state or not ctx.nodes:
return
unexpected = set(ctx.actual_edges) - set(ctx.expected_edges)
return ["%s->%s (%s)"%(p, s, t) for (t, p, s) in unexpected]
def missing_edges(ctx):
if not ctx.system_state or not ctx.nodes:
return
missing = set(ctx.expected_edges) - set(ctx.actual_edges)
return ["%s->%s (%s)"%(p, s, t) for (t, p, s) in missing]
def ping_check(ctx):
if not ctx.system_state or not ctx.nodes:
return
_, unpinged = rosnode.rosnode_ping_all()
return unpinged
def simtime_check(ctx):
if ctx.use_sim_time:
master = rosgraph.Master('/roswtf')
try:
pubtopics = master.getPublishedTopics('/')
except rosgraph.MasterException:
ctx.errors.append(WtfError("Cannot talk to ROS master"))
raise WtfException("roswtf lost connection to the ROS Master at %s"%rosgraph.rosenv.get_master_uri())
for topic, _ in pubtopics:
if topic in ['/time', '/clock']:
return
return True
## contact each service and make sure it returns a header
def probe_all_services(ctx):
master = rosgraph.Master('/roswtf')
errors = []
for service_name in ctx.services:
try:
service_uri = master.lookupServiceCache(service_name)
except:
ctx.errors.append(WtfError("cannot contact ROS Master at %s"%rosgraph.rosenv.get_master_uri()))
raise WtfException("roswtf lost connection to the ROS Master at %s"%rosgraph.rosenv.get_master_uri())
try:
headers = rosservice.get_service_headers(service_name, service_uri)
if not headers:
errors.append("service [%s] did not return service headers"%service_name)
except rosgraph.network.ROSHandshakeException as e:
errors.append("service [%s] appears to be malfunctioning"%service_name)
except Exception as e:
errors.append("service [%s] appears to be malfunctioning: %s"%(service_name, e))
return errors
def unconnected_subscriptions(ctx):
ret = ''
whitelist = ['/reset_time']
if ctx.use_sim_time:
for sub, l in ctx.unconnected_subscriptions.items():
l = [t for t in l if t not in whitelist]
if l:
ret += ' * %s:\n'%sub
ret += ''.join([" * %s\n"%t for t in l])
else:
for sub, l in ctx.unconnected_subscriptions.items():
l = [t for t in l if t not in ['/time', '/clock']]
if l:
ret += ' * %s:\n'%sub
ret += ''.join([" * %s\n"%t for t in l])
return ret
graph_warnings = [
(unconnected_subscriptions, "The following node subscriptions are unconnected:\n"),
(unexpected_edges, "The following nodes are unexpectedly connected:"),
]
graph_errors = [
(simtime_check, "/use_simtime is set but no publisher of /clock is present"),
(ping_check, "Could not contact the following nodes:"),
(missing_edges, "The following nodes should be connected but aren't:"),
(probe_all_services, "Errors connecting to the following services:"),
]
def topic_timestamp_drift(ctx, t):
#TODO: get msg_class, if msg_class has header, receive a message
# and compare its time to ros time
if 0:
rospy.Subscriber(t, msg_class)
#TODO: these are mainly future enhancements. It's unclear to me whether or not this will be
#useful as most of the generic rules are capable of targetting these problems as well.
#The only rule that in particular seems useful is the timestamp drift. It may be too
#expensive otherwise to run, though it would be interesting to attempt to receive a
#message from every single topic.
#TODO: parameter audit?
service_errors = [
]
service_warnings = [
]
topic_errors = [
(topic_timestamp_drift, "Timestamp drift:")
]
topic_warnings = [
]
node_errors = [
]
node_warnings = [
]
## cache sim_time calculation sot that multiple rules can use
def _compute_sim_time(ctx):
param_server = rosgraph.Master('/roswtf')
ctx.use_sim_time = False
try:
val = simtime = param_server.getParam('/use_sim_time')
if val:
ctx.use_sim_time = True
except:
pass
def _compute_system_state(ctx):
socket.setdefaulttimeout(3.0)
master = rosgraph.Master('/roswtf')
# store system state
try:
val = master.getSystemState()
except rosgraph.MasterException:
return
ctx.system_state = val
pubs, subs, srvs = val
# compute list of topics and services
topics = []
for t, _ in itertools.chain(pubs, subs):
topics.append(t)
services = []
service_providers = []
for s, l in srvs:
services.append(s)
service_providers.extend(l)
ctx.topics = topics
ctx.services = services
ctx.service_providers = service_providers
# compute list of nodes
nodes = []
for s in val:
for t, l in s:
nodes.extend(l)
ctx.nodes = list(set(nodes)) #uniq
# - compute reverse mapping of URI->nodename
count = 0
start = time.time()
for n in ctx.nodes:
count += 1
try:
val = master.lookupNode(n)
except socket.error:
ctx.errors.append(WtfError("cannot contact ROS Master at %s"%rosgraph.rosenv.get_master_uri()))
raise WtfException("roswtf lost connection to the ROS Master at %s"%rosgraph.rosenv.get_master_uri())
ctx.uri_node_map[val] = n
end = time.time()
# - time thresholds currently very arbitrary
if count:
if ((end - start) / count) > 1.:
ctx.warnings.append(WtfError("Communication with master is very slow (>1s average)"))
elif (end - start) / count > .5:
ctx.warnings.append(WtfWarning("Communication with master is very slow (>0.5s average)"))
import threading
class NodeInfoThread(threading.Thread):
def __init__(self, n, ctx, master, actual_edges, lock):
threading.Thread.__init__(self)
self.master = master
self.actual_edges = actual_edges
self.lock = lock
self.n = n
self.done = False
self.ctx = ctx
def run(self):
ctx = self.ctx
master = self.master
actual_edges = self.actual_edges
lock = self.lock
n = self.n
try:
socket.setdefaulttimeout(3.0)
with lock: #Apparently get_api_uri is not thread safe...
node_api = rosnode.get_api_uri(master, n)
if not node_api:
with lock:
ctx.errors.append(WtfError("Master does not have lookup information for node [%s]"%n))
return
node = ServerProxy(node_api)
start = time.time()
socket.setdefaulttimeout(3.0)
code, msg, bus_info = node.getBusInfo('/roswtf')
end = time.time()
with lock:
if (end-start) > 1.:
ctx.warnings.append(WtfWarning("Communication with node [%s] is very slow"%n))
if code != 1:
ctx.warnings.append(WtfWarning("Node [%s] would not return bus info"%n))
elif not bus_info:
if not n in ctx.service_providers:
ctx.warnings.append(WtfWarning("Node [%s] is not connected to anything"%n))
else:
edges = _businfo(ctx, n, bus_info)
actual_edges.extend(edges)
except socket.error:
pass #ignore as we have rules to catch this
except Exception as e:
ctx.errors.append(WtfError("Communication with [%s] raised an error: %s"%(n, str(e))))
finally:
self.done = True
## retrieve graph state from master and related nodes once so we don't overload
## the network
def _compute_connectivity(ctx):
socket.setdefaulttimeout(3.0)
master = rosgraph.Master('/roswtf')
# Compute list of expected edges and unconnected subscriptions
pubs, subs, _ = ctx.system_state
expected_edges = [] # [(topic, publisher, subscriber),]
unconnected_subscriptions = {} # { subscriber : [topics] }
# - build up a dictionary of publishers keyed by topic
pub_dict = {}
for t, pub_list in pubs:
pub_dict[t] = pub_list
# - iterate through subscribers and add edge to each publisher of topic
for t, sub_list in subs:
for sub in sub_list:
if t in pub_dict:
expected_edges.extend([(t, pub, sub) for pub in pub_dict[t]])
elif sub in unconnected_subscriptions:
unconnected_subscriptions[sub].append(t)
else:
unconnected_subscriptions[sub] = [t]
# compute actual edges
actual_edges = []
lock = threading.Lock()
threads = []
for n in ctx.nodes:
t =NodeInfoThread(n, ctx, master, actual_edges, lock)
threads.append(t)
t.start()
# spend up to a minute waiting for threads to complete. each
# thread has a 3-second timeout, but this will spike load
timeout_t = time.time() + 60.0
while time.time() < timeout_t and [t for t in threads if not t.done]:
time.sleep(0.5)
ctx.expected_edges = expected_edges
ctx.actual_edges = actual_edges
ctx.unconnected_subscriptions = unconnected_subscriptions
def _compute_online_context(ctx):
# have to compute sim time first
_compute_sim_time(ctx)
_compute_system_state(ctx)
_compute_connectivity(ctx)
def wtf_check_graph(ctx, names=None):
master_uri = ctx.ros_master_uri
#TODO: master rules
# - check for stale master state
# TODO: get the type for each topic from each publisher and see if they match up
master = rosgraph.Master('/roswtf')
try:
master.getPid()
except rospkg.MasterException:
warning_rule((True, "Cannot communicate with master, ignoring online checks"), True, ctx)
return
# fill in ctx info so we only have to compute once
print("analyzing graph...")
_compute_online_context(ctx)
print("... done analyzing graph")
if names:
check_topics = [t for t in names if t in ctx.topics]
check_services = [t for t in names if t in ctx.services]
check_nodes = [t for t in names if t in ctx.nodes]
unknown = [t for t in names if t not in check_topics + check_services + check_nodes]
if unknown:
raise WtfException("The following names were not found in the list of nodes, topics, or services:\n%s"%(''.join([" * %s\n"%t for t in unknown])))
for t in check_topics:
for r in topic_warnings:
warning_rule(r, r[0](ctx, t), ctx)
for r in topic_errors:
error_rule(r, r[0](ctx, t), ctx)
for s in check_services:
for r in service_warnings:
warning_rule(r, r[0](ctx, s), ctx)
for r in service_errors:
error_rule(r, r[0](ctx, s), ctx)
for n in check_nodes:
for r in node_warnings:
warning_rule(r, r[0](ctx, n), ctx)
for r in node_errors:
error_rule(r, r[0](ctx, n), ctx)
print("running graph rules...")
for r in graph_warnings:
warning_rule(r, r[0](ctx), ctx)
for r in graph_errors:
error_rule(r, r[0](ctx), ctx)
print("... done running graph rules")
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/__init__.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
roswtf command-line tool.
"""
from __future__ import print_function
import os
import socket
import sys
import traceback
import rospkg
import rosgraph.names
def yaml_results(ctx):
cd = ctx.as_dictionary()
d = {}
d['warnings'] = {}
d['errors'] = {}
wd = d['warnings']
for warn in ctx.warnings:
wd[warn.format_msg%cd] = warn.return_val
ed = d['warnings']
for err in ctx.warnings:
ed[err.format_msg%cd] = err.return_val
import yaml
print(yaml.dump(d))
def print_results(ctx):
if not ctx.warnings and not ctx.errors:
print("No errors or warnings")
else:
if ctx.warnings:
print("Found %s warning(s).\nWarnings are things that may be just fine, but are sometimes at fault\n" % len(ctx.warnings))
for warn in ctx.warnings:
print('\033[1mWARNING\033[0m', warn.msg)
print('')
if ctx.errors:
print("Found %s error(s).\n"%len(ctx.errors))
for e in ctx.errors:
print('\033[31m\033[1mERROR\033[0m', e.msg)
#print("ERROR:", e.msg
def roswtf_main():
try:
import std_msgs.msg
import rosgraph_msgs.msg
except ImportError:
print("ERROR: The core ROS message libraries (std_msgs and rosgraph_msgs) have not been built.")
sys.exit(1)
from roswtf.context import WtfException
try:
_roswtf_main()
except WtfException as e:
print(str(e), file=sys.stderr)
def _roswtf_main():
launch_files = names = None
# performance optimization
rospack = rospkg.RosPack()
all_pkgs = rospack.list()
import optparse
parser = optparse.OptionParser(usage="usage: roswtf [launch file]", description="roswtf is a tool for verifying a ROS installation and running system. Checks provided launchfile if provided, else current stack or package.")
# #2268
parser.add_option("--all",
dest="all_packages", default=False,
action="store_true",
help="run roswtf against all packages")
# #2270
parser.add_option("--no-plugins",
dest="disable_plugins", default=False,
action="store_true",
help="disable roswtf plugins")
parser.add_option("--offline",
dest="offline", default=False,
action="store_true",
help="only run offline tests")
#TODO: --all-pkgs option
options, args = parser.parse_args()
if args:
launch_files = args
if 0:
# disable names for now as don't have any rules yet
launch_files = [a for a in args if os.path.isfile(a)]
names = [a for a in args if not a in launch_files]
names = [rosgraph.names.script_resolve_name('/roswtf', n) for n in names]
from roswtf.context import WtfContext
from roswtf.environment import wtf_check_environment, invalid_url, ros_root_check
from roswtf.graph import wtf_check_graph
import roswtf.rosdep_db
import roswtf.py_pip_deb_checks
import roswtf.network
import roswtf.packages
import roswtf.roslaunchwtf
import roswtf.stacks
import roswtf.plugins
if not options.disable_plugins:
static_plugins, online_plugins = roswtf.plugins.load_plugins()
else:
static_plugins, online_plugins = [], []
# - do a ros_root check first and abort if it fails as rest of tests are useless after that
error = ros_root_check(None, ros_root=os.environ['ROS_ROOT'])
if error:
print("ROS_ROOT is invalid: "+str(error))
sys.exit(1)
all_warnings = []
all_errors = []
if launch_files:
ctx = WtfContext.from_roslaunch(launch_files)
#TODO: allow specifying multiple roslaunch files
else:
curr_package = rospkg.get_package_name('.')
if curr_package:
print("Package:", curr_package)
ctx = WtfContext.from_package(curr_package)
#TODO: load all .launch files in package
elif os.path.isfile('stack.xml'):
curr_stack = os.path.basename(os.path.abspath('.'))
print("Stack:", curr_stack)
ctx = WtfContext.from_stack(curr_stack)
else:
print("No package or stack in context")
ctx = WtfContext.from_env()
if options.all_packages:
print("roswtf will run against all packages")
ctx.pkgs = all_pkgs
# static checks
wtf_check_environment(ctx)
roswtf.rosdep_db.wtf_check(ctx)
roswtf.py_pip_deb_checks.wtf_check(ctx)
roswtf.network.wtf_check(ctx)
roswtf.packages.wtf_check(ctx)
roswtf.stacks.wtf_check(ctx)
roswtf.roslaunchwtf.wtf_check_static(ctx)
for p in static_plugins:
p(ctx)
print("="*80)
print("Static checks summary:\n")
print_results(ctx)
# Save static results and start afresh for online checks
all_warnings.extend(ctx.warnings)
all_errors.extend(ctx.errors)
del ctx.warnings[:]
del ctx.errors[:]
# test online
print("="*80)
try:
if options.offline or not ctx.ros_master_uri or invalid_url(ctx.ros_master_uri) or not rosgraph.is_master_online():
online_checks = False
else:
online_checks = True
if online_checks:
online_checks = True
print("Beginning tests of your ROS graph. These may take awhile...")
# online checks
wtf_check_graph(ctx, names=names)
elif names:
# TODO: need to rework this logic
print("\nCannot communicate with master, unable to diagnose [%s]"%(', '.join(names)))
return
else:
print("\nROS Master does not appear to be running.\nOnline graph checks will not be run.\nROS_MASTER_URI is [%s]"%(ctx.ros_master_uri))
return
# spin up a roswtf node so we can subscribe to messages
import rospy
rospy.init_node('roswtf', anonymous=True)
online_checks = True
roswtf.roslaunchwtf.wtf_check_online(ctx)
for p in online_plugins:
online_checks = True
p(ctx)
if online_checks:
# done
print("\nOnline checks summary:\n")
print_results(ctx)
except roswtf.context.WtfException as e:
print(str(e), file=sys.stderr)
print("\nAborting checks, partial results summary:\n")
print_results(ctx)
except Exception as e:
traceback.print_exc()
print(str(e), file=sys.stderr)
print("\nAborting checks, partial results summary:\n")
print_results(ctx)
#TODO: print results in YAML if run remotely
#yaml_results(ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/rules.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Common library for writing rule-style checks for generating warnings
and errors. Use of this style streamlines reporting.
The pattern for rules is simple: a rule provides a function that
implements the rule and a format string. If the function returns a
non-zero value, that value is combined with the format string to
produced an error reporting string. There are other conveniences as
well. If the rule returns a list or a tuple, that will be transformed
into a human-readable list.
This library is a layer on top of the base L{WtfWarning} and
L{WtfError} representation in roswtf.model.
"""
from roswtf.model import WtfWarning, WtfError
def _check_rule(rule, ret, ctx, ctx_list, level):
if ret:
d = ctx.as_dictionary()
def isstring(s):
"""Small helper version to check an object is a string in
a way that works for both Python 2 and 3
"""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
if type(ret) in (tuple, list):
f_msg = rule[1]
ret_str = '\n'.join([" * %s"%r for r in ret])
ctx_list.append(level(f_msg%d + "\n" + ret_str+'\n', f_msg, ret))
elif isstring(ret):
f_msg = rule[1]
ctx_list.append(level(f_msg%d + ret%d, f_msg, ret))
else:
f_msg = rule[1]
ctx_list.append(level(f_msg%d, f_msg, ret))
def warning_rule(rule, ret, ctx):
"""
Check return value of rule and update ctx if rule failed.
@param rule: Rule/message pair.
@type rule: (rule_fn, format_msg)
@param ret: return value of rule. If value is non-zero, rule failed
@param ret: Any
@param ctx: context for which rule failed
@param ctx: L{WtfContext}
"""
_check_rule(rule, ret, ctx, ctx.warnings, WtfWarning)
def error_rule(rule, ret, ctx):
"""
Check return value of rule and update ctx if rule failed.
@param rule: Rule/message pair.
@type rule: (rule_fn, format_msg)
@param ret: return value of rule. If value is non-zero, rule failed
@type ret: Any
@param ctx: context for which rule failed
@type ctx: L{WtfContext}
"""
_check_rule(rule, ret, ctx, ctx.errors, WtfError)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/packages.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
import os
import time
from roswtf.environment import paths, is_executable
from roswtf.rules import warning_rule, error_rule
import roslib.msgs
import roslib.srvs
from roslib.packages import get_pkg_dir, InvalidROSPkgException, PACKAGE_FILE
## look for unknown tags in manifest
def manifest_valid(ctx):
errors = []
if ctx.manifest is not None:
errors = ["<%s>"%t.tagName for t in ctx.manifest.unknown_tags]
return errors
def _manifest_msg_srv_export(ctx, type_):
exist = []
for pkg in ctx.pkgs:
pkg_dir = roslib.packages.get_pkg_dir(pkg)
d = os.path.join(pkg_dir, type_)
if os.path.isdir(d):
files = os.listdir(d)
if filter(lambda x: x.endswith('.'+type_), files):
try:
m_file = roslib.manifest.manifest_file(pkg, True)
except InvalidROSPkgException:
# ignore wet package from further investigation
env = os.environ
pkg_path = get_pkg_dir(pkg, True, ros_root=env['ROS_ROOT'])
if os.path.exists(os.path.join(pkg_path, PACKAGE_FILE)):
continue
raise
m = roslib.manifest.parse_file(m_file)
cflags = m.get_export('cpp', 'cflags')
include = '-I${prefix}/%s/cpp'%type_
if filter(lambda x: include in x, cflags):
exist.append(pkg)
return exist
def manifest_msg_srv_export(ctx):
msgs = set(_manifest_msg_srv_export(ctx, 'msg'))
srvs = set(_manifest_msg_srv_export(ctx, 'srv'))
errors = []
for pkg in msgs & srvs:
errors.append('%s: -I${prefix}/msg/cpp -I${prefix}/srv/cpp'%pkg)
for pkg in msgs - srvs:
errors.append('%s: -I${prefix}/msg/cpp'%pkg)
for pkg in srvs - msgs:
errors.append('%s: -I${prefix}/srv/cpp'%pkg)
return errors
def _check_for_rpath_flags(pkg, lflags):
if not lflags:
return
L_arg = '-L'
Wl_arg = '-Wl'
rpath_arg = '-rpath'
lflags_args = lflags.split()
# Collect the args we care about
L_args = []
rpath_args = []
i = 0
while i < len(lflags_args):
f = lflags_args[i]
if f.startswith(L_arg) and len(f) > len(L_arg):
# normpath avoids problems with trailing slash vs. no trailing
# slash, #2284
L_args.append(os.path.normpath(f[len(L_arg):]))
elif f == L_arg and (i+1) < len(lflags_args):
i += 1
# normpath avoids problems with trailing slash vs. no trailing
# slash, #2284
L_args.append(os.path.normpath(lflags_args[i]))
elif f.startswith(Wl_arg) and len(f) > len(Wl_arg):
# -Wl can be followed by multiple, comma-separated arguments,
# #2284.
args = f.split(',')
j = 1
while j < (len(args) - 1):
if args[j] == rpath_arg:
# normpath avoids problems with trailing slash vs. no trailing
# slash, #2284
rpath_args.append(os.path.normpath(args[j+1]))
j += 2
else:
j += 1
i += 1
# Check for parallelism; not efficient, but these strings are short
for f in L_args:
if f not in rpath_args:
return '%s: found flag "-L%s", but no matching "-Wl,-rpath,%s"'%(pkg, f,f)
for f in rpath_args:
if f not in L_args:
return '%s: found flag "-Wl,-rpath,%s", but no matching "-L%s"'%(pkg, f,f)
def manifest_rpath_flags(ctx):
warn = []
for pkg in ctx.pkgs:
# Use rospack to get lflags, so that they can be bash-expanded
# first, #2286.
import subprocess
lflags = subprocess.Popen(['rospack', 'export', '--lang=cpp', '--attrib=lflags', pkg], stdout=subprocess.PIPE).communicate()[0]
err_msg = _check_for_rpath_flags(pkg, lflags)
if err_msg:
warn.append(err_msg)
return warn
def cmakelists_package_valid(ctx):
missing = []
for pkg in ctx.pkgs:
found = False
pkg_dir = roslib.packages.get_pkg_dir(pkg)
p = os.path.join(pkg_dir, 'CMakeLists.txt')
if not os.path.isfile(p):
continue #covered by cmakelists_exists
f = open(p)
try:
for l in f:
# ignore all whitespace
l = l.strip().replace(' ', '')
if l.startswith('rospack('):
found = True
if not l.startswith('rospack(%s)'%pkg):
missing.append(pkg)
break
# there may be more than 1 rospack() declaration, so scan through entire
# CMakeLists
elif l.startswith("rosbuild_init()"):
found = True
finally:
f.close()
# rospack exists outside our build system
if 'rospack' in missing:
missing.remove('rospack')
return missing
warnings = [
# disabling as it is too common and regular
(cmakelists_package_valid,
"The following packages have incorrect rospack() declarations in CMakeLists.txt.\nPlease switch to using rosbuild_init():"),
(manifest_msg_srv_export,
'The following packages have msg/srv-related cflags exports that are no longer necessary\n\t<export>\n\t\t<cpp cflags="..."\n\t</export>:'),
(manifest_valid, "%(pkg)s/manifest.xml has unrecognized tags:"),
]
errors = [
(manifest_rpath_flags, "The following packages have rpath issues in manifest.xml:"),
]
def wtf_check(ctx):
# no package in context to verify
if not ctx.pkgs:
return
for r in warnings:
warning_rule(r, r[0](ctx), ctx)
for r in errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/model.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Error and Warning representation. The roswtf.rules module simplifies
the process of creating instances of L{WtfError}s and L{WtfWarning}s,
but these objects can be used directly if desired.
"""
class WtfError(object):
def __init__(self, msg, format_msg=None, return_val=None):
self.msg = msg
if format_msg is None:
self.format_msg = msg
else:
self.format_msg = format_msg
if return_val is None:
self.return_val = True
else:
self.return_val = return_val
class WtfWarning(object):
def __init__(self, msg, format_msg=None, return_val=None):
self.msg = msg
if format_msg is None:
self.format_msg = msg
else:
self.format_msg = format_msg
if return_val is None:
self.return_val = True
else:
self.return_val = return_val
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/context.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
L{WtfContext} object, which is commonly used throughout the roswtf
APIs to pass state.
"""
import os
import sys
import rospkg
import rospkg.environment
import rosgraph
import roslaunch.depends
import roslaunch.substitution_args
from roswtf.model import WtfWarning
class WtfException(Exception):
"""
Base exception class of roswtf-related issues.
"""
pass
class WtfContext(object):
"""
WtfContext stores common state about the ROS filesystem and online
environment. The primary use of this is for convenience (not
having to load this state manually) and performance (not having to
do the same calculation repeatedly).
"""
__slots__ = ['pkg', 'pkg_dir', 'pkgs',
'stack', 'stack_dir', 'stacks',
'manifest_file', 'manifest',
'env', 'ros_root', 'ros_package_path', 'pythonpath',
'ros_master_uri',
'roslaunch_uris',
'launch_files',
'launch_file_deps',
'launch_file_missing_deps',
'system_state',
'service_providers',
'topics', 'services',
'nodes', 'uri_node_map',
'expected_edges',
'actual_edges',
'unconnected_subscriptions',
'use_sim_time',
'warnings', 'errors',
'rospack', 'rosstack']
def __init__(self):
# main package we are running
self.pkg = None
self.pkg_dir = None
# main stack we are running
self.stack = None
self.stack_dir = None
# - list of all packages involved in this check
self.pkgs = []
# - list of all stacks involved in this check
self.stacks = []
# manifest location of package that we are running
self.manifest_file = None
# manifest of package that we are running
self.manifest = None
# environment variables
self.env = {}
# provide these for convenience
self.ros_root = None
self.ros_package_path = None
self.pythonpath = None
# launch file that is being run
self.launch_files = None
self.launch_file_deps = None
self.launch_file_missing_deps = None
# online state
self.roslaunch_uris = None
self.system_state = None #master.getSystemState
self.topics = None
self.services = None
self.service_providers = None #names of nodes with services
self.nodes = None
self.uri_node_map = {}
self.expected_edges = None
self.actual_edges = None
self.unconnected_subscriptions = None
self.use_sim_time = None
# caching rospack instance
self.rospack = self.rosstack = None
# warnings that we have collected so far
self.warnings = []
# errors that we have collected so far
self.errors = []
def as_dictionary(self):
"""
@return: dictionary representation of context, which is
useful for producing error messages
@rtype: dict
"""
return dict((s, getattr(self, s)) for s in self.__slots__)
@staticmethod
def from_roslaunch(roslaunch_files, env=None):
"""
@param roslaunch_file: roslaunch_file to load from
@type roslaunch_file: str
"""
if env is None:
env = os.environ
# can't go any further if launch file doesn't validate
l, c = roslaunch.XmlLoader(), roslaunch.ROSLaunchConfig()
for f in roslaunch_files:
try:
l.load(f, c, verbose=False)
except roslaunch.RLException as e:
raise WtfException("Unable to load roslaunch file [%s]: %s"%(f, str(e)))
ctx = WtfContext()
ctx.rospack = rospkg.RosPack(rospkg.get_ros_paths(env))
ctx.rosstack = rospkg.RosStack(rospkg.get_ros_paths(env))
ctx.launch_files = roslaunch_files
_load_roslaunch(ctx, roslaunch_files)
# ctx.pkg and ctx.stack initialized by _load_roslaunch
_load_pkg(ctx, ctx.pkg)
if ctx.stack:
_load_stack(ctx, ctx.stack)
_load_env(ctx, env)
return ctx
@staticmethod
def from_stack(stack, env=None):
"""
Initialize WtfContext from stack.
@param stack: stack name
@type stack: str
@raise WtfException: if context state cannot be initialized
"""
if env is None:
env = os.environ
ctx = WtfContext()
ctx.rospack = rospkg.RosPack(rospkg.get_ros_paths(env))
ctx.rosstack = rospkg.RosStack(rospkg.get_ros_paths(env))
_load_stack(ctx, stack)
try:
ctx.pkgs = ctx.rosstack.packages_of(stack)
except rospkg.ResourceNotFound:
# this should be handled elsewhere
ctx.pkgs = []
_load_env(ctx, env)
return ctx
@staticmethod
def from_package(pkg, env=None):
"""
Initialize WtfContext from package name.
@param pkg: package name
@type pkg: str
@raise WtfException: if context state cannot be initialized
"""
if env is None:
env = os.environ
ctx = WtfContext()
ctx.rospack = rospkg.RosPack(rospkg.get_ros_paths(env))
ctx.rosstack = rospkg.RosStack(rospkg.get_ros_paths(env))
_load_pkg(ctx, pkg)
stack = ctx.rospack.stack_of(pkg)
if stack:
_load_stack(ctx, stack)
_load_env(ctx, env)
return ctx
@staticmethod
def from_env(env=None):
"""
Initialize WtfContext from environment.
@raise WtfException: if context state cannot be initialized
"""
if env is None:
env = os.environ
ctx = WtfContext()
ctx.rospack = rospkg.RosPack(rospkg.get_ros_paths(env))
ctx.rosstack = rospkg.RosStack(rospkg.get_ros_paths(env))
_load_env(ctx, env)
return ctx
def _load_roslaunch(ctx, roslaunch_files):
"""
Utility for initializing WtfContext state from roslaunch file
"""
try:
base_pkg, file_deps, missing = roslaunch.depends.roslaunch_deps(roslaunch_files)
ctx.pkg = base_pkg
ctx.launch_file_deps = file_deps
ctx.launch_file_missing_deps = missing
except roslaunch.substitution_args.SubstitutionException as se:
raise WtfException("Cannot load roslaunch file(s): "+str(se))
except roslaunch.depends.RoslaunchDepsException as e:
raise WtfException(str(e))
def _load_pkg(ctx, pkg):
"""
Utility for initializing WtfContext state
@raise WtfException: if context state cannot be initialized
"""
r = ctx.rospack
ctx.pkg = pkg
try:
ctx.pkgs = [pkg] + r.get_depends(pkg)
except rospkg.ResourceNotFound as e:
raise WtfException("Cannot find dependencies for package [%s]: missing %s"%(pkg, e))
try:
ctx.pkg_dir = r.get_path(pkg)
ctx.manifest_file = os.path.join(ctx.pkg_dir, 'manifest.xml')
ctx.manifest = r.get_manifest(pkg)
except rospkg.ResourceNotFound:
raise WtfException("Cannot locate manifest file for package [%s]"%pkg)
except rospkg.InvalidManifest as e:
raise WtfException("Package [%s] has an invalid manifest: %s"%(pkg, e))
def _load_stack(ctx, stack):
"""
Utility for initializing WtfContext state
@raise WtfException: if context state cannot be initialized
"""
r = ctx.rosstack
ctx.stack = stack
try:
ctx.stacks = [stack] + r.get_depends(stack, implicit=True)
except rospkg.ResourceNotFound as e:
raise WtfException("Cannot load dependencies of stack [%s]: %s"%(stack, e))
try:
ctx.stack_dir = r.get_path(stack)
except rospkg.ResourceNotFound:
raise WtfException("[%s] appears to be a stack, but it's not on your ROS_PACKAGE_PATH"%stack)
def _load_env(ctx, env):
"""
Utility for initializing WtfContext state
@raise WtfException: if context state cannot be initialized
"""
ctx.env = env
try:
ctx.ros_root = env[rospkg.environment.ROS_ROOT]
except KeyError:
raise WtfException("ROS_ROOT is not set")
ctx.ros_package_path = env.get(rospkg.environment.ROS_PACKAGE_PATH, None)
ctx.pythonpath = env.get('PYTHONPATH', None)
ctx.ros_master_uri = env.get(rosgraph.ROS_MASTER_URI, None)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/network.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id: environment.py 4428 2009-05-05 05:48:36Z jfaustwg $
import os
import socket
import stat
import string
import sys
import rosgraph
import rosgraph.network
from roswtf.rules import warning_rule, error_rule
# #1220
def ip_check(ctx):
# best we can do is compare roslib's routine against socket resolution and make sure they agree
local_addrs = rosgraph.network.get_local_addresses()
resolved_ips = [host[4][0] for host in socket.getaddrinfo(socket.gethostname(), 0, 0, 0, socket.SOL_TCP)]
global_ips = [ ip for ip in resolved_ips if not ip.startswith('127.') and not ip == '::1']
remote_ips = list(set(global_ips) - set(local_addrs))
if remote_ips:
retval = "Local hostname [%s] resolves to [%s], which does not appear to be a local IP address %s." % (socket.gethostname(), ','.join(remote_ips), str(local_addrs))
# IPv6 support % to denote zone/scope ids. The value is expanded
# in other functions, this is why we are using replace command in
# the return. For more info https://github.com/ros/ros_comm/pull/598
return retval.replace('%', '%%')
# suggestion by mquigley based on laptop dhcp issues
def ros_hostname_check(ctx):
"""Make sure that ROS_HOSTNAME resolves to a local IP address"""
if not rosgraph.ROS_HOSTNAME in ctx.env:
return
hostname = ctx.env[rosgraph.ROS_HOSTNAME]
try:
resolved_ips = [host[4][0] for host in socket.getaddrinfo(hostname, 0, 0, 0, socket.SOL_TCP)]
except socket.gaierror:
return "ROS_HOSTNAME [%s] cannot be resolved to an IP address"%(hostname)
# best we can do is compare roslib's routine against socket resolution and make sure they agree
local_addrs = rosgraph.network.get_local_addresses()
remote_ips = list(set(resolved_ips) - set(local_addrs))
if remote_ips:
return "ROS_HOSTNAME [%s] resolves to [%s], which does not appear to be a local IP address %s."%(hostname, ','.join(remote_ips), str(local_addrs))
def ros_ip_check(ctx):
"""Make sure that ROS_IP is a local IP address"""
if not rosgraph.ROS_IP in ctx.env:
return
ip = ctx.env[rosgraph.ROS_IP]
# best we can do is compare roslib's routine against socket resolution and make sure they agree
addrs = rosgraph.network.get_local_addresses()
if ip not in addrs:
return "ROS_IP [%s] does not appear to be a local IP address %s."%(ip, str(addrs))
# Error/Warning Rules
warnings = [
(ros_hostname_check,
"ROS_HOSTNAME may be incorrect: "),
(ros_ip_check,
"ROS_IP may be incorrect: "),
]
errors = [
(ip_check,
"Local network configuration is invalid: "),
]
def wtf_check(ctx):
for r in warnings:
warning_rule(r, r[0](ctx), ctx)
for r in errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/roslaunchwtf.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
import os
import itertools
import socket
import stat
import sys
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
from os.path import isfile, isdir
import roslib.packages
import roslaunch
import roslaunch.netapi
from roswtf.environment import paths, is_executable
from roswtf.rules import warning_rule, error_rule
## check if node is cannot be located in package
def roslaunch_missing_node_check(ctx):
nodes = []
for filename, rldeps in ctx.launch_file_deps.items():
nodes.extend(rldeps.nodes)
errors = []
for pkg, node_type in nodes:
paths = roslib.packages.find_node(pkg, node_type)
if not paths:
errors.append("node [%s] in package [%s]"%(node_type, pkg))
return errors
## check if two nodes with same name in package
def roslaunch_duplicate_node_check(ctx):
nodes = []
for filename, rldeps in ctx.launch_file_deps.items():
nodes.extend(rldeps.nodes)
warnings = []
for pkg, node_type in nodes:
paths = roslib.packages.find_node(pkg, node_type)
if len(paths) > 1:
warnings.append("node [%s] in package [%s]\n"%(node_type, pkg))
return warnings
def pycrypto_check(ctx):
try:
import Crypto
except ImportError as e:
return True
def paramiko_check(ctx):
try:
import paramiko
except ImportError as e:
return True
def paramiko_system_keys(ctx):
try:
import paramiko
ssh = paramiko.SSHClient()
try:
ssh.load_system_host_keys() #default location
except:
return True
except: pass
def paramiko_ssh(ctx, address, port, username, password):
try:
import paramiko
ssh = paramiko.SSHClient()
import roslaunch.remoteprocess
err_msg = roslaunch.remoteprocess.ssh_check_known_hosts(ssh, address, port, username=username)
if err_msg:
return err_msg
if not password: #use SSH agent
ssh.connect(address, port, username)
else: #use SSH with login/pass
ssh.connect(address, port, username, password)
except paramiko.BadHostKeyException:
return "Unable to verify host key for [%s:%s]"%(address, port)
except paramiko.AuthenticationException:
return "Authentication to [%s:%s] failed"%(address, port)
except paramiko.SSHException as e:
return "[%s:%s]: %s"%(address, port, e)
except ImportError:
pass
def _load_roslaunch_config(ctx):
config = roslaunch.ROSLaunchConfig()
loader = roslaunch.XmlLoader()
# TODO load roscore
for launch_file in ctx.launch_files:
loader.load(launch_file, config, verbose=False)
try:
config.assign_machines()
except roslaunch.RLException as e:
return config, []
machines = []
for n in itertools.chain(config.nodes, config.tests):
if n.machine not in machines:
machines.append(n.machine)
return config, machines
def roslaunch_load_check(ctx):
config = roslaunch.ROSLaunchConfig()
loader = roslaunch.XmlLoader()
# TODO load roscore
for launch_file in ctx.launch_files:
loader.load(launch_file, config, verbose=False)
try:
config.assign_machines()
except roslaunch.RLException as e:
return str(e)
def roslaunch_machine_name_check(ctx):
config, machines = _load_roslaunch_config(ctx)
bad = []
for m in machines:
try:
#TODO IPV6: only check for IPv6 when IPv6 is enabled
socket.getaddrinfo(m.address, 0, 0, 0, socket.SOL_TCP)
except socket.gaierror:
bad.append(m.address)
return ''.join([' * %s\n'%b for b in bad])
def roslaunch_ssh_check(ctx):
import roslaunch.core
if not ctx.launch_files:
return # not relevant
config, machines = _load_roslaunch_config(ctx)
err_msgs = []
for m in machines:
socket.setdefaulttimeout(3.)
# only check if the machine requires ssh to connect
if not roslaunch.core.is_machine_local(m):
err_msg = paramiko_ssh(ctx, m.address, m.ssh_port, m.user, m.password)
if err_msg:
err_msgs.append(err_msg)
return err_msgs
def roslaunch_missing_pkgs_check(ctx):
# rospack depends does not return depends that it cannot find, so
# we have to manually determine this
config, machines = _load_roslaunch_config(ctx)
missing = []
for n in config.nodes:
pkg = n.package
try:
roslib.packages.get_pkg_dir(pkg, required=True)
except:
missing.append(pkg)
return missing
def roslaunch_config_errors(ctx):
config, machines = _load_roslaunch_config(ctx)
return config.config_errors
def roslaunch_missing_deps_check(ctx):
missing = []
for pkg, miss in ctx.launch_file_missing_deps.items():
if miss:
missing.append("%s/manifest.xml: %s"%(pkg, ', '.join(miss)))
return missing
def roslaunch_respawn_check(ctx):
respawn = []
for uri in ctx.roslaunch_uris:
try:
r = ServerProxy(uri)
code, msg, val = r.list_processes()
active, _ = val
respawn.extend([a for a in active if a[1] > 1])
#TODO: children processes
#code, msg, val = r.list_children()
except:
pass # error for another rule
return ["%s (%s)"%(a[0], a[1]) for a in respawn]
def roslaunch_uris_check(ctx):
# check for any roslaunch processes that cannot be contacted
bad = []
# uris only contains the parent launches
for uri in ctx.roslaunch_uris:
try:
r = ServerProxy(uri)
code, msg, val = r.list_children()
# check the children launches
if code == 1:
for child_uri in val:
try:
r = ServerProxy(uri)
code, msg, val = r.get_pid()
except:
bad.append(child_uri)
except:
bad.append(uri)
return bad
def roslaunch_dead_check(ctx):
dead = []
for uri in ctx.roslaunch_uris:
try:
r = ServerProxy(uri)
code, msg, val = r.list_processes()
_, dead_list = val
dead.extend([d[0] for d in dead_list])
#TODO: children processes
#code, msg, val = r.list_children()
except:
pass # error for another rule
return dead
online_roslaunch_warnings = [
(roslaunch_respawn_check,"These nodes have respawned at least once:"),
(roslaunch_dead_check,"These nodes have died:"),
# disabling for now as roslaunches don't do cleanup
#(roslaunch_uris_check,"These roslaunch processes can no longer be contacted and may have exited:"),
]
online_roslaunch_errors = [
(roslaunch_ssh_check,"SSH failures:"),
]
static_roslaunch_warnings = [
(roslaunch_duplicate_node_check, "Multiple nodes of same name in packages:"),
(pycrypto_check, "pycrypto is not installed"),
(paramiko_check, "paramiko is not installed"),
(paramiko_system_keys, "cannot load SSH host keys -- your known_hosts file may be corrupt") ,
(roslaunch_config_errors, "Loading your launch files reported the following configuration errors:"),
]
static_roslaunch_errors = [
# Disabling, because we've removed package dependencies from manifests.
#(roslaunch_missing_deps_check,
# "Package %(pkg)s is missing roslaunch dependencies.\nPlease add the following tags to %(pkg)s/manifest.xml:"),
(roslaunch_missing_pkgs_check,
"Cannot find the following required packages:"),
(roslaunch_missing_node_check, "Several nodes in your launch file could not be located. These are either typed incorrectly or need to be built:"),
(roslaunch_machine_name_check,"Cannot resolve the following hostnames:"),
(roslaunch_load_check, "roslaunch load failed"),
]
def wtf_check_static(ctx):
if not ctx.launch_files:
return
#NOTE: roslaunch files are already loaded separately into context
#TODO: check each machine name
#TODO: bidirectional ping for each machine
for r in static_roslaunch_warnings:
warning_rule(r, r[0](ctx), ctx)
for r in static_roslaunch_errors:
error_rule(r, r[0](ctx), ctx)
def _load_online_ctx(ctx):
ctx.roslaunch_uris = roslaunch.netapi.get_roslaunch_uris()
def wtf_check_online(ctx):
_load_online_ctx(ctx)
for r in online_roslaunch_warnings:
warning_rule(r, r[0](ctx), ctx)
for r in online_roslaunch_errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/environment.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
"""
Rules for checking ROS environment state.
"""
import os
import socket
import stat
import string
import sys
from os.path import isdir, isfile
from roswtf.rules import warning_rule, error_rule
#TODO: unit tests
def paths(path):
"""
@return: paths contained in path variable. path must conform to OS
conventions for path separation (i.e. colon-separated on Unix)
@rtype: [str]
"""
if path:
return path.split(os.pathsep)
return []
def is_executable(path):
"""
@return: True if path has executable permissions
@rtype: bool
"""
mode = os.stat(path)[stat.ST_MODE]
return mode & (stat.S_IXUSR|stat.S_IXGRP|stat.S_IXOTH)
try:
from urllib.parse import urlparse #Python 3
except ImportError:
from urlparse import urlparse #Python 2
def invalid_url(url):
"""
@return: error message if \a url is not a valid url. \a url is
allowed to be empty as that check is considered separately.
@rtype: str
"""
if not url:
return #caught by different rule
p = urlparse(url)
if p[0] != 'http':
return "protocol is not 'http'"
if not p[1]:
return "address is missing"
if not ':' in p[1]:
return "port number is missing"
try:
splits = p[1].split(':')
if len(splits) != 2:
return "invalid address string [%s]"%p[1]
int(splits[1])
except ValueError:
return "port number [%s] is invalid"%(splits[1])
# Error-checking functions for more advanced checks
def ros_root_check(ctx, ros_root=None):
"""
@param ros_root: override ctx, useful for when ctx is not created yet
@type ros_root: str
"""
if ros_root is not None:
path = ros_root
else:
path = ctx.ros_root
if os.path.basename(os.path.normpath(path)) not in ['ros', 'rosbuild']:
return "ROS_ROOT [%s] must end in directory named 'ros'"%path
def _writable_dir_check(ctx, path, name):
"""
If path is not None, validate that it is a writable directory
"""
if path is None:
return
if isfile(path):
return "%s [%s] must point to a directory, not a file"%(name, path)
if not os.access(path, os.W_OK):
return "%s [%s] is not writable"%(name, path)
def ros_home_check(ctx):
return _writable_dir_check(ctx, ctx.env.get('ROS_HOME', None), 'ROS_HOME')
def ros_log_dir_check(ctx):
return _writable_dir_check(ctx, ctx.env.get('ROS_LOG_DIR', None), 'ROS_LOG_DIR')
def ros_test_results_dir_check(ctx):
return _writable_dir_check(ctx, ctx.env.get('ROS_TEST_RESULTS_DIR', None), 'ROS_TEST_RESULTS_DIR')
def pythonpath_check(ctx):
# used to have a lot more checks here, but trying to phase out need for roslib on custom PYTHONPATH
path = ctx.pythonpath
roslib_count = len(set([p for p in paths(path) if 'roslib' in p]))
if roslib_count > 1:
return "Multiple roslib directories in PYTHONPATH (there should only be one)"
def rosconsole_config_file_check(ctx):
if 'ROSCONSOLE_CONFIG_FILE' in ctx.env:
return not isfile(ctx.env['ROSCONSOLE_CONFIG_FILE'])
def path_check(ctx):
# rosdeb setup can clobber local ros stuff, so try and detect this
path = ctx.env['PATH']
idx = path.find('/usr/bin')
if idx < 0:
return
if os.path.exists('/usr/lib/ros/'):
rr_idx = path.find(ctx.ros_root)
if rr_idx > -1 and rr_idx > idx:
return True
def ros_master_uri_hostname(ctx):
uri = ctx.ros_master_uri
parsed = urlparse(uri)
p = urlparse(uri)
if not p[1]:
return #caught by different rule
if not ':' in p[1]:
return #caught by different rule
try:
splits = p[1].split(':')
if len(splits) != 2:
return #caught by different rule
#TODO IPV6: only check for IPv6 when IPv6 is enabled
socket.getaddrinfo(splits[0], 0, 0, 0, socket.SOL_TCP)
except socket.gaierror:
return "Unknown host %s"%splits[0]
# Error/Warning Rules
environment_warnings = [
(path_check,
"PATH has /usr/bin set before ROS_ROOT/bin, which can cause problems as there is system install of ROS on this machine. You may wish to put ROS_ROOT/bin first"),
(lambda ctx: ctx.ros_package_path is None,
"ROS_PACKAGE_PATH is not set. This is not required, but is unusual"),
(lambda ctx: len(paths(ctx.ros_package_path)) == 0,
"ROS_PACKAGE_PATH is empty. This is not required, but is unusual"),
(lambda ctx: not ctx.ros_master_uri,
"ROS_MASTER_URI is empty. This is not required, but is unusual"),
(ros_master_uri_hostname,
"Cannot resolve hostname in ROS_MASTER_URI [%(ros_master_uri)s]"),
(rosconsole_config_file_check,
"ROS_CONSOLE_CONFIG_FILE does not point to an existing file"),
]
environment_errors = [
# ROS_ROOT
(lambda ctx: not isdir(ctx.ros_root),
"ROS_ROOT [%(ros_root)s] does not point to a directory"),
(ros_root_check,
"ROS_ROOT is invalid: "),
# ROS_PACKAGE_PATH
(lambda ctx: [d for d in paths(ctx.ros_package_path) if d and isfile(d)],
"Path(s) in ROS_PACKAGE_PATH [%(ros_package_path)s] points to a file instead of a directory: "),
(lambda ctx: [d for d in paths(ctx.ros_package_path) if d and not isdir(d) and not (os.path.basename(d) == 'stacks' and os.path.exists(os.path.join(os.path.dirname(d), '.catkin')))],
"Not all paths in ROS_PACKAGE_PATH [%(ros_package_path)s] point to an existing directory: "),
# PYTHONPATH
(lambda ctx: [d for d in paths(ctx.pythonpath) if d and not isdir(d)],
"Not all paths in PYTHONPATH [%(pythonpath)s] point to a directory: "),
(pythonpath_check,
"PYTHONPATH [%(pythonpath)s] is invalid: "),
# ROS_HOME, ROS_LOG_DIR, ROS_TEST_RESULTS_DIR
(ros_home_check, "ROS_HOME is invalid: "),
(ros_log_dir_check, "ROS_LOG_DIR is invalid: "),
(ros_test_results_dir_check, "ROS_TEST_RESULTS_DIR is invalid: "),
(lambda ctx: invalid_url(ctx.ros_master_uri),
"ROS_MASTER_URI [%(ros_master_uri)s] is not a valid URL: "),
]
def wtf_check_environment(ctx):
#TODO: check ROS_BOOST_ROOT
for r in environment_warnings:
warning_rule(r, r[0](ctx), ctx)
for r in environment_errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src | apollo_public_repos/apollo-platform/ros/ros_comm/roswtf/src/roswtf/stacks.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id: packages.py 6258 2009-09-22 22:08:20Z kwc $
import os
import time
from roswtf.environment import paths, is_executable
from roswtf.rules import warning_rule, error_rule
import rospkg
_packages_of_cache = {}
def _packages_of(rosstack, d):
if d in _packages_of_cache:
return _packages_of_cache[d]
else:
_packages_of_cache[d] = pkgs = rosstack.packages_of(d)
return pkgs
def manifest_depends(ctx):
# This rule should probably be cache optimized
errors = []
rospack = rospkg.RosPack()
rosstack = rospkg.RosStack()
stack_list = rosstack.list()
#print stack_list
for s in ctx.stacks:
try:
s_deps = []
s_pkgs = _packages_of(rosstack, s)
for p in s_pkgs:
s_deps.extend(rospack.get_depends(p, implicit=False))
m = rosstack.get_manifest(s)
m_file = os.path.join(rosstack.get_path(s), 'stack.xml')
for d in m.depends:
if not d.name in stack_list:
errors.append("%s (%s does not exist)"%(m_file, d))
elif d.name in ['ros', 'ros_comm']:
# ros dependency always exists. ros_comm
# dependency has implicit connections (msggen), so
# we ignore.
continue
else:
pkgs = _packages_of(rosstack, d.name)
# check no longer works due to rosdeps chains
#if not [p for p in pkgs if p in s_deps]:
# errors.append("%s (%s appears to be an unnecessary depend)"%(m_file, d))
except rospkg.ResourceNotFound:
# report with a different rule
pass
return errors
warnings = [
(manifest_depends, "The following stack.xml file list invalid dependencies:"),
]
errors = [
]
def wtf_check(ctx):
# no package in context to verify
if not ctx.stacks:
return
for r in warnings:
warning_rule(r, r[0](ctx), ctx)
for r in errors:
error_rule(r, r[0](ctx), ctx)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/xmlrpcpp/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(xmlrpcpp)
if(NOT WIN32)
set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra")
endif()
find_package(catkin REQUIRED COMPONENTS cpp_common)
catkin_package(
INCLUDE_DIRS include
LIBRARIES xmlrpcpp
CATKIN_DEPENDS cpp_common
)
include_directories(include ${catkin_INCLUDE_DIRS})
link_directories(${catkin_LIBRARY_DIRS})
if(WIN32)
add_definitions(-D_WINDOWS)
endif()
add_library(xmlrpcpp
src/XmlRpcClient.cpp
src/XmlRpcDispatch.cpp
src/XmlRpcServer.cpp
src/XmlRpcServerConnection.cpp
src/XmlRpcServerMethod.cpp
src/XmlRpcSocket.cpp
src/XmlRpcSource.cpp
src/XmlRpcUtil.cpp
src/XmlRpcValue.cpp
)
if(WIN32)
target_link_libraries(xmlrpcpp ws2_32)
endif()
# FIXME the headers should be in a package-specific subfolder but can not be for backward compatibility
install(DIRECTORY include/
DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h")
install(TARGETS xmlrpcpp
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.