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/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/rosout_appender.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 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 ROSCPP_ROSOUT_APPENDER_H #define ROSCPP_ROSOUT_APPENDER_H #include <ros/message_forward.h> #include "common.h" #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <boost/thread.hpp> namespace rosgraph_msgs { ROS_DECLARE_MESSAGE(Log); } namespace ros { class Publication; typedef boost::shared_ptr<Publication> PublicationPtr; typedef boost::weak_ptr<Publication> PublicationWPtr; class ROSCPP_DECL ROSOutAppender : public ros::console::LogAppender { public: ROSOutAppender(); ~ROSOutAppender(); const std::string& getLastError() const; virtual void log(::ros::console::Level level, const char* str, const char* file, const char* function, int line); protected: void logThread(); std::string last_error_; typedef std::vector<rosgraph_msgs::LogPtr> V_Log; V_Log log_queue_; boost::mutex queue_mutex_; boost::condition_variable queue_condition_; bool shutting_down_; boost::thread publish_thread_; }; } // namespace ros #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/common.h.in
/* * 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. */ #ifndef ROSCPP_COMMON_H #define ROSCPP_COMMON_H #include <stdint.h> #include <assert.h> #include <stddef.h> #include <string> #include "ros/assert.h" #include "ros/forwards.h" #include "ros/serialized_message.h" #include <boost/shared_array.hpp> #define ROS_VERSION_MAJOR @roscpp_VERSION_MAJOR@ #define ROS_VERSION_MINOR @roscpp_VERSION_MINOR@ #define ROS_VERSION_PATCH @roscpp_VERSION_PATCH@ #define ROS_VERSION_COMBINED(major, minor, patch) (((major) << 20) | ((minor) << 10) | (patch)) #define ROS_VERSION ROS_VERSION_COMBINED(ROS_VERSION_MAJOR, ROS_VERSION_MINOR, ROS_VERSION_PATCH) #define ROS_VERSION_GE(major1, minor1, patch1, major2, minor2, patch2) (ROS_VERSION_COMBINED(major1, minor1, patch1) >= ROS_VERSION_COMBINED(major2, minor2, patch2)) #define ROS_VERSION_MINIMUM(major, minor, patch) ROS_VERSION_GE(ROS_VERSION_MAJOR, ROS_VERSION_MINOR, ROS_VERSION_PATCH, major, minor, patch) #include <ros/macros.h> // 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 roscpp_EXPORTS // we are building a shared lib/dll #define ROSCPP_DECL ROS_HELPER_EXPORT #else // we are using shared lib/dll #define ROSCPP_DECL ROS_HELPER_IMPORT #endif #else // ros is being built around static libraries #define ROSCPP_DECL #endif namespace ros { void disableAllSignalsInThisThread(); } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_server.h
/* * 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. */ #ifndef ROSCPP_SERVICE_HANDLE_H #define ROSCPP_SERVICE_HANDLE_H #include "ros/forwards.h" #include "common.h" namespace ros { /** * \brief Manages an service advertisement. * * A ServiceServer should always be created through a call to NodeHandle::advertiseService(), or copied from * one that was. Once all copies of a specific * ServiceServer go out of scope, the service associated with it will be unadvertised and the service callback * will stop being called. */ class ROSCPP_DECL ServiceServer { public: ServiceServer() {} ServiceServer(const ServiceServer& rhs); ~ServiceServer(); /** * \brief Unadvertise the service associated with this ServiceServer * * This method usually does not need to be explicitly called, as automatic shutdown happens when * all copies of this ServiceServer go out of scope * * This method overrides the automatic reference counted unadvertise, and immediately * unadvertises the service associated with this ServiceServer */ void shutdown(); std::string getService() const; operator void*() const { return (impl_ && impl_->isValid()) ? (void*)1 : (void*)0; } bool operator<(const ServiceServer& rhs) const { return impl_ < rhs.impl_; } bool operator==(const ServiceServer& rhs) const { return impl_ == rhs.impl_; } bool operator!=(const ServiceServer& rhs) const { return impl_ != rhs.impl_; } private: ServiceServer(const std::string& service, const NodeHandle& node_handle); class Impl { public: Impl(); ~Impl(); void unadvertise(); bool isValid() const; std::string service_; NodeHandlePtr node_handle_; bool unadvertised_; }; typedef boost::shared_ptr<Impl> ImplPtr; typedef boost::weak_ptr<Impl> ImplWPtr; ImplPtr impl_; friend class NodeHandle; friend class NodeHandleBackingCollection; }; typedef std::vector<ServiceServer> V_ServiceServer; } #endif // ROSCPP_SERVICE_HANDLE_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/message.h
/* * 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. */ #ifndef ROSCPP_MESSAGE_H #define ROSCPP_MESSAGE_H // #warning You should not be using this file #include "ros/macros.h" #include "ros/assert.h" #include <string> #include <string.h> #include <boost/shared_ptr.hpp> #include <boost/array.hpp> #include <stdint.h> #define ROSCPP_MESSAGE_HAS_DEFINITION namespace ros { typedef std::map<std::string, std::string> M_string; /** * \deprecated This base-class is deprecated in favor of a template-based serialization and traits system */ #if 0 class Message { public: typedef boost::shared_ptr<Message> Ptr; typedef boost::shared_ptr<Message const> ConstPtr; Message() { } virtual ~Message() { } virtual const std::string __getDataType() const = 0; virtual const std::string __getMD5Sum() const = 0; virtual const std::string __getMessageDefinition() const = 0; inline static std::string __s_getDataType() { ROS_BREAK(); return std::string(""); } inline static std::string __s_getMD5Sum() { ROS_BREAK(); return std::string(""); } inline static std::string __s_getMessageDefinition() { ROS_BREAK(); return std::string(""); } virtual uint32_t serializationLength() const = 0; virtual uint8_t *serialize(uint8_t *write_ptr, uint32_t seq) const = 0; virtual uint8_t *deserialize(uint8_t *read_ptr) = 0; uint32_t __serialized_length; }; typedef boost::shared_ptr<Message> MessagePtr; typedef boost::shared_ptr<Message const> MessageConstPtr; #endif #define SROS_SERIALIZE_PRIMITIVE(ptr, data) { memcpy(ptr, &data, sizeof(data)); ptr += sizeof(data); } #define SROS_SERIALIZE_BUFFER(ptr, data, data_size) { if (data_size > 0) { memcpy(ptr, data, data_size); ptr += data_size; } } #define SROS_DESERIALIZE_PRIMITIVE(ptr, data) { memcpy(&data, ptr, sizeof(data)); ptr += sizeof(data); } #define SROS_DESERIALIZE_BUFFER(ptr, data, data_size) { if (data_size > 0) { memcpy(data, ptr, data_size); ptr += data_size; } } } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/publisher.h
/* * 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. */ #ifndef ROSCPP_PUBLISHER_HANDLE_H #define ROSCPP_PUBLISHER_HANDLE_H #include "ros/forwards.h" #include "ros/common.h" #include "ros/message.h" #include "ros/serialization.h" #include <boost/bind.hpp> #include <boost/thread/mutex.hpp> #include "roscpp/SharedMemoryHeader.h" #include "sharedmem_transport/sharedmem_publisher_impl.h" #include "sharedmem_transport/sharedmem_util.h" #include "ros/publication.h" namespace ros { /** * \brief Manages an advertisement on a specific topic. * * A Publisher should always be created through a call to NodeHandle::advertise(), or copied from one * that was. Once all copies of a specific * Publisher go out of scope, any subscriber status callbacks associated with that handle will stop * being called. Once all Publishers for a given topic go out of scope the topic will be unadvertised. */ class ROSCPP_DECL Publisher { public: Publisher() {} Publisher(const Publisher& rhs); ~Publisher(); /** * \brief Publish a message on the topic associated with this Publisher. * * This version of publish will allow fast intra-process message-passing in the future, * so you may not mutate the message after it has been passed in here (since it will be * passed directly into a callback function) * */ template <typename M> void publish(const boost::shared_ptr<M>& message) const { using namespace serialization; if (!impl_) { ROS_ASSERT_MSG(false, "Call to publish() on an invalid Publisher"); return; } if (!impl_->isValid()) { ROS_ASSERT_MSG(false, "Call to publish() on an invalid Publisher (topic [%s])", impl_->topic_.c_str()); return; } ROS_ASSERT_MSG(impl_->md5sum_ == "*" || std::string(mt::md5sum<M>(*message)) == "*" || impl_->md5sum_ == mt::md5sum<M>(*message), "Trying to publish message of type [%s/%s] on a publisher with type [%s/%s]", mt::datatype<M>(*message), mt::md5sum<M>(*message), impl_->datatype_.c_str(), impl_->md5sum_.c_str()); SerializedMessage m; m.type_info = &typeid(M); m.message = message; publish(boost::bind(serializeMessage<M>, boost::ref(*message)), m); } /** * \brief Publish a message on the topic associated with this Publisher. */ template <typename M> void publish(const M& message) const { using namespace serialization; namespace mt = ros::message_traits; if (!impl_) { ROS_ASSERT_MSG(false, "Call to publish() on an invalid Publisher"); return; } if (!impl_->isValid()) { ROS_ASSERT_MSG(false, "Call to publish() on an invalid Publisher (topic [%s])", impl_->topic_.c_str()); return; } ROS_ASSERT_MSG(impl_->md5sum_ == "*" || std::string(mt::md5sum<M>(message)) == "*" || impl_->md5sum_ == mt::md5sum<M>(message), "Trying to publish message of type [%s/%s] on a publisher with type [%s/%s]", mt::datatype<M>(message), mt::md5sum<M>(message), impl_->datatype_.c_str(), impl_->md5sum_.c_str()); SerializedMessage m; publish(boost::bind(serializeMessage<M>, boost::ref(message)), m); } /** * \brief Shutdown the advertisement associated with this Publisher * * This method usually does not need to be explicitly called, as automatic shutdown happens when * all copies of this Publisher go out of scope * * This method overrides the automatic reference counted unadvertise, and does so immediately. * \note Note that if multiple advertisements were made through NodeHandle::advertise(), this will * only remove the one associated with this Publisher */ void shutdown(); /** * \brief Returns the topic that this Publisher will publish on. */ std::string getTopic() const; /** * \brief Returns the number of subscribers that are currently connected to this Publisher */ uint32_t getNumSubscribers() const; /** * \brief Returns whether or not this topic is latched */ bool isLatched() const; operator void*() const { return (impl_ && impl_->isValid()) ? (void*)1 : (void*)0; } bool operator<(const Publisher& rhs) const { return impl_ < rhs.impl_; } bool operator==(const Publisher& rhs) const { return impl_ == rhs.impl_; } bool operator!=(const Publisher& rhs) const { return impl_ != rhs.impl_; } private: Publisher(const std::string& topic, const std::string& md5sum, const std::string& datatype, const std::string& message_definition, const NodeHandle& node_handle, const SubscriberCallbacksPtr& callbacks, const uint32_t& queue_size); void publishShm( const boost::function<SerializedMessage(void)>& serfunc, SerializedMessage& message, std::string datatype, std::string md5sum, std::string msg_def) const ; void publish(const boost::function<SerializedMessage(void)>& serfunc, SerializedMessage& m) const; void incrementSequence() const; class ROSCPP_DECL Impl { public: Impl(); ~Impl(); void unadvertise(); bool isValid() const; std::string topic_; uint32_t queue_size_; uint64_t alloc_size_; std::string md5sum_; std::string datatype_; std::string message_definition_; NodeHandlePtr node_handle_; SubscriberCallbacksPtr callbacks_; bool unadvertised_; sharedmem_transport::SharedMemoryPublisherImpl shared_impl_; bool first_run_; enum TransportType default_transport_; }; typedef boost::shared_ptr<Impl> ImplPtr; typedef boost::weak_ptr<Impl> ImplWPtr; ImplPtr impl_; friend class NodeHandle; friend class NodeHandleBackingCollection; }; typedef std::vector<Publisher> V_Publisher; } #endif // ROSCPP_PUBLISHER_HANDLE_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/config_comm.h
/* * 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. */ #ifndef CONFIG_COMM_H #define CONFIG_COMM_H #include <iostream> #include <fstream> #include <vector> #include <set> namespace ros { struct ConfigComm { std::set<std::string> topic_white_list; int transport_mode; }; } #endif // CONFIG_COMM_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/subscription_callback_helper.h
/* * 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. */ #ifndef ROSCPP_SUBSCRIPTION_CALLBACK_HELPER_H #define ROSCPP_SUBSCRIPTION_CALLBACK_HELPER_H #include <typeinfo> #include "common.h" #include "ros/forwards.h" #include "ros/parameter_adapter.h" #include "ros/message_traits.h" #include "ros/builtin_message_traits.h" #include "ros/serialization.h" #include "ros/message_event.h" #include <ros/static_assert.h> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/utility/enable_if.hpp> #include <boost/make_shared.hpp> #include "roscpp/SharedMemoryHeader.h" #include "boost/bind.hpp" #include "ros/names.h" namespace ros { struct SubscriptionCallbackHelperDeserializeParams { uint8_t* buffer; uint32_t length; boost::shared_ptr<M_string> connection_header; }; struct ROSCPP_DECL SubscriptionCallbackHelperCallParams { MessageEvent<void const> event; }; /** * \brief Abstract base class used by subscriptions to deal with concrete message types through a common * interface. This is one part of the roscpp API that is \b not fully stable, so overloading this class * is not recommended. */ class ROSCPP_DECL SubscriptionCallbackHelper { public: virtual ~SubscriptionCallbackHelper() {} virtual VoidConstPtr deserialize(const SubscriptionCallbackHelperDeserializeParams&) = 0; virtual void call(SubscriptionCallbackHelperCallParams& params) = 0; virtual const std::type_info& getTypeInfo() = 0; virtual bool isConst() = 0; virtual bool hasHeader() = 0; }; typedef boost::shared_ptr<SubscriptionCallbackHelper> SubscriptionCallbackHelperPtr; /** * \brief Concrete generic implementation of * SubscriptionCallbackHelper for any normal message type. Use * directly with care, this is mostly for internal use. */ template<typename P, typename Enabled = void> class SubscriptionCallbackHelperT : public SubscriptionCallbackHelper { public: typedef ParameterAdapter<P> Adapter; typedef typename ParameterAdapter<P>::Message NonConstType; typedef typename ParameterAdapter<P>::Event Event; typedef typename boost::add_const<NonConstType>::type ConstType; typedef boost::shared_ptr<NonConstType> NonConstTypePtr; typedef boost::shared_ptr<ConstType> ConstTypePtr; static const bool is_const = ParameterAdapter<P>::is_const; typedef boost::function<void(typename Adapter::Parameter)> Callback; typedef boost::function<NonConstTypePtr()> CreateFunction; SubscriptionCallbackHelperT(const Callback& callback, const CreateFunction& create = DefaultMessageCreator<NonConstType>()) : callback_(callback) , create_(create) { } void setCreateFunction(const CreateFunction& create) { create_ = create; } virtual bool hasHeader() { return message_traits::hasHeader<typename ParameterAdapter<P>::Message>(); } virtual VoidConstPtr deserialize(const SubscriptionCallbackHelperDeserializeParams& params) { namespace ser = serialization; NonConstTypePtr msg = create_(); if (!msg) { ROS_DEBUG("Allocation failed for message of type [%s]", getTypeInfo().name()); return VoidConstPtr(); } ser::PreDeserializeParams<NonConstType> predes_params; predes_params.message = msg; predes_params.connection_header = params.connection_header; ser::PreDeserialize<NonConstType>::notify(predes_params); ser::IStream stream(params.buffer, params.length); ser::deserialize(stream, *msg); return VoidConstPtr(msg); } virtual void call(SubscriptionCallbackHelperCallParams& params) { Event event(params.event, create_); callback_(ParameterAdapter<P>::getParameter(event)); } virtual const std::type_info& getTypeInfo() { return typeid(NonConstType); } virtual bool isConst() { return ParameterAdapter<P>::is_const; } private: Callback callback_; CreateFunction create_; }; } #endif // ROSCPP_SUBSCRIPTION_CALLBACK_HELPER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/internal_timer_manager.h
/* * 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. */ #ifndef ROSCPP_INTERNAL_TIMER_MANAGER_H #define ROSCPP_INTERNAL_TIMER_MANAGER_H #include "forwards.h" #include <ros/time.h> #include "common.h" namespace ros { template<typename T, typename D, typename E> class TimerManager; typedef TimerManager<WallTime, WallDuration, WallTimerEvent> InternalTimerManager; typedef boost::shared_ptr<InternalTimerManager> InternalTimerManagerPtr; ROSCPP_DECL void initInternalTimerManager(); ROSCPP_DECL InternalTimerManagerPtr getInternalTimerManager(); } // namespace ros #endif // ROSCPP_INTERNAL_TIMER_MANAGER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/timer.h
/* * 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. */ #ifndef ROSCPP_TIMER_H #define ROSCPP_TIMER_H #include "common.h" #include "forwards.h" #include "timer_options.h" namespace ros { /** * \brief Manages a timer callback * * A Timer should always be created through a call to NodeHandle::createTimer(), or copied from one * that was. Once all copies of a specific * Timer go out of scope, the callback associated with that handle will stop * being called. */ class ROSCPP_DECL Timer { public: Timer() {} Timer(const Timer& rhs); ~Timer(); /** * \brief Start the timer. Does nothing if the timer is already started. */ void start(); /** * \brief Stop the timer. Once this call returns, no more callbacks will be called. Does * nothing if the timer is already stopped. */ void stop(); /** * \brief Returns whether or not the timer has any pending events to call. */ bool hasPending(); /** * \brief Set the period of this timer * \param reset Whether to reset the timer. If true, timer ignores elapsed time and next cb occurs at now()+period */ void setPeriod(const Duration& period, bool reset=true); bool isValid() { return impl_ && impl_->isValid(); } operator void*() { return isValid() ? (void*)1 : (void*)0; } bool operator<(const Timer& rhs) { return impl_ < rhs.impl_; } bool operator==(const Timer& rhs) { return impl_ == rhs.impl_; } bool operator!=(const Timer& rhs) { return impl_ != rhs.impl_; } private: Timer(const TimerOptions& ops); class Impl { public: Impl(); ~Impl(); bool isValid(); bool hasPending(); void setPeriod(const Duration& period, bool reset=true); void start(); void stop(); bool started_; int32_t timer_handle_; Duration period_; TimerCallback callback_; CallbackQueueInterface* callback_queue_; VoidConstWPtr tracked_object_; bool has_tracked_object_; bool oneshot_; }; typedef boost::shared_ptr<Impl> ImplPtr; typedef boost::weak_ptr<Impl> ImplWPtr; ImplPtr impl_; friend class NodeHandle; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/spinner.h
/* * 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. */ #ifndef ROSCPP_SPINNER_H #define ROSCPP_SPINNER_H #include "ros/types.h" #include "common.h" #include <boost/shared_ptr.hpp> namespace ros { class NodeHandle; class CallbackQueue; /** * \brief Abstract interface for classes which spin on a callback queue. */ class ROSCPP_DECL Spinner { public: virtual ~Spinner() {} /** * \brief Spin on a callback queue (defaults to the global one). Blocks until roscpp has been shutdown. */ virtual void spin(CallbackQueue* queue = 0) = 0; }; /** * \brief Spinner which runs in a single thread. */ class SingleThreadedSpinner : public Spinner { public: virtual void spin(CallbackQueue* queue = 0); }; /** * \brief Spinner which spins in multiple threads. */ class ROSCPP_DECL MultiThreadedSpinner : public Spinner { public: /** * \param thread_count Number of threads to use for calling callbacks. 0 will * automatically use however many hardware threads exist on your system. */ MultiThreadedSpinner(uint32_t thread_count = 0); virtual void spin(CallbackQueue* queue = 0); private: uint32_t thread_count_; }; class AsyncSpinnerImpl; typedef boost::shared_ptr<AsyncSpinnerImpl> AsyncSpinnerImplPtr; /** * \brief AsyncSpinner is a spinner that does not conform to the abstract Spinner interface. Instead, * it spins asynchronously when you call start(), and stops when either you call stop(), ros::shutdown() * is called, or its destructor is called * * AsyncSpinner is reference counted internally, so if you copy one it will continue spinning until all * copies have destructed (or stop() has been called on one of them) */ class ROSCPP_DECL AsyncSpinner { public: /** * \brief Simple constructor. Uses the global callback queue * \param thread_count The number of threads to use. A value of 0 means to use the number of processor cores */ AsyncSpinner(uint32_t thread_count); /** * \brief Constructor with custom callback queue * \param thread_count The number of threads to use. A value of 0 means to use the number of processor cores * \param queue The callback queue to operate on. A null value means to use the global queue */ AsyncSpinner(uint32_t thread_count, CallbackQueue* queue); /** * \brief Check if the spinner can be started. A spinner can't be started if * another spinner is already running. */ bool canStart(); /** * \brief Start this spinner spinning asynchronously */ void start(); /** * \brief Stop this spinner from running */ void stop(); private: AsyncSpinnerImplPtr impl_; }; } #endif // ROSCPP_SPIN_POLICY_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/broadcast_manager.h
/* * 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. */ #ifndef ROSCPP_BROADCAST_MANAGER_H #define ROSCPP_BROADCAST_MANAGER_H #define BOOST_SPIRIT_THREADSAFE // must define before include boost libs #include <condition_variable> #include <functional> #include <future> #include <queue> #include <memory> #include <mutex> #include <stdexcept> #include <string> #include <set> #include <thread> #include <vector> #include <chrono> #include <time.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "common.h" #include "XmlRpc.h" #include "ros/time.h" #include "ros/master.h" #include "ros/topic_manager.h" #include "ros/xmlrpc_manager.h" #include "discovery/participant.h" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #define REGISTRY(name, method) \ functions_[#name] = CallbackFunc([this] (const MsgInfo& result) \ {this->method##Callback(result);}); namespace ros { class BroadcastManager; typedef boost::property_tree::ptree MsgInfo; typedef std::set<std::string> PubInfo; typedef std::set<std::string> SubInfo; typedef std::function<void (const MsgInfo&)> CallbackFunc; typedef std::shared_ptr<BroadcastManager> BroadcastManagerPtr; struct TopicInfo { std::string type; std::string uri; }; struct ServiceInfo { std::string uri; bool is_owner; }; class ROSCPP_DECL BroadcastManager { public: BroadcastManager(); ~BroadcastManager(); static const BroadcastManagerPtr& instance(); void start(); void shutdown(); void registerPublisher(const std::string& topic, const std::string& datatype, const std::string& uri); void unregisterPublisher(const std::string& pub_name, const std::string& uri); void registerSubscriber(const std::string& topic, const std::string& type, const std::string& uri); void unregisterSubscriber(const std::string& sub_name, const std::string& uri); void registerService(const std::string& node_name, const std::string& srv_name, const std::string& uri_buf, const std::string& uri); void unregisterService(const std::string& service, const std::string& uri); bool lookupService(const std::string& srv_name, std::string& serv_uri, int timeout = 2000); PubInfo getPubs(const std::string& topic_name); SubInfo getSubs(const std::string& topic_name); void publisherUpdate(const std::string& topic_name); void getTopics(master::V_TopicInfo& topics); void getTopicTypes(master::V_TopicInfo& topics); void getNodes(V_string& nodes); void commonCallback(const std::string& result); private: //callbacks for broadcast msg void registerPublisherCallback(const MsgInfo& result); void unregisterPublisherCallback(const MsgInfo& result); void registerSubscriberCallback(const MsgInfo& result); void unregisterSubscriberCallback(const MsgInfo& result); void registerServiceCallback(const MsgInfo& result); void unregisterServiceCallback(const MsgInfo& result); void noneCallback(const MsgInfo& result) { (void)result; }; void registerNode(); void serviceUpdate(const std::string& name, const std::string& uri); MsgInfo generateMessage(const std::string& request_type); MsgInfo generateMessage(const std::string& request_type, uint64_t timestamp); void sendMessage(const MsgInfo& msg); void sendMessage(const std::string& msg); bool shutting_down_; void initCallbacks(); bool isShuttingDown() { return shutting_down_; } TopicManagerPtr topic_manager_; XMLRPCManagerPtr xmlrpc_manager_; master::V_TopicInfo topic_cache_; std::map<std::string, PubInfo> pub_cache_; std::map<std::string, SubInfo> sub_cache_; std::map<std::string, ServiceInfo> service_cache_; std::map<std::string, TopicInfo> advertised_topics_; std::map<std::string, CallbackFunc> functions_; std::unique_ptr<Participant> part_; uint64_t node_timestamp_; const std::string NODE_NAME = "node_name"; const std::string TIMESTAMP = "timestamp"; const std::string XMLRPC_URI = "xmlrpc_uri"; const std::string REQUEST_TYPE = "request_type"; const std::string NODE_TIME = "node_time"; const std::string TOPIC_NAME = "topic_name"; const std::string TOPIC_TYPE = "topic_type"; const std::string TOPIC_URI = "topic_uri"; const std::string SERVICE_NAME = "service_name"; const std::string SERVICE_TYPE = "service_type"; const std::string SERVICE_URI = "service_uri"; }; } // namespace ros #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/param.h
/* * 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. */ #ifndef ROSCPP_PARAM_H #define ROSCPP_PARAM_H #include "forwards.h" #include "common.h" #include "XmlRpcValue.h" #include <vector> #include <map> namespace ros { /** * \brief Contains functions which allow you to query the parameter server */ namespace param { /** \brief Set an arbitrary XML/RPC value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param v The value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const XmlRpc::XmlRpcValue& v); /** \brief Set a string value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param s The value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::string& s); /** \brief Set a string value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param s The value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const char* s); /** \brief Set a double value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param d The value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, double d); /** \brief Set an integer value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param i The value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, int i); /** \brief Set a bool value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param b The value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, bool b); /** \brief Set a string vector value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param vec The vector value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::vector<std::string>& vec); /** \brief Set a double vector value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param vec The vector value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::vector<double>& vec); /** \brief Set a float vector value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param vec The vector value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::vector<float>& vec); /** \brief Set an integer vector value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param vec The vector value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::vector<int>& vec); /** \brief Set a bool vector value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param vec The vector value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::vector<bool>& vec); /** \brief Set a string->string map value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param map The map value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::map<std::string, std::string>& map); /** \brief Set a string->double map value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param map The map value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::map<std::string, double>& map); /** \brief Set a string->float map value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param map The map value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::map<std::string, float>& map); /** \brief Set a string->int map value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param map The map value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::map<std::string, int>& map); /** \brief Set a string->bool map value on the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param map The map value to be inserted. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL void set(const std::string& key, const std::map<std::string, bool>& map); /** \brief Get a string value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] s Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::string& s); /** \brief Get a double value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] d Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, double& d); /** \brief Get a float value from the parameter server (internally using the double value). * * \param key The key to be used in the parameter server's dictionary * \param[out] f Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, float& f); /** \brief Get an integer value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] i Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, int& i); /** \brief Get a boolean value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] b Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, bool& b); /** \brief Get an arbitrary XML/RPC value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] v Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, XmlRpc::XmlRpcValue& v); /** \brief Get a string value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] s Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::string& s); /** \brief Get a double value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] d Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, double& d); /** \brief Get a float value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] f Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, float& f); /** \brief Get an integer value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] i Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, int& i); /** \brief Get a boolean value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] b Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, bool& b); /** \brief Get an arbitrary XML/RPC value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] v Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, XmlRpc::XmlRpcValue& v); /** \brief Get a string vector value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::vector<std::string>& vec); /** \brief Get a double vector value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::vector<double>& vec); /** \brief Get a float vector value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::vector<float>& vec); /** \brief Get an int vector value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::vector<int>& vec); /** \brief Get a bool vector value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::vector<bool>& vec); /** \brief Get a string vector value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::vector<std::string>& vec); /** \brief Get a double vector value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::vector<double>& vec); /** \brief Get a float vector value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::vector<float>& vec); /** \brief Get an int vector value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::vector<int>& vec); /** \brief Get a bool vector value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] vec Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::vector<bool>& vec); /** \brief Get a string->string map value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::map<std::string, std::string>& map); /** \brief Get a string->double map value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::map<std::string, double>& map); /** \brief Get a string->float map value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::map<std::string, float>& map); /** \brief Get a string->int map value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::map<std::string, int>& map); /** \brief Get a string->bool map value from the parameter server. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool get(const std::string& key, std::map<std::string, bool>& map); /** \brief Get a string->string map value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::map<std::string, std::string>& map); /** \brief Get a string->double map value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::map<std::string, double>& map); /** \brief Get a string->float map value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::map<std::string, float>& map); /** \brief Get a string->int map value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::map<std::string, int>& map); /** \brief Get a string->bool map value from the parameter server, with local caching * * This function will cache parameters locally, and subscribe for updates from * the parameter server. Once the parameter is retrieved for the first time * no subsequent getCached() calls with the same key will query the master -- * they will instead look up in the local cache. * * \param key The key to be used in the parameter server's dictionary * \param[out] map Storage for the retrieved value. * * \return true if the parameter value was retrieved, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool getCached(const std::string& key, std::map<std::string, bool>& map); /** \brief Check whether a parameter exists on the parameter server. * * \param key The key to check. * * \return true if the parameter exists, false otherwise * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool has(const std::string& key); /** \brief Delete a parameter from the parameter server. * * \param key The key to delete. * * \return true if the deletion succeeded, false otherwise. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool del(const std::string& key); /** \brief Search up the tree for a parameter with a given key * * This function parameter server's searchParam feature to search up the tree for * a parameter. For example, if the parameter server has a parameter [/a/b] * and you specify the namespace [/a/c/d], searching for the parameter "b" will * yield [/a/b]. If [/a/c/d/b] existed, that parameter would be returned instead. * * \param ns The namespace to begin the search in * \param key the parameter to search for * \param [out] result the found value (if any) * * \return true if the parameter was found, false otherwise. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool search(const std::string& ns, const std::string& key, std::string& result); /** \brief Search up the tree for a parameter with a given key. This version defaults to starting in * the current node's name * * This function parameter server's searchParam feature to search up the tree for * a parameter. For example, if the parameter server has a parameter [/a/b] * and you specify the namespace [/a/c/d], searching for the parameter "b" will * yield [/a/b]. If [/a/c/d/b] existed, that parameter would be returned instead. * * \param key the parameter to search for * \param [out] result the found value (if any) * * \return true if the parameter was found, false otherwise. * \throws InvalidNameException if the key is not a valid graph resource name */ ROSCPP_DECL bool search(const std::string& key, std::string& result); /** * \brief Get the list of all the parameters in the server * \param keys The vector of all the keys * \return false if the process fails */ ROSCPP_DECL bool getParamNames(std::vector<std::string>& keys); /** \brief Assign value from parameter server, with default. * * This method tries to retrieve the indicated parameter value from the * parameter server, storing the result in param_val. If the value * cannot be retrieved from the server, default_val is used instead. * * \param param_name The key to be searched on the parameter server. * \param[out] param_val Storage for the retrieved value. * \param default_val Value to use if the server doesn't contain this * parameter. * \throws InvalidNameException if the key is not a valid graph resource name */ template<typename T> void param(const std::string& param_name, T& param_val, const T& default_val) { if (has(param_name)) { if (get(param_name, param_val)) { return; } } param_val = default_val; } /** * \brief Return value from parameter server, or default if unavailable. * * This method tries to retrieve the indicated parameter value from the * parameter server. If the parameter cannot be retrieved, \c default_val * is returned instead. * * \param param_name The key to be searched on the parameter server. * * \param default_val Value to return if the server doesn't contain this * parameter. * * \return The parameter value retrieved from the parameter server, or * \c default_val if unavailable. * * \throws InvalidNameException If the key is not a valid graph resource name. */ template<typename T> T param(const std::string& param_name, const T& default_val) { T param_val; param(param_name, param_val, default_val); return param_val; } } // namespace param } // namespace ros #endif // ROSCPP_PARAM_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/advertise_service_options.h
/* * 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. */ #ifndef ROSCPP_ADVERTISE_SERVICE_OPTIONS_H #define ROSCPP_ADVERTISE_SERVICE_OPTIONS_H #include "ros/forwards.h" #include "ros/service_callback_helper.h" #include "ros/service_traits.h" #include "ros/message_traits.h" #include "common.h" namespace ros { /** * \brief Encapsulates all options available for creating a ServiceServer */ struct ROSCPP_DECL AdvertiseServiceOptions { AdvertiseServiceOptions() : callback_queue(0) { } /** * \brief Templated convenience method for filling out md5sum/etc. based on the service request/response types * \param _service Service name to advertise on * \param _callback Callback to call when this service is called */ template<class MReq, class MRes> void init(const std::string& _service, const boost::function<bool(MReq&, MRes&)>& _callback) { namespace st = service_traits; namespace mt = message_traits; if (st::md5sum<MReq>() != st::md5sum<MRes>()) { ROS_FATAL("the request and response parameters to the server " "callback function must be autogenerated from the same " "server definition file (.srv). your advertise_servce " "call for %s appeared to use request/response types " "from different .srv files.", service.c_str()); ROS_BREAK(); } service = _service; md5sum = st::md5sum<MReq>(); datatype = st::datatype<MReq>(); req_datatype = mt::datatype<MReq>(); res_datatype = mt::datatype<MRes>(); helper = boost::make_shared<ServiceCallbackHelperT<ServiceSpec<MReq, MRes> > >(_callback); } /** * \brief Templated convenience method for filling out md5sum/etc. based on the service type * \param _service Service name to advertise on * \param _callback Callback to call when this service is called */ template<class Service> void init(const std::string& _service, const boost::function<bool(typename Service::Request&, typename Service::Response&)>& _callback) { namespace st = service_traits; namespace mt = message_traits; typedef typename Service::Request Request; typedef typename Service::Response Response; service = _service; md5sum = st::md5sum<Service>(); datatype = st::datatype<Service>(); req_datatype = mt::datatype<Request>(); res_datatype = mt::datatype<Response>(); helper = boost::make_shared<ServiceCallbackHelperT<ServiceSpec<Request, Response> > >(_callback); } /** * \brief Templated convenience method for filling out md5sum/etc. based on the service spec type * \param _service Service name to advertise on * \param _callback Callback to call when this service is called */ template<class Spec> void initBySpecType(const std::string& _service, const typename Spec::CallbackType& _callback) { namespace st = service_traits; namespace mt = message_traits; typedef typename Spec::RequestType Request; typedef typename Spec::ResponseType Response; service = _service; md5sum = st::md5sum<Request>(); datatype = st::datatype<Request>(); req_datatype = mt::datatype<Request>(); res_datatype = mt::datatype<Response>(); helper = boost::make_shared<ServiceCallbackHelperT<Spec> >(_callback); } std::string service; ///< Service name std::string md5sum; ///< MD5 of the service std::string datatype; ///< Datatype of the service std::string req_datatype; ///< Request message datatype std::string res_datatype; ///< Response message datatype ServiceCallbackHelperPtr helper; ///< Helper object used for creating messages and calling callbacks CallbackQueueInterface* callback_queue; ///< Queue to add callbacks to. If NULL, the global callback queue will be used /** * \brief An object whose destruction will prevent the callback associated with this service from being called * * A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object, * and if the reference count goes to 0 the subscriber callbacks will not get called. * * \note Note that setting this will cause a new reference to be added to the object before the * callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore * thread) that the callback is invoked from. */ VoidConstPtr tracked_object; /** * \brief Templated helper function for creating an AdvertiseServiceOptions with all of its options * \param service Service name to advertise on * \param callback The callback to invoke when the service is called * \param tracked_object The tracked object to use (see AdvertiseServiceOptions::tracked_object) * \param queue The callback queue to use (see AdvertiseServiceOptions::callback_queue) */ template<class Service> static AdvertiseServiceOptions create(const std::string& service, const boost::function<bool(typename Service::Request&, typename Service::Response&)>& callback, const VoidConstPtr& tracked_object, CallbackQueueInterface* queue) { AdvertiseServiceOptions ops; ops.init<typename Service::Request, typename Service::Response>(service, callback); ops.tracked_object = tracked_object; ops.callback_queue = queue; return ops; } }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/network.h
/* * 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. */ #ifndef ROSCPP_NETWORK_H #define ROSCPP_NETWORK_H #include "forwards.h" #include "common.h" namespace ros { /** * \brief internal */ namespace network { ROSCPP_DECL bool splitURI(const std::string& uri, std::string& host, uint32_t& port); ROSCPP_DECL const std::string& getHost(); ROSCPP_DECL uint16_t getTCPROSPort(); } // namespace network } // namespace ros #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/subscriber.h
/* * 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. */ #ifndef ROSCPP_SUBSCRIBER_HANDLE_H #define ROSCPP_SUBSCRIBER_HANDLE_H #include "common.h" #include "ros/forwards.h" #include "ros/subscription_callback_helper.h" namespace ros { /** * \brief Manages an subscription callback on a specific topic. * * A Subscriber should always be created through a call to NodeHandle::subscribe(), or copied from one * that was. Once all copies of a specific * Subscriber go out of scope, the subscription callback associated with that handle will stop * being called. Once all Subscriber for a given topic go out of scope the topic will be unsubscribed. */ class ROSCPP_DECL Subscriber { public: Subscriber() {} Subscriber(const Subscriber& rhs); ~Subscriber(); /** * \brief Unsubscribe the callback associated with this Subscriber * * This method usually does not need to be explicitly called, as automatic shutdown happens when * all copies of this Subscriber go out of scope * * This method overrides the automatic reference counted unsubscribe, and immediately * unsubscribes the callback associated with this Subscriber */ void shutdown(); std::string getTopic() const; /** * \brief Returns the number of publishers this subscriber is connected to */ uint32_t getNumPublishers() const; operator void*() const { return (impl_ && impl_->isValid()) ? (void*)1 : (void*)0; } bool operator<(const Subscriber& rhs) const { return impl_ < rhs.impl_; } bool operator==(const Subscriber& rhs) const { return impl_ == rhs.impl_; } bool operator!=(const Subscriber& rhs) const { return impl_ != rhs.impl_; } private: Subscriber(const std::string& topic, const NodeHandle& node_handle, const SubscriptionCallbackHelperPtr& helper); class Impl { public: Impl(); ~Impl(); void unsubscribe(); bool isValid() const; std::string topic_; NodeHandlePtr node_handle_; SubscriptionCallbackHelperPtr helper_; bool unsubscribed_; }; typedef boost::shared_ptr<Impl> ImplPtr; typedef boost::weak_ptr<Impl> ImplWPtr; ImplPtr impl_; friend class NodeHandle; friend class NodeHandleBackingCollection; }; typedef std::vector<Subscriber> V_Subscriber; } #endif // ROSCPP_PUBLISHER_HANDLE_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/names.h
/* * 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. */ #ifndef ROSCPP_NAMES_H #define ROSCPP_NAMES_H #include "forwards.h" #include "common.h" namespace ros { /** * \brief Contains functions which allow you to manipulate ROS names */ namespace names { /** * \brief Cleans a graph resource name: removes double slashes, trailing slash */ ROSCPP_DECL std::string clean(const std::string& name); /** * \brief Resolve a graph resource name into a fully qualified graph resource name * * See http://www.ros.org/wiki/Names for more details * * \param name Name to resolve * \param remap Whether or not to apply remappings to the name * \throws InvalidNameException if the name passed is not a valid graph resource name */ ROSCPP_DECL std::string resolve(const std::string& name, bool remap = true); /** * \brief Resolve a graph resource name into a fully qualified graph resource name * * See http://www.ros.org/wiki/Names for more details * * \param ns Namespace to use in resolution * \param name Name to resolve * \param remap Whether or not to apply remappings to the name * \throws InvalidNameException if the name passed is not a valid graph resource name */ ROSCPP_DECL std::string resolve(const std::string& ns, const std::string& name, bool remap = true); /** * \brief Append one name to another */ ROSCPP_DECL std::string append(const std::string& left, const std::string& right); /** * \brief Apply remappings to a name * \throws InvalidNameException if the name passed is not a valid graph resource name */ ROSCPP_DECL std::string remap(const std::string& name); /** * \brief Validate a name against the name spec */ ROSCPP_DECL bool validate(const std::string& name, std::string& error); ROSCPP_DECL const M_string& getRemappings(); ROSCPP_DECL const M_string& getUnresolvedRemappings(); /** * \brief Get the parent namespace of a name * \param name The namespace of which to get the parent namespace. * \throws InvalidNameException if the name passed is not a valid graph resource name */ ROSCPP_DECL std::string parentNamespace(const std::string& name); } // namespace names } // namespace ros #endif // ROSCPP_NAMES_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/subscriber_link.h
/* * 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. */ #ifndef ROSCPP_SUBSCRIBER_LINK_H #define ROSCPP_SUBSCRIBER_LINK_H #include "ros/common.h" #include <boost/thread/mutex.hpp> #include <boost/shared_array.hpp> #include <boost/weak_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <queue> namespace ros { class Header; class Message; class Publication; typedef boost::shared_ptr<Publication> PublicationPtr; typedef boost::weak_ptr<Publication> PublicationWPtr; class Connection; typedef boost::shared_ptr<Connection> ConnectionPtr; class ROSCPP_DECL SubscriberLink : public boost::enable_shared_from_this<SubscriberLink> { public: class Stats { public: uint64_t bytes_sent_, message_data_sent_, messages_sent_; Stats() : bytes_sent_(0), message_data_sent_(0), messages_sent_(0) { } }; SubscriberLink(); virtual ~SubscriberLink(); const std::string& getTopic() const { return topic_; } const Stats &getStats() { return stats_; } const std::string &getDestinationCallerID() const { return destination_caller_id_; } int getConnectionID() const { return connection_id_; } /** * \brief Queue up a message for publication. Throws out old messages if we've reached our Publication's max queue size */ virtual void enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy) = 0; virtual void drop() = 0; virtual const ConnectionPtr& getConnection() = 0; virtual std::string getTransportType() = 0; virtual std::string getTransportInfo() = 0; virtual bool isIntraprocess() { return false; } virtual void getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti) { (void)ti; ser = true; nocopy = false; } const std::string& getMD5Sum(); const std::string& getDataType(); const std::string& getMessageDefinition(); void setDefaultTransport(bool default_transport); bool getDefaultTransport(); void setRospy(bool rospy); bool getRospy (); protected: bool verifyDatatype(const std::string &datatype); PublicationWPtr parent_; unsigned int connection_id_; std::string destination_caller_id_; Stats stats_; std::string topic_; bool default_transport_ ; bool rospy_; }; } // namespace ros #endif // ROSCPP_SUBSCRIBER_LINK_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_server_link.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 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 ROSCPP_SERVICE_SERVER_LINK_H #define ROSCPP_SERVICE_SERVER_LINK_H #include "ros/common.h" #include <boost/thread/mutex.hpp> #include <boost/shared_array.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/thread.hpp> #include <queue> namespace ros { class Header; class Message; class Connection; typedef boost::shared_ptr<Connection> ConnectionPtr; /** * \brief Handles a connection to a service. If it's a non-persistent client, automatically disconnects * when its first service call has finished. */ class ROSCPP_DECL ServiceServerLink : public boost::enable_shared_from_this<ServiceServerLink> { private: struct CallInfo { SerializedMessage req_; SerializedMessage* resp_; bool finished_; boost::condition_variable finished_condition_; boost::mutex finished_mutex_; boost::thread::id caller_thread_id_; bool success_; bool call_finished_; std::string exception_string_; }; typedef boost::shared_ptr<CallInfo> CallInfoPtr; typedef std::queue<CallInfoPtr> Q_CallInfo; public: typedef std::map<std::string, std::string> M_string; ServiceServerLink(const std::string& service_name, bool persistent, const std::string& request_md5sum, const std::string& response_md5sum, const M_string& header_values); virtual ~ServiceServerLink(); // bool initialize(const ConnectionPtr& connection); /** * \brief Returns whether this client is still valid, ie. its connection has not been dropped */ bool isValid() const; /** * \brief Returns whether this is a persistent connection */ bool isPersistent() const { return persistent_; } const ConnectionPtr& getConnection() const { return connection_; } const std::string& getServiceName() const { return service_name_; } const std::string& getRequestMD5Sum() const { return request_md5sum_; } const std::string& getResponseMD5Sum() const { return response_md5sum_; } /** * \brief Blocking call the service this client is connected to * * If there is already a call happening in another thread, this will queue up the call and still block until * it has finished. */ bool call(const SerializedMessage& req, SerializedMessage& resp); private: void onConnectionDropped(const ConnectionPtr& conn); bool onHeaderReceived(const ConnectionPtr& conn, const Header& header); /** * \brief Called when the currently queued call has finished. Clears out the current call, notifying it that it * has finished, then calls processNextCall() */ void callFinished(); /** * \brief Pops the next call off the queue if one is available. If this is a non-persistent connection and the queue is empty * it will also drop the connection. */ void processNextCall(); /** * \brief Clear all calls, notifying them that they've failed */ void clearCalls(); /** * \brief Cancel a queued call, notifying it that it has failed */ void cancelCall(const CallInfoPtr& info); void onHeaderWritten(const ConnectionPtr& conn); void onRequestWritten(const ConnectionPtr& conn); void onResponseOkAndLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success); void onResponse(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success); ConnectionPtr connection_; std::string service_name_; bool persistent_; std::string request_md5sum_; std::string response_md5sum_; M_string extra_outgoing_header_values_; bool header_written_; bool header_read_; Q_CallInfo call_queue_; boost::mutex call_queue_mutex_; CallInfoPtr current_call_; bool dropped_; }; typedef boost::shared_ptr<ServiceServerLink> ServiceServerLinkPtr; } // namespace ros #endif // ROSCPP_SERVICE_SERVER_LINK_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_client.h
/* * 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. */ #ifndef ROSCPP_SERVICE_CLIENT_H #define ROSCPP_SERVICE_CLIENT_H #include "ros/forwards.h" #include "ros/common.h" #include "ros/service_traits.h" #include "ros/serialization.h" namespace ros { /** * @brief Provides a handle-based interface to service client connections */ class ROSCPP_DECL ServiceClient { public: ServiceClient() {} ServiceClient(const std::string& service_name, bool persistent, const M_string& header_values, const std::string& service_md5sum); ServiceClient(const ServiceClient& rhs); ~ServiceClient(); /** * @brief Call the service aliased by this handle with the specified request/response messages. * @note The request/response message types must match the types specified in the templated call to NodeHandle::serviceClient()/service::createClient() */ template<class MReq, class MRes> bool call(MReq& req, MRes& res) { namespace st = service_traits; if (!isValid()) { return false; } if (strcmp(st::md5sum(req), st::md5sum(res))) { ROS_ERROR("The request and response parameters to the service " "call must be autogenerated from the same " "server definition file (.srv). your service call " "for %s appeared to use request/response types " "from different .srv files. (%s vs. %s)", impl_->name_.c_str(), st::md5sum(req), st::md5sum(res)); return false; } return call(req, res, st::md5sum(req)); } /** * @brief Call the service aliased by this handle with the specified service request/response */ template<class Service> bool call(Service& service) { namespace st = service_traits; if (!isValid()) { return false; } return call(service.request, service.response, st::md5sum(service)); } /** * \brief Mostly for internal use, the other templated versions of call() just call into this one */ template<typename MReq, typename MRes> bool call(const MReq& req, MRes& resp, const std::string& service_md5sum) { namespace ser = serialization; SerializedMessage ser_req = ser::serializeMessage(req); SerializedMessage ser_resp; bool ok = call(ser_req, ser_resp, service_md5sum); if (!ok) { return false; } try { ser::deserializeMessage(ser_resp, resp); } catch (std::exception& e) { deserializeFailed(e); return false; } return true; } bool call(const SerializedMessage& req, SerializedMessage& resp, const std::string& service_md5sum); /** * \brief Returns whether or not this handle is valid. For a persistent service, this becomes false when the connection has dropped. * Non-persistent service handles are always valid. */ bool isValid() const; /** * \brief Returns true if this handle points to a persistent service, false otherwise. */ bool isPersistent() const; /** * \brief Shutdown the connection associated with this ServiceClient * * This method usually does not need to be explicitly called, as automatic shutdown happens when * all copies of this ServiceClient go out of scope * * This method overrides the automatic reference counted shutdown, and does so immediately. */ void shutdown(); /** * \brief Wait for this service to be advertised and available. Blocks until it is. * \param timeout The amount of time to wait for before timing out. If timeout is -1 (default), * waits until the node is shutdown * \return true on success, false otherwise */ bool waitForExistence(ros::Duration timeout = ros::Duration(-1)); /** * \brief Checks if this is both advertised and available. * \return true if the service is up and available, false otherwise */ bool exists(); /** * \brief Returns the name of the service this ServiceClient connects to */ std::string getService(); operator void*() const { return isValid() ? (void*)1 : (void*)0; } bool operator<(const ServiceClient& rhs) const { return impl_ < rhs.impl_; } bool operator==(const ServiceClient& rhs) const { return impl_ == rhs.impl_; } bool operator!=(const ServiceClient& rhs) const { return impl_ != rhs.impl_; } private: // This works around a problem with the OSX linker that causes the static variable declared by // ROS_ERROR to error with missing symbols when it's used directly in the templated call() method above // This for some reason only showed up in the rxtools package void deserializeFailed(const std::exception& e) { ROS_ERROR("Exception thrown while while deserializing service call: %s", e.what()); } struct Impl { Impl(); ~Impl(); void shutdown(); bool isValid() const; ServiceServerLinkPtr server_link_; std::string name_; bool persistent_; M_string header_values_; std::string service_md5sum_; bool is_shutdown_; }; typedef boost::shared_ptr<Impl> ImplPtr; typedef boost::weak_ptr<Impl> ImplWPtr; ImplPtr impl_; friend class NodeHandle; friend class NodeHandleBackingCollection; }; typedef boost::shared_ptr<ServiceClient> ServiceClientPtr; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/message_deserializer.h
/* * 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. */ #ifndef ROSCPP_MESSAGE_DESERIALIZER_H #define ROSCPP_MESSAGE_DESERIALIZER_H #include "forwards.h" #include "common.h" #include <ros/serialized_message.h> #include <boost/thread/mutex.hpp> #include <boost/shared_array.hpp> namespace ros { class SubscriptionCallbackHelper; typedef boost::shared_ptr<SubscriptionCallbackHelper> SubscriptionCallbackHelperPtr; class ROSCPP_DECL MessageDeserializer { public: MessageDeserializer(const SubscriptionCallbackHelperPtr& helper, const SerializedMessage& m, const boost::shared_ptr<M_string>& connection_header); VoidConstPtr deserialize(); const boost::shared_ptr<M_string>& getConnectionHeader() { return connection_header_; } private: SubscriptionCallbackHelperPtr helper_; SerializedMessage serialized_message_; boost::shared_ptr<M_string> connection_header_; boost::mutex mutex_; VoidConstPtr msg_; }; typedef boost::shared_ptr<MessageDeserializer> MessageDeserializerPtr; } #endif // ROSCPP_MESSAGE_DESERIALIZER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/io.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 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. */ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef ROSCPP_IO_H_ #define ROSCPP_IO_H_ /***************************************************************************** ** Includes *****************************************************************************/ #include <string> #include "common.h" #ifdef WIN32 #include <winsock2.h> // For struct timeval #include <ws2tcpip.h> // Must be after winsock2.h because MS didn't put proper inclusion guards in their headers. #include <sys/types.h> #include <io.h> #include <fcntl.h> #include <process.h> // for _getpid #else #include <poll.h> // should get cmake to explicitly check for poll.h? #include <sys/poll.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <netdb.h> // getnameinfo in network.cpp #include <netinet/in.h> // sockaddr_in in network.cpp #include <netinet/tcp.h> // TCP_NODELAY in transport/transport_tcp.cpp #endif /***************************************************************************** ** Cross Platform Macros *****************************************************************************/ #ifdef WIN32 #define getpid _getpid #define ROS_INVALID_SOCKET INVALID_SOCKET #define ROS_SOCKETS_SHUT_RDWR SD_BOTH /* Used by ::shutdown() */ #define ROS_SOCKETS_ASYNCHRONOUS_CONNECT_RETURN WSAEWOULDBLOCK #ifndef POLLRDNORM #define POLLRDNORM 0x0100 /* mapped to read fds_set */ #endif #ifndef POLLRDBAND #define POLLRDBAND 0x0200 /* mapped to exception fds_set */ #endif #ifndef POLLIN #define POLLIN (POLLRDNORM | POLLRDBAND) /* There is data to read. */ #endif #ifndef POLLPRI #define POLLPRI 0x0400 /* There is urgent data to read. */ #endif #ifndef POLLWRNORM #define POLLWRNORM 0x0010 /* mapped to write fds_set */ #endif #ifndef POLLOUT #define POLLOUT (POLLWRNORM) /* Writing now will not block. */ #endif #ifndef POLLWRBAND #define POLLWRBAND 0x0020 /* mapped to write fds_set */ #endif #ifndef POLLERR #define POLLERR 0x0001 /* Error condition. */ #endif #ifndef POLLHUP #define POLLHUP 0x0002 /* Hung up. */ #endif #ifndef POLLNVAL #define POLLNVAL 0x0004 /* Invalid polling request. */ #endif #else #define ROS_SOCKETS_SHUT_RDWR SHUT_RDWR /* Used by ::shutdown() */ #define ROS_INVALID_SOCKET ((int) -1) #define ROS_SOCKETS_ASYNCHRONOUS_CONNECT_RETURN EINPROGRESS #endif /***************************************************************************** ** Namespaces *****************************************************************************/ namespace ros { /***************************************************************************** ** Cross Platform Types *****************************************************************************/ #ifdef WIN32 typedef SOCKET socket_fd_t; typedef SOCKET signal_fd_t; /* poll emulation support */ typedef struct socket_pollfd { socket_fd_t fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */ } socket_pollfd; typedef unsigned long int nfds_t; #ifdef _MSC_VER typedef int pid_t; /* return type for windows' _getpid */ #endif #else typedef int socket_fd_t; typedef int signal_fd_t; typedef struct pollfd socket_pollfd; #endif /***************************************************************************** ** Functions *****************************************************************************/ ROSCPP_DECL int last_socket_error(); ROSCPP_DECL const char* last_socket_error_string(); ROSCPP_DECL bool last_socket_error_is_would_block(); ROSCPP_DECL int poll_sockets(socket_pollfd *fds, nfds_t nfds, int timeout); ROSCPP_DECL int set_non_blocking(socket_fd_t &socket); ROSCPP_DECL int close_socket(socket_fd_t &socket); ROSCPP_DECL int create_signal_pair(signal_fd_t signal_pair[2]); /***************************************************************************** ** Inlines - almost direct api replacements, should stay fast. *****************************************************************************/ /** * Closes the signal pair - on windows we're using sockets (because windows * select() function cant handle pipes). On linux, we're just using the pipes. * @param signal_pair : the signal pair type. */ inline void close_signal_pair(signal_fd_t signal_pair[2]) { #ifdef WIN32 // use a socket pair ::closesocket(signal_pair[0]); ::closesocket(signal_pair[1]); #else // use a socket pair on mingw or pipe pair on linux, either way, close works ::close(signal_pair[0]); ::close(signal_pair[1]); #endif } /** * Write to a signal_fd_t device. On windows we're using sockets (because windows * select() function cant handle pipes) so we have to use socket functions. * On linux, we're just using the pipes. */ #ifdef _MSC_VER inline int write_signal(const signal_fd_t &signal, const char *buffer, const unsigned int &nbyte) { return ::send(signal, buffer, nbyte, 0); // return write(signal, buffer, nbyte); } #else inline ssize_t write_signal(const signal_fd_t &signal, const void *buffer, const size_t &nbyte) { return write(signal, buffer, nbyte); } #endif /** * Read from a signal_fd_t device. On windows we're using sockets (because windows * select() function cant handle pipes) so we have to use socket functions. * On linux, we're just using the pipes. */ #ifdef _MSC_VER inline int read_signal(const signal_fd_t &signal, char *buffer, const unsigned int &nbyte) { return ::recv(signal, buffer, nbyte, 0); // return _read(signal, buffer, nbyte); } #else inline ssize_t read_signal(const signal_fd_t &signal, void *buffer, const size_t &nbyte) { return read(signal, buffer, nbyte); } #endif } // namespace ros #endif /* ROSCPP_IO_H_ */
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/statistics.h
/* * Copyright (C) 2013-2014, Dariush Forouher * * 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. */ #ifndef ROSCPP_STATISTICS_H #define ROSCPP_STATISTICS_H #include "forwards.h" #include "poll_set.h" #include "common.h" #include "publisher.h" #include <ros/time.h> #include "ros/subscription_callback_helper.h" #include <map> namespace ros { /** * \brief This class logs statistics data about a ROS connection and * publishs them periodically on a common topic. * * It provides a callback() function that has to be called everytime * a new message arrives on a topic. */ class ROSCPP_DECL StatisticsLogger { public: /** * Constructior */ StatisticsLogger(); /** * Actual initialization. Must be called before the first call to callback() */ void init(const SubscriptionCallbackHelperPtr& helper); /** * Callback function. Must be called for every message received. */ void callback(const boost::shared_ptr<M_string>& connection_header, const std::string& topic, const std::string& callerid, const SerializedMessage& m, const uint64_t& bytes_sent, const ros::Time& received_time, bool dropped); private: // these are hard constrains int max_window; int min_window; // these are soft constrains int max_elements; int min_elements; bool enable_statistics; // remember, if this message type has a header bool hasHeader_; // frequency to publish statistics double pub_frequency_; // publisher for statistics data ros::Publisher pub_; struct StatData { // last time, we published /statistics data ros::Time last_publish; // arrival times of all messages within the current window std::list<ros::Time> arrival_time_list; // age of all messages within the current window (if available) std::list<ros::Duration> age_list; // number of dropped messages uint64_t dropped_msgs; // latest sequence number observered (if available) uint64_t last_seq; // latest total traffic volume observed uint64_t stat_bytes_last; }; // storage for statistics data std::map<std::string, struct StatData> map_; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/master.h
/* * 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. */ #ifndef ROSCPP_MASTER_H #define ROSCPP_MASTER_H #include "forwards.h" #include "XmlRpcValue.h" #include "common.h" namespace ros { /** * \brief Contains functions which allow you to query information about the master */ namespace master { /** @brief Execute an XMLRPC call on the master * * @param method The RPC method to invoke * @param request The arguments to the RPC call * @param response [out] The resonse that was received. * @param payload [out] The payload that was received. * @param wait_for_master Whether or not this call should loop until it can contact the master * * @return true if call succeeds, false otherwise. */ ROSCPP_DECL bool execute(const std::string& method, const XmlRpc::XmlRpcValue& request, XmlRpc::XmlRpcValue& response, XmlRpc::XmlRpcValue& payload, bool wait_for_master); /** @brief Get the hostname where the master runs. * * @return The master's hostname, as a string */ ROSCPP_DECL const std::string& getHost(); /** @brief Get the port where the master runs. * * @return The master's port. */ ROSCPP_DECL uint32_t getPort(); /** * \brief Get the full URI to the master (eg. http://host:port/) */ ROSCPP_DECL const std::string& getURI(); /** @brief Check whether the master is up * * This method tries to contact the master. You can call it any time * after ros::init has been called. The intended usage is to check * whether the master is up before trying to make other requests * (subscriptions, advertisements, etc.). * * @returns true if the master is available, false otherwise. */ ROSCPP_DECL bool check(); /** * \brief Contains information retrieved from the master about a topic */ struct ROSCPP_DECL TopicInfo { TopicInfo() {} TopicInfo(const std::string& _name, const std::string& _datatype /*, const std::string& _md5sum*/) : name(_name) , datatype(_datatype) //, md5sum(_md5sum) {} std::string name; ///< Name of the topic std::string datatype; ///< Datatype of the topic // not possible yet unfortunately (master does not have this information) //std::string md5sum; ///< md5sum of the topic }; typedef std::vector<TopicInfo> V_TopicInfo; /** @brief Get the list of topics that are being published by all nodes. * * This method communicates with the master to retrieve the list of all * currently advertised topics. * * @param topics A place to store the resulting list. Each item in the * list is a pair <string topic, string type>. The type is represented * in the format "package_name/MessageName", and is also retrievable * through message.__getDataType() or MessageName::__s_getDataType(). * * @return true on success, false otherwise (topics not filled in) */ ROSCPP_DECL bool getTopics(V_TopicInfo& topics); /** * \brief Retreives the currently-known list of nodes from the master */ ROSCPP_DECL bool getNodes(V_string& nodes); /** * @brief Set the max time this node should spend looping trying to connect to the master * @param The timeout. A negative value means infinite */ ROSCPP_DECL void setRetryTimeout(ros::WallDuration timeout); } // namespace master } // namespace ros #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/transport_publisher_link.h
/* * 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. */ #ifndef ROSCPP_TRANSPORT_PUBLISHER_LINK_H #define ROSCPP_TRANSPORT_PUBLISHER_LINK_H #include "common.h" #include "publisher_link.h" #include "connection.h" namespace ros { class Header; class Message; class Subscription; typedef boost::shared_ptr<Subscription> SubscriptionPtr; typedef boost::weak_ptr<Subscription> SubscriptionWPtr; class Connection; typedef boost::shared_ptr<Connection> ConnectionPtr; class WallTimerEvent; /** * \brief Handles a connection to a single publisher on a given topic. Receives messages from a publisher * and hands them off to its parent Subscription */ class ROSCPP_DECL TransportPublisherLink : public PublisherLink { public: TransportPublisherLink(const SubscriptionPtr& parent, const std::string& xmlrpc_uri, const TransportHints& transport_hints); virtual ~TransportPublisherLink(); // bool initialize(const ConnectionPtr& connection); const ConnectionPtr& getConnection() { return connection_; } virtual std::string getTransportType(); virtual std::string getTransportInfo(); virtual void drop(); private: void onConnectionDropped(const ConnectionPtr& conn, Connection::DropReason reason); bool onHeaderReceived(const ConnectionPtr& conn, const Header& header); /** * \brief Handles handing off a received message to the subscription, where it will be deserialized and called back */ virtual void handleMessage(const SerializedMessage& m, bool ser, bool nocopy); void onHeaderWritten(const ConnectionPtr& conn); void onMessageLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success); void onMessage(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success); void onRetryTimer(const ros::WallTimerEvent&); ConnectionPtr connection_; int32_t retry_timer_handle_; bool needs_retry_; WallDuration retry_period_; WallTime next_retry_; bool dropping_; }; typedef boost::shared_ptr<TransportPublisherLink> TransportPublisherLinkPtr; } // namespace ros #endif // ROSCPP_TRANSPORT_PUBLISHER_LINK_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/subscription.h
/* * 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. */ #ifndef ROSCPP_SUBSCRIPTION_H #define ROSCPP_SUBSCRIPTION_H #include <queue> #include "ros/common.h" #include "ros/header.h" #include "ros/forwards.h" #include "ros/transport_hints.h" #include "ros/xmlrpc_manager.h" #include "ros/statistics.h" #include "XmlRpc.h" #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> namespace ros { class PublisherLink; typedef boost::shared_ptr<PublisherLink> PublisherLinkPtr; class SubscriptionCallback; typedef boost::shared_ptr<SubscriptionCallback> SubscriptionCallbackPtr; class SubscriptionQueue; typedef boost::shared_ptr<SubscriptionQueue> SubscriptionQueuePtr; class MessageDeserializer; typedef boost::shared_ptr<MessageDeserializer> MessageDeserializerPtr; class SubscriptionCallbackHelper; typedef boost::shared_ptr<SubscriptionCallbackHelper> SubscriptionCallbackHelperPtr; /** * \brief Manages a subscription on a single topic. */ class ROSCPP_DECL Subscription : public boost::enable_shared_from_this<Subscription> { public: Subscription(const std::string &name, const std::string& md5sum, const std::string& datatype, const TransportHints& transport_hints); virtual ~Subscription(); /** * \brief Terminate all our PublisherLinks */ void drop(); /** * \brief Terminate all our PublisherLinks and join our callback thread if it exists */ void shutdown(); /** * \brief Handle a publisher update list received from the master. Creates/drops PublisherLinks based on * the list. Never handles new self-subscriptions */ bool pubUpdate(const std::vector<std::string> &pubs); /** * \brief Negotiates a connection with a publisher * \param xmlrpc_uri The XMLRPC URI to connect to to negotiate the connection */ bool negotiateConnection(const std::string& xmlrpc_uri); void addLocalConnection(const PublicationPtr& pub); /** * \brief Returns whether this Subscription has been dropped or not */ bool isDropped() { return dropped_; } XmlRpc::XmlRpcValue getStats(); void getInfo(XmlRpc::XmlRpcValue& info); bool addCallback(const SubscriptionCallbackHelperPtr& helper, const std::string& md5sum, CallbackQueueInterface* queue, int32_t queue_size, const VoidConstPtr& tracked_object, bool allow_concurrent_callbacks); void removeCallback(const SubscriptionCallbackHelperPtr& helper); typedef std::map<std::string, std::string> M_string; /** * \brief Called to notify that a new message has arrived from a publisher. * Schedules the callback for invokation with the callback queue */ uint32_t handleMessage(const SerializedMessage& m, bool ser, bool nocopy, const boost::shared_ptr<M_string>& connection_header, const PublisherLinkPtr& link); const std::string datatype(); const std::string md5sum(); /** * \brief Removes a subscriber from our list */ void removePublisherLink(const PublisherLinkPtr& pub_link); const std::string& getName() const { return name_; } uint32_t getNumCallbacks() const { return callbacks_.size(); } uint32_t getNumPublishers(); // We'll keep a list of these objects, representing in-progress XMLRPC // connections to other nodes. class ROSCPP_DECL PendingConnection : public ASyncXMLRPCConnection { public: PendingConnection(XmlRpc::XmlRpcClient* client, TransportUDPPtr udp_transport, const SubscriptionWPtr& parent, const std::string& remote_uri) : client_(client) , udp_transport_(udp_transport) , parent_(parent) , remote_uri_(remote_uri) {} ~PendingConnection() { delete client_; } XmlRpc::XmlRpcClient* getClient() const { return client_; } TransportUDPPtr getUDPTransport() const { return udp_transport_; } virtual void addToDispatch(XmlRpc::XmlRpcDispatch* disp) { disp->addSource(client_, XmlRpc::XmlRpcDispatch::WritableEvent | XmlRpc::XmlRpcDispatch::Exception); } virtual void removeFromDispatch(XmlRpc::XmlRpcDispatch* disp) { disp->removeSource(client_); } virtual bool check() { SubscriptionPtr parent = parent_.lock(); if (!parent) { return true; } XmlRpc::XmlRpcValue result; if (client_->executeCheckDone(result)) { parent->pendingConnectionDone(boost::dynamic_pointer_cast<PendingConnection>(shared_from_this()), result); return true; } return false; } const std::string& getRemoteURI() { return remote_uri_; } private: XmlRpc::XmlRpcClient* client_; TransportUDPPtr udp_transport_; SubscriptionWPtr parent_; std::string remote_uri_; }; typedef boost::shared_ptr<PendingConnection> PendingConnectionPtr; void pendingConnectionDone(const PendingConnectionPtr& pending_conn, XmlRpc::XmlRpcValue& result); void getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti); void headerReceived(const PublisherLinkPtr& link, const Header& h); bool getSelfSubscribed(); void setSelfSubscribed(bool self_subscribed); void setLastIndex(int last_read_index); int getLastIndex(); private: Subscription(const Subscription &); // not copyable Subscription &operator =(const Subscription &); // nor assignable void dropAllConnections(); void addPublisherLink(const PublisherLinkPtr& link); struct CallbackInfo { CallbackQueueInterface* callback_queue_; // Only used if callback_queue_ is non-NULL (NodeHandle API) SubscriptionCallbackHelperPtr helper_; SubscriptionQueuePtr subscription_queue_; bool has_tracked_object_; VoidConstWPtr tracked_object_; }; typedef boost::shared_ptr<CallbackInfo> CallbackInfoPtr; typedef std::vector<CallbackInfoPtr> V_CallbackInfo; std::string name_; boost::mutex md5sum_mutex_; std::string md5sum_; std::string datatype_; boost::mutex callbacks_mutex_; V_CallbackInfo callbacks_; uint32_t nonconst_callbacks_; bool dropped_; bool shutting_down_; boost::mutex shutdown_mutex_; typedef std::set<PendingConnectionPtr> S_PendingConnection; S_PendingConnection pending_connections_; boost::mutex pending_connections_mutex_; typedef std::vector<PublisherLinkPtr> V_PublisherLink; V_PublisherLink publisher_links_; boost::mutex publisher_links_mutex_; TransportHints transport_hints_; StatisticsLogger statistics_; struct LatchInfo { SerializedMessage message; PublisherLinkPtr link; boost::shared_ptr<std::map<std::string, std::string> > connection_header; ros::Time receipt_time; }; typedef std::map<PublisherLinkPtr, LatchInfo> M_PublisherLinkToLatchInfo; M_PublisherLinkToLatchInfo latched_messages_; typedef std::vector<std::pair<const std::type_info*, MessageDeserializerPtr> > V_TypeAndDeserializer; V_TypeAndDeserializer cached_deserializers_; bool default_transport_ ; bool self_subscribed_ ; int32_t last_read_index_; boost::interprocess::interprocess_mutex shm_sub_mutex_; SubscriptionCallbackHelperPtr helper_; public: SubscriptionCallbackHelperPtr& get_helper() { return helper_; } std::vector<PublisherLinkPtr> get_publisher_links() { return publisher_links_; } }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_publication.h
/* * 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. */ #ifndef ROSCPP_SERVICE_PUBLICATION_H #define ROSCPP_SERVICE_PUBLICATION_H #include "ros/service_callback_helper.h" #include "common.h" #include "XmlRpc.h" #include <boost/thread/mutex.hpp> #include <boost/shared_ptr.hpp> #include <boost/shared_array.hpp> #include <boost/thread.hpp> #include <boost/enable_shared_from_this.hpp> #include <vector> #include <queue> namespace ros { class ServiceClientLink; typedef boost::shared_ptr<ServiceClientLink> ServiceClientLinkPtr; typedef std::vector<ServiceClientLinkPtr> V_ServiceClientLink; class CallbackQueueInterface; class Message; /** * \brief Manages an advertised service. * * ServicePublication manages all incoming service requests. If its thread pool size is not 0, it will queue the requests * into a number of threads, calling the callback from within those threads. Otherwise it immediately calls the callback */ class ROSCPP_DECL ServicePublication : public boost::enable_shared_from_this<ServicePublication> { public: ServicePublication(const std::string& name, const std::string &md5sum, const std::string& data_type, const std::string& request_data_type, const std::string& response_data_type, const ServiceCallbackHelperPtr& helper, CallbackQueueInterface* queue, const VoidConstPtr& tracked_object); ~ServicePublication(); /** * \brief Adds a request to the queue if our thread pool size is not 0, otherwise immediately calls the callback */ void processRequest(boost::shared_array<uint8_t> buf, size_t num_bytes, const ServiceClientLinkPtr& link); /** * \brief Adds a service link for us to manage */ void addServiceClientLink(const ServiceClientLinkPtr& link); /** * \brief Removes a service link from our list */ void removeServiceClientLink(const ServiceClientLinkPtr& link); /** * \brief Terminate this service server */ void drop(); /** * \brief Returns whether or not this service server is valid */ bool isDropped() { return dropped_; } const std::string& getMD5Sum() { return md5sum_; } const std::string& getRequestDataType() { return request_data_type_; } const std::string& getResponseDataType() { return response_data_type_; } const std::string& getDataType() { return data_type_; } const std::string& getName() { return name_; } private: void dropAllConnections(); std::string name_; std::string md5sum_; std::string data_type_; std::string request_data_type_; std::string response_data_type_; ServiceCallbackHelperPtr helper_; V_ServiceClientLink client_links_; boost::mutex client_links_mutex_; bool dropped_; CallbackQueueInterface* callback_queue_; bool has_tracked_object_; VoidConstWPtr tracked_object_; }; typedef boost::shared_ptr<ServicePublication> ServicePublicationPtr; } #endif // ROSCPP_SERVICE_PUBLICATION_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/parameter_adapter.h
/* * 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. */ #ifndef ROSCPP_PARAMETER_ADAPTER_H #define ROSCPP_PARAMETER_ADAPTER_H #include "ros/forwards.h" #include "ros/message_event.h" #include <ros/static_assert.h> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> namespace ros { /** * \brief Generally not for outside use. Adapts a function parameter type into the message type, event type and parameter. Allows you to * retrieve a parameter type from an event type. * * ParameterAdapter is generally only useful for outside use when implementing things that require message callbacks * (such as the message_filters package)and you would like to support all the roscpp message parameter types * * The ParameterAdapter is templated on the callback parameter type (\b not the bare message type), and provides 3 things: * - Message typedef, which provides the bare message type, no const or reference qualifiers * - Event typedef, which provides the ros::MessageEvent type * - Parameter typedef, which provides the actual parameter type (may be slightly different from M) * - static getParameter(event) function, which returns a parameter type given the event * - static bool is_const informs you whether or not the parameter type is a const message * * ParameterAdapter is specialized to allow callbacks of any of the forms: \verbatim void callback(const boost::shared_ptr<M const>&); void callback(const boost::shared_ptr<M>&); void callback(boost::shared_ptr<M const>); void callback(boost::shared_ptr<M>); void callback(const M&); void callback(M); void callback(const MessageEvent<M const>&); void callback(const MessageEvent<M>&); \endverbatim */ template<typename M> struct ParameterAdapter { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef M Parameter; static const bool is_const = true; static Parameter getParameter(const Event& event) { return *event.getMessage(); } }; template<typename M> struct ParameterAdapter<const boost::shared_ptr<M const>& > { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef const boost::shared_ptr<Message const> Parameter; static const bool is_const = true; static Parameter getParameter(const Event& event) { return event.getMessage(); } }; template<typename M> struct ParameterAdapter<const boost::shared_ptr<M>& > { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef boost::shared_ptr<Message> Parameter; static const bool is_const = false; static Parameter getParameter(const Event& event) { return ros::MessageEvent<Message>(event).getMessage(); } }; template<typename M> struct ParameterAdapter<const M&> { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef const M& Parameter; static const bool is_const = true; static Parameter getParameter(const Event& event) { return *event.getMessage(); } }; template<typename M> struct ParameterAdapter<boost::shared_ptr<M const> > { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef boost::shared_ptr<Message const> Parameter; static const bool is_const = true; static Parameter getParameter(const Event& event) { return event.getMessage(); } }; template<typename M> struct ParameterAdapter<boost::shared_ptr<M> > { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef boost::shared_ptr<Message> Parameter; static const bool is_const = false; static Parameter getParameter(const Event& event) { return ros::MessageEvent<Message>(event).getMessage(); } }; template<typename M> struct ParameterAdapter<const ros::MessageEvent<M const>& > { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef const ros::MessageEvent<Message const>& Parameter; static const bool is_const = true; static Parameter getParameter(const Event& event) { return event; } }; template<typename M> struct ParameterAdapter<const ros::MessageEvent<M>& > { typedef typename boost::remove_reference<typename boost::remove_const<M>::type>::type Message; typedef ros::MessageEvent<Message const> Event; typedef ros::MessageEvent<Message> Parameter; static const bool is_const = false; static Parameter getParameter(const Event& event) { return ros::MessageEvent<Message>(event); } }; } #endif // ROSCPP_PARAMETER_ADAPTER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/poll_set.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 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 ROSCPP_POLL_SET_H #define ROSCPP_POLL_SET_H #include <vector> #include "io.h" #include "common.h" #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <boost/thread/mutex.hpp> namespace ros { class Transport; typedef boost::shared_ptr<Transport> TransportPtr; /** * \brief Manages a set of sockets being polled through the poll() function call. * * PollSet provides thread-safe ways of adding and deleting sockets, as well as adding * and deleting events. */ class ROSCPP_DECL PollSet { public: PollSet(); ~PollSet(); typedef boost::function<void(int)> SocketUpdateFunc; /** * \brief Add a socket. * * addSocket() may be called from any thread. * \param sock The socket to add * \param update_func The function to call when a socket has events * \param transport The (optional) transport associated with this socket. Mainly * used to prevent the transport from being deleted while we're calling the update function */ bool addSocket(int sock, const SocketUpdateFunc& update_func, const TransportPtr& transport = TransportPtr()); /** * \brief Delete a socket * * delSocket() may be called from any thread. * \param sock The socket to delete */ bool delSocket(int sock); /** * \brief Add events to be polled on a socket * * addEvents() may be called from any thread. * \param sock The socket to add events to * \param events The events to add */ bool addEvents(int sock, int events); /** * \brief Delete events to be polled on a socket * * delEvents() may be called from any thread. * \param sock The socket to delete events from * \param events The events to delete */ bool delEvents(int sock, int events); /** * \brief Process all socket events * * This function will actually call poll() on the available sockets, and allow * them to do their processing. * * update() may only be called from one thread at a time * * \param poll_timeout The time, in milliseconds, for the poll() call to timeout after * if there are no events. Note that this does not provide an upper bound for the entire * function, just the call to poll() */ void update(int poll_timeout); /** * \brief Signal our poll() call to finish if it's blocked waiting (see the poll_timeout * option for update()). */ void signal(); private: /** * \brief Creates the native pollset for our sockets, if any have changed */ void createNativePollset(); /** * \brief Called when events have been triggered on our signal pipe */ void onLocalPipeEvents(int events); struct SocketInfo { TransportPtr transport_; SocketUpdateFunc func_; int fd_; int events_; }; typedef std::map<int, SocketInfo> M_SocketInfo; M_SocketInfo socket_info_; boost::mutex socket_info_mutex_; bool sockets_changed_; boost::mutex just_deleted_mutex_; typedef std::vector<int> V_int; V_int just_deleted_; std::vector<socket_pollfd> ufds_; boost::mutex signal_mutex_; signal_fd_t signal_pipe_[2]; }; } #endif // ROSCPP_POLL_SET_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/subscription_queue.h
/* * 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. */ #ifndef ROSCPP_SUBSCRIPTION_QUEUE_H #define ROSCPP_SUBSCRIPTION_QUEUE_H #include "forwards.h" #include "common.h" #include "ros/message_event.h" #include "callback_queue_interface.h" #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/mutex.hpp> #include <boost/enable_shared_from_this.hpp> #include <deque> #include <thread> #include <iostream> #include <stdio.h> #include <string.h> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include "ros/subscription_callback_helper.h" #include "sharedmem_transport/sharedmem_util.h" namespace ros { class MessageDeserializer; typedef boost::shared_ptr<MessageDeserializer> MessageDeserializerPtr; class SubscriptionCallbackHelper; typedef boost::shared_ptr<SubscriptionCallbackHelper> SubscriptionCallbackHelperPtr; class ROSCPP_DECL SubscriptionQueue : public CallbackInterface, public boost::enable_shared_from_this<SubscriptionQueue> { private: struct Item { bool default_transport; SubscriptionCallbackHelperPtr helper; MessageDeserializerPtr deserializer; bool has_tracked_object; VoidConstWPtr tracked_object; bool nonconst_need_copy; ros::Time receipt_time; }; typedef std::deque<Item> D_Item; public: SubscriptionQueue(const std::string& topic, int32_t queue_size, bool allow_concurrent_callbacks); ~SubscriptionQueue(); void 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 = ros::Time(), bool* was_full = 0); void clear(); virtual CallbackInterface::CallResult call(); virtual bool ready(); bool full(); void removeMessageQueue(std::string topic); private: bool fullNoLock(); std::string topic_; int32_t size_; bool full_; boost::mutex queue_mutex_; D_Item queue_; uint32_t queue_size_; bool allow_concurrent_callbacks_; boost::recursive_mutex callback_mutex_; std::thread internal_cb_; bool first_run_; bool internal_cb_runnning_; int32_t last_read_index_; boost::interprocess::managed_shared_memory* segment_; sharedmem_transport::SharedMemorySegment* segment_mgr_; sharedmem_transport::SharedMemoryBlock* descriptors_sub_; uint32_t segment_queue_size_; }; } #endif // ROSCPP_SUBSCRIPTION_QUEUE_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/roscpp.dox
/** @mainpage roscpp @htmlinclude manifest.html \b roscpp is a ROS client implementation in C++. The main parts of \b roscpp are: - \ref ros::init() : A version of ros::init() must be called before using any of the rest of the ROS system. - \ref ros::NodeHandle : Public interface to topics, services, parameters, etc. - \ref ros::master : Contains functions for querying information from the master - \ref ros::this_node : Contains functions for querying information about this process' node - \ref ros::service : Contains functions for querying information about services - \ref ros::param : Contains functions for querying the parameter service without the need for a ros::NodeHandle - \ref ros::names : Contains functions for manipulating ROS graph resource names @par Examples Many examples of using ROS can be found <a href="http://www.ros.org/wiki/ROS/Tutorials">on the wiki</a> and in the <a href="http://www.ros.org/wiki/roscpp_tutorials">roscpp_tutorials</a> package. */
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/wall_timer_options.h
/* * 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. */ #ifndef ROSCPP_WALL_TIMER_OPTIONS_H #define ROSCPP_WALL_TIMER_OPTIONS_H #include "common.h" #include "ros/forwards.h" namespace ros { /** * \brief Encapsulates all options available for starting a timer */ struct ROSCPP_DECL WallTimerOptions { WallTimerOptions() : period(0.1) , callback_queue(0) , oneshot(false) , autostart(true) { } /* * \brief Constructor * \param */ WallTimerOptions(WallDuration _period, const WallTimerCallback& _callback, CallbackQueueInterface* _queue, bool oneshot = false, bool autostart = true) : period(_period) , callback(_callback) , callback_queue(_queue) , oneshot(oneshot) , autostart(autostart) {} WallDuration period; ///< The period to call the callback at WallTimerCallback callback; ///< The callback to call CallbackQueueInterface* callback_queue; ///< Queue to add callbacks to. If NULL, the global callback queue will be used /** * A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object, * and if the reference count goes to 0 the subscriber callbacks will not get called. * * \note Note that setting this will cause a new reference to be added to the object before the * callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore * thread) that the callback is invoked from. */ VoidConstPtr tracked_object; bool oneshot; bool autostart; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/callback_queue_interface.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 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 ROSCPP_CALLBACK_QUEUE_INTERFACE_H #define ROSCPP_CALLBACK_QUEUE_INTERFACE_H #include <boost/shared_ptr.hpp> #include "common.h" #include "ros/types.h" namespace ros { /** * \brief Abstract interface for items which can be added to a CallbackQueueInterface */ class ROSCPP_DECL CallbackInterface { public: /** * \brief Possible results for the call() method */ enum CallResult { Success, ///< Call succeeded TryAgain, ///< Call not ready, try again later Invalid, ///< Call no longer valid }; virtual ~CallbackInterface() {} /** * \brief Call this callback * \return The result of the call */ virtual CallResult call() = 0; /** * \brief Provides the opportunity for specifying that a callback is not ready to be called * before call() actually takes place. */ virtual bool ready() { return true; } }; typedef boost::shared_ptr<CallbackInterface> CallbackInterfacePtr; /** * \brief Abstract interface for a queue used to handle all callbacks within roscpp. * * Allows you to inherit and provide your own implementation that can be used instead of our * default CallbackQueue */ class CallbackQueueInterface { public: virtual ~CallbackQueueInterface() {} /** * \brief Add a callback, with an optional owner id. The owner id can be used to * remove a set of callbacks from this queue. */ virtual void addCallback(const CallbackInterfacePtr& callback, uint64_t owner_id = 0) = 0; /** * \brief Remove all callbacks associated with an owner id */ virtual void removeByID(uint64_t owner_id) = 0; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_client_options.h
/* * 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. */ #ifndef ROSCPP_SERVICE_CLIENT_OPTIONS_H #define ROSCPP_SERVICE_CLIENT_OPTIONS_H #include "ros/forwards.h" #include "common.h" #include "ros/service_traits.h" namespace ros { /** * \brief Encapsulates all options available for creating a ServiceClient */ struct ROSCPP_DECL ServiceClientOptions { ServiceClientOptions() : persistent(false) { } /* * \brief Constructor * \param _service Name of the service to connect to * \param _md5sum md5sum of the service * \param _persistent Whether or not to keep the connection open to the service for future calls * \param _header Any extra values to be passed along in the connection header */ ServiceClientOptions(const std::string& _service, const std::string& _md5sum, bool _persistent, const M_string& _header) : service(_service) , md5sum(_md5sum) , persistent(_persistent) , header(_header) { } /* * \brief Templated helper method, preventing you from needing to manually get the service md5sum * \param MReq [template] Request message type * \param MRes [template] Response message type * \param _service Name of the service to connect to * \param _persistent Whether or not to keep the connection open to the service for future calls * \param _header Any extra values to be passed along in the connection header */ template <class MReq, class MRes> void init(const std::string& _service, bool _persistent, const M_string& _header) { namespace st = service_traits; service = _service; md5sum = st::md5sum<MReq>(); persistent = _persistent; header = _header; } /* * \brief Templated helper method, preventing you from needing to manually get the service md5sum * \param Service [template] Service type * \param _service Name of the service to connect to * \param _persistent Whether or not to keep the connection open to the service for future calls * \param _header Any extra values to be passed along in the connection header */ template <class Service> void init(const std::string& _service, bool _persistent, const M_string& _header) { namespace st = service_traits; service = _service; md5sum = st::md5sum<Service>(); persistent = _persistent; header = _header; } std::string service; ///< Service to connect to std::string md5sum; ///< Service md5sum bool persistent; ///< Whether or not the connection should persist M_string header; ///< Extra key/value pairs to add to the connection header }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/timer_options.h
/* * 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. */ #ifndef ROSCPP_TIMER_OPTIONS_H #define ROSCPP_TIMER_OPTIONS_H #include "common.h" #include "ros/forwards.h" namespace ros { /** * \brief Encapsulates all options available for starting a timer */ struct ROSCPP_DECL TimerOptions { TimerOptions() : period(0.1) , callback_queue(0) , oneshot(false) , autostart(true) { } /* * \brief Constructor * \param */ TimerOptions(Duration _period, const TimerCallback& _callback, CallbackQueueInterface* _queue, bool oneshot = false, bool autostart = true) : period(_period) , callback(_callback) , callback_queue(_queue) , oneshot(oneshot) , autostart(autostart) { } Duration period; ///< The period to call the callback at TimerCallback callback; ///< The callback to call CallbackQueueInterface* callback_queue; ///< Queue to add callbacks to. If NULL, the global callback queue will be used /** * A shared pointer to an object to track for these callbacks. If set, the a weak_ptr will be created to this object, * and if the reference count goes to 0 the subscriber callbacks will not get called. * * \note Note that setting this will cause a new reference to be added to the object before the * callback, and for it to go out of scope (and potentially be deleted) in the code path (and therefore * thread) that the callback is invoked from. */ VoidConstPtr tracked_object; bool oneshot; bool autostart; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/callback_queue.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 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 ROSCPP_CALLBACK_QUEUE_H #define ROSCPP_CALLBACK_QUEUE_H #include "ros/callback_queue_interface.h" #include "ros/time.h" #include "common.h" #include <boost/shared_ptr.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/shared_mutex.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/tss.hpp> #include <list> #include <deque> namespace ros { /** * \brief This is the default implementation of the ros::CallbackQueueInterface */ class ROSCPP_DECL CallbackQueue : public CallbackQueueInterface { public: CallbackQueue(bool enabled = true); virtual ~CallbackQueue(); virtual void addCallback(const CallbackInterfacePtr& callback, uint64_t removal_id = 0); virtual void removeByID(uint64_t removal_id); enum CallOneResult { Called, TryAgain, Disabled, Empty, }; /** * \brief Pop a single callback off the front of the queue and invoke it. If the callback was not ready to be called, * pushes it back onto the queue. */ CallOneResult callOne() { return callOne(ros::WallDuration()); } /** * \brief Pop a single callback off the front of the queue and invoke it. If the callback was not ready to be called, * pushes it back onto the queue. This version includes a timeout which lets you specify the amount of time to wait for * a callback to be available before returning. * * \param timeout The amount of time to wait for a callback to be available. If there is already a callback available, * this parameter does nothing. */ CallOneResult callOne(ros::WallDuration timeout); /** * \brief Invoke all callbacks currently in the queue. If a callback was not ready to be called, pushes it back onto the queue. */ void callAvailable() { callAvailable(ros::WallDuration()); } /** * \brief Invoke all callbacks currently in the queue. If a callback was not ready to be called, pushes it back onto the queue. This version * includes a timeout which lets you specify the amount of time to wait for a callback to be available before returning. * * \param timeout The amount of time to wait for at least one callback to be available. If there is already at least one callback available, * this parameter does nothing. */ void callAvailable(ros::WallDuration timeout); /** * \brief returns whether or not the queue is empty */ bool empty() { return isEmpty(); } /** * \brief returns whether or not the queue is empty */ bool isEmpty(); /** * \brief Removes all callbacks from the queue. Does \b not wait for calls currently in progress to finish. */ void clear(); /** * \brief Enable the queue (queue is enabled by default) */ void enable(); /** * \brief Disable the queue, meaning any calls to addCallback() will have no effect */ void disable(); /** * \brief Returns whether or not this queue is enabled */ bool isEnabled(); protected: void setupTLS(); struct TLS; CallOneResult callOneCB(TLS* tls); struct IDInfo { uint64_t id; boost::shared_mutex calling_rw_mutex; }; typedef boost::shared_ptr<IDInfo> IDInfoPtr; typedef std::map<uint64_t, IDInfoPtr> M_IDInfo; IDInfoPtr getIDInfo(uint64_t id); struct CallbackInfo { CallbackInfo() : removal_id(0) , marked_for_removal(false) {} CallbackInterfacePtr callback; uint64_t removal_id; bool marked_for_removal; }; typedef std::list<CallbackInfo> L_CallbackInfo; typedef std::deque<CallbackInfo> D_CallbackInfo; D_CallbackInfo callbacks_; size_t calling_; boost::mutex mutex_; boost::condition_variable condition_; boost::mutex id_info_mutex_; M_IDInfo id_info_; struct TLS { TLS() : calling_in_this_thread(0xffffffffffffffffULL) , cb_it(callbacks.end()) {} uint64_t calling_in_this_thread; D_CallbackInfo callbacks; D_CallbackInfo::iterator cb_it; }; boost::thread_specific_ptr<TLS> tls_; bool enabled_; }; typedef boost::shared_ptr<CallbackQueue> CallbackQueuePtr; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/connection_manager.h
/* * 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 "forwards.h" #include "connection.h" #include "common.h" #include <boost/thread/mutex.hpp> #include <boost/signals2/connection.hpp> namespace ros { class PollManager; typedef boost::shared_ptr<PollManager> PollManagerPtr; class ConnectionManager; typedef boost::shared_ptr<ConnectionManager> ConnectionManagerPtr; class ROSCPP_DECL ConnectionManager { public: static const ConnectionManagerPtr& instance(); ConnectionManager(); ~ConnectionManager(); /** @brief Get a new connection ID */ uint32_t getNewConnectionID(); /** @brief Add a connection to be tracked by the node. Will automatically remove them if they've been dropped, but from inside the ros thread * * @param The connection to add */ void addConnection(const ConnectionPtr& connection); void clear(Connection::DropReason reason); uint32_t getTCPPort(); uint32_t getUDPPort(); const TransportTCPPtr& getTCPServerTransport() { return tcpserver_transport_; } const TransportUDPPtr& getUDPServerTransport() { return udpserver_transport_; } void udprosIncomingConnection(const TransportUDPPtr& transport, Header& header); void start(); void shutdown(); private: void onConnectionDropped(const ConnectionPtr& conn); // Remove any dropped connections from our list, causing them to be destroyed // They can't just be removed immediately when they're dropped because the ros // thread may still be using them (or more likely their transport) void removeDroppedConnections(); bool onConnectionHeaderReceived(const ConnectionPtr& conn, const Header& header); void tcprosAcceptConnection(const TransportTCPPtr& transport); PollManagerPtr poll_manager_; S_Connection connections_; V_Connection dropped_connections_; boost::mutex connections_mutex_; boost::mutex dropped_connections_mutex_; // The connection ID counter, used to assign unique ID to each inbound or // outbound connection. Access via getNewConnectionID() uint32_t connection_id_counter_; boost::mutex connection_id_counter_mutex_; boost::signals2::connection poll_conn_; TransportTCPPtr tcpserver_transport_; TransportUDPPtr udpserver_transport_; const static int MAX_TCPROS_CONN_QUEUE = 100; // magic }; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/init.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 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 ROSCPP_INIT_H #define ROSCPP_INIT_H #include "ros/forwards.h" #include "ros/spinner.h" #include "common.h" namespace ros { namespace init_options { /** * \brief Flags for ROS initialization */ enum InitOption { /** * Don't install a SIGINT handler. You should install your own SIGINT handler in this * case, to ensure that the node gets shutdown correctly when it exits. */ NoSigintHandler = 1 << 0, /** \brief Anonymize the node name. Adds a random number to the end of your node's name, to make it unique. */ AnonymousName = 1 << 1, /** * \brief Don't broadcast rosconsole output to the /rosout topic */ NoRosout = 1 << 2, }; } typedef init_options::InitOption InitOption; /** @brief ROS initialization function. * * This function will parse any ROS arguments (e.g., topic name * remappings), and will consume them (i.e., argc and argv may be modified * as a result of this call). * * Use this version if you are using the NodeHandle API * * \param argc * \param argv * \param name Name of this node. The name must be a base name, ie. it cannot contain namespaces. * \param options [optional] Options to start the node with (a set of bit flags from \ref ros::init_options) * \throws InvalidNodeNameException If the name passed in is not a valid "base" name * */ ROSCPP_DECL void init(int &argc, char **argv, const std::string& name, uint32_t options = 0); /** * \brief alternate ROS initialization function. * * \param remappings A map<string, string> where each one constitutes a name remapping, or one of the special remappings like __name, __master, __ns, etc. * \param name Name of this node. The name must be a base name, ie. it cannot contain namespaces. * \param options [optional] Options to start the node with (a set of bit flags from \ref ros::init_options) * \throws InvalidNodeNameException If the name passed in is not a valid "base" name */ ROSCPP_DECL void init(const M_string& remappings, const std::string& name, uint32_t options = 0); /** * \brief alternate ROS initialization function. * * \param remappings A vector<pair<string, string> > where each one constitutes a name remapping, or one of the special remappings like __name, __master, __ns, etc. * \param name Name of this node. The name must be a base name, ie. it cannot contain namespaces. * \param options [optional] Options to start the node with (a set of bit flags from \ref ros::init_options) * \throws InvalidNodeNameException If the name passed in is not a valid "base" name */ ROSCPP_DECL void init(const VP_string& remapping_args, const std::string& name, uint32_t options = 0); /** * \brief Returns whether or not ros::init() has been called */ ROSCPP_DECL bool isInitialized(); /** * \brief Returns whether or not ros::shutdown() has been (or is being) called */ ROSCPP_DECL bool isShuttingDown(); /** \brief Enter simple event loop * * This method enters a loop, processing callbacks. This method should only be used * if the NodeHandle API is being used. * * This method is mostly useful when your node does all of its work in * subscription callbacks. It will not process any callbacks that have been assigned to * custom queues. * */ ROSCPP_DECL void spin(); /** \brief Enter simple event loop * * This method enters a loop, processing callbacks. This method should only be used * if the NodeHandle API is being used. * * This method is mostly useful when your node does all of its work in * subscription callbacks. It will not process any callbacks that have been assigned to * custom queues. * * \param spinner a spinner to use to call callbacks. Two default implementations are available, * SingleThreadedSpinner and MultiThreadedSpinner */ ROSCPP_DECL void spin(Spinner& spinner); /** * \brief Process a single round of callbacks. * * This method is useful if you have your own loop running and would like to process * any callbacks that are available. This is equivalent to calling callAvailable() on the * global CallbackQueue. It will not process any callbacks that have been assigned to * custom queues. */ ROSCPP_DECL void spinOnce(); /** * \brief Wait for this node to be shutdown, whether through Ctrl-C, ros::shutdown(), or similar. */ ROSCPP_DECL void waitForShutdown(); /** \brief Check whether it's time to exit. * * ok() becomes false once ros::shutdown() has been called and is finished * * \return true if we're still OK, false if it's time to exit */ ROSCPP_DECL bool ok(); /** * \brief Disconnects everything and unregisters from the master. It is generally not * necessary to call this function, as the node will automatically shutdown when all * NodeHandles destruct. However, if you want to break out of a spin() loop explicitly, * this function allows that. */ ROSCPP_DECL void shutdown(); /** * \brief Request that the node shut itself down from within a ROS thread * * This method signals a ROS thread to call shutdown(). */ ROSCPP_DECL void requestShutdown(); /** * \brief Actually starts the internals of the node (spins up threads, starts the network polling and xmlrpc loops, * connects to internal subscriptions like /clock, starts internal service servers, etc.). * * Usually unnecessary to call manually, as it is automatically called by the creation of the first NodeHandle if * the node has not already been started. If you would like to prevent the automatic shutdown caused by the last * NodeHandle going out of scope, call this before any NodeHandle has been created (e.g. immediately after init()) */ ROSCPP_DECL void start(); /** * \brief Returns whether or not the node has been started through ros::start() */ ROSCPP_DECL bool isStarted(); /** * \brief Returns a pointer to the global default callback queue. * * This is the queue that all callbacks get added to unless a different one is specified, either in the NodeHandle * or in the individual NodeHandle::subscribe()/NodeHandle::advertise()/etc. functions. */ ROSCPP_DECL CallbackQueue* getGlobalCallbackQueue(); /** * \brief searches the command line arguments for the given arg parameter. In case this argument is not found * an empty string is returned. * * \param argc the number of command-line arguments * \param argv the command-line arguments * \param arg argument to search for */ ROSCPP_DECL std::string getROSArg(int argc, const char* const* argv, const std::string& arg); /** * \brief returns a vector of program arguments that do not include any ROS remapping arguments. Useful if you need * to parse your arguments to determine your node name * * \param argc the number of command-line arguments * \param argv the command-line arguments * \param [out] args_out Output args, stripped of any ROS args */ ROSCPP_DECL void removeROSArgs(int argc, const char* const* argv, V_string& args_out); /** * \brief * * \param file the config file path * Returns result */ bool configParse(std::string file); } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/poll_manager.h
/* * 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. */ #ifndef ROSCPP_POLL_MANAGER_H #define ROSCPP_POLL_MANAGER_H #include "forwards.h" #include "poll_set.h" #include "common.h" #include <boost/signals2.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/thread.hpp> namespace ros { class PollManager; typedef boost::shared_ptr<PollManager> PollManagerPtr; typedef boost::signals2::signal<void(void)> VoidSignal; typedef boost::function<void(void)> VoidFunc; class ROSCPP_DECL PollManager { public: static const PollManagerPtr& instance(); PollManager(); ~PollManager(); PollSet& getPollSet() { return poll_set_; } boost::signals2::connection addPollThreadListener(const VoidFunc& func); void removePollThreadListener(boost::signals2::connection c); void start(); void shutdown(); private: void threadFunc(); PollSet poll_set_; volatile bool shutting_down_; VoidSignal poll_signal_; boost::recursive_mutex signal_mutex_; boost::thread thread_; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/topic.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 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 ROSCPP_TOPIC_H #define ROSCPP_TOPIC_H #include "common.h" #include "node_handle.h" #include <boost/shared_ptr.hpp> namespace ros { namespace topic { /** * \brief Internal method, do not use */ ROSCPP_DECL void waitForMessageImpl(SubscribeOptions& ops, const boost::function<bool(void)>& ready_pred, NodeHandle& nh, ros::Duration timeout); template<class M> class SubscribeHelper { public: typedef boost::shared_ptr<M const> MConstPtr; void callback(const MConstPtr& message) { message_ = message; } bool hasMessage() { return static_cast<bool>(message_); } MConstPtr getMessage() { return message_; } private: MConstPtr message_; }; /** * \brief Wait for a single message to arrive on a topic, with timeout * * \param M <template> The message type * \param topic The topic to subscribe on * \param nh The NodeHandle to use to do the subscription * \param timeout The amount of time to wait before returning if no message is received * \return The message. Empty boost::shared_ptr if waitForMessage is interrupted by the node shutting down */ template<class M> boost::shared_ptr<M const> waitForMessage(const std::string& topic, NodeHandle& nh, ros::Duration timeout) { SubscribeHelper<M> helper; SubscribeOptions ops; ops.template init<M>(topic, 1, boost::bind(&SubscribeHelper<M>::callback, &helper, _1)); waitForMessageImpl(ops, boost::bind(&SubscribeHelper<M>::hasMessage, &helper), nh, timeout); return helper.getMessage(); } /** * \brief Wait for a single message to arrive on a topic * * \param M <template> The message type * \param topic The topic to subscribe on * \return The message. Empty boost::shared_ptr if waitForMessage is interrupted by the node shutting down */ template<class M> boost::shared_ptr<M const> waitForMessage(const std::string& topic) { ros::NodeHandle nh; return waitForMessage<M>(topic, nh, ros::Duration()); } /** * \brief Wait for a single message to arrive on a topic, with timeout * * \param M <template> The message type * \param topic The topic to subscribe on * \param timeout The amount of time to wait before returning if no message is received * \return The message. Empty boost::shared_ptr if waitForMessage is interrupted by the node shutting down */ template<class M> boost::shared_ptr<M const> waitForMessage(const std::string& topic, ros::Duration timeout) { ros::NodeHandle nh; return waitForMessage<M>(topic, nh, timeout); } /** * \brief Wait for a single message to arrive on a topic * * \param M <template> The message type * \param topic The topic to subscribe on * \param nh The NodeHandle to use to do the subscription * \return The message. Empty boost::shared_ptr if waitForMessage is interrupted by the node shutting down */ template<class M> boost::shared_ptr<M const> waitForMessage(const std::string& topic, ros::NodeHandle& nh) { return waitForMessage<M>(topic, nh, ros::Duration()); } } // namespace topic } // namespace ros #endif // ROSCPP_TOPIC_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/ros.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 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 ROSCPP_ROS_H #define ROSCPP_ROS_H #include "ros/time.h" #include "ros/rate.h" #include "ros/console.h" #include "ros/assert.h" #include "ros/serialization_protobuffer.h" #include "ros/protobuffer_traits.h" #include "ros/common.h" #include "ros/types.h" #include "ros/node_handle.h" #include "ros/publisher.h" #include "ros/single_subscriber_publisher.h" #include "ros/service_server.h" #include "ros/subscriber.h" #include "ros/service.h" #include "ros/init.h" #include "ros/master.h" #include "ros/this_node.h" #include "ros/param.h" #include "ros/topic.h" #include "ros/names.h" #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/single_subscriber_publisher.h
/* * 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. */ #ifndef ROSCPP_SINGLE_SUBSCRIBER_PUBLISHER_H #define ROSCPP_SINGLE_SUBSCRIBER_PUBLISHER_H #include "ros/forwards.h" #include "ros/serialization.h" #include "common.h" #include <boost/utility.hpp> namespace ros { /** * \brief Allows publication of a message to a single subscriber. Only available inside subscriber connection callbacks */ class ROSCPP_DECL SingleSubscriberPublisher : public boost::noncopyable { public: SingleSubscriberPublisher(const SubscriberLinkPtr& link); ~SingleSubscriberPublisher(); /** * \brief Publish a message on the topic associated with this Publisher. * * This version of publish will allow fast intra-process message-passing in the future, * so you may not mutate the message after it has been passed in here (since it will be * passed directly into a callback function) * */ template<class M> void publish(const boost::shared_ptr<M const>& message) const { publish(*message); } /** * \brief Publish a message on the topic associated with this Publisher. * * This version of publish will allow fast intra-process message-passing in the future, * so you may not mutate the message after it has been passed in here (since it will be * passed directly into a callback function) * */ template<class M> void publish(const boost::shared_ptr<M>& message) const { publish(*message); } /** * \brief Publish a message on the topic associated with this Publisher. */ template<class M> void publish(const M& message) const { using namespace serialization; SerializedMessage m = serializeMessage(message); publish(m); } /** * \brief Returns the topic this publisher publishes on */ std::string getTopic() const; /** * \brief Returns the name of the subscriber node */ std::string getSubscriberName() const; private: void publish(const SerializedMessage& m) const; SubscriberLinkPtr link_; }; } #endif // ROSCPP_PUBLISHER_HANDLE_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/timer_manager.h
/* * 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. */ #ifndef ROSCPP_TIMER_MANAGER_H #define ROSCPP_TIMER_MANAGER_H #include "ros/forwards.h" #include "ros/time.h" #include "ros/file_log.h" #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/condition_variable.hpp> #include "ros/assert.h" #include "ros/callback_queue_interface.h" #include <vector> #include <list> namespace ros { template<class T, class D, class E> class TimerManager { private: struct TimerInfo { int32_t handle; D period; boost::function<void(const E&)> callback; CallbackQueueInterface* callback_queue; WallDuration last_cb_duration; T last_expected; T next_expected; T last_real; bool removed; VoidConstWPtr tracked_object; bool has_tracked_object; // TODO: atomicize boost::mutex waiting_mutex; uint32_t waiting_callbacks; bool oneshot; // debugging info uint32_t total_calls; }; typedef boost::shared_ptr<TimerInfo> TimerInfoPtr; typedef boost::weak_ptr<TimerInfo> TimerInfoWPtr; typedef std::vector<TimerInfoPtr> V_TimerInfo; typedef std::list<int32_t> L_int32; public: TimerManager(); ~TimerManager(); int32_t add(const D& period, const boost::function<void(const E&)>& callback, CallbackQueueInterface* callback_queue, const VoidConstPtr& tracked_object, bool oneshot); void remove(int32_t handle); bool hasPending(int32_t handle); void setPeriod(int32_t handle, const D& period, bool reset=true); static TimerManager& global() { static TimerManager<T, D, E> global; return global; } private: void threadFunc(); bool waitingCompare(int32_t lhs, int32_t rhs); TimerInfoPtr findTimer(int32_t handle); void schedule(const TimerInfoPtr& info); void updateNext(const TimerInfoPtr& info, const T& current_time); V_TimerInfo timers_; boost::mutex timers_mutex_; boost::condition_variable timers_cond_; volatile bool new_timer_; boost::mutex waiting_mutex_; L_int32 waiting_; uint32_t id_counter_; boost::mutex id_mutex_; bool thread_started_; boost::thread thread_; bool quit_; class TimerQueueCallback : public CallbackInterface { public: TimerQueueCallback(TimerManager<T, D, E>* parent, const TimerInfoPtr& info, T last_expected, T last_real, T current_expected) : parent_(parent) , info_(info) , last_expected_(last_expected) , last_real_(last_real) , current_expected_(current_expected) , called_(false) { boost::mutex::scoped_lock lock(info->waiting_mutex); ++info->waiting_callbacks; } ~TimerQueueCallback() { TimerInfoPtr info = info_.lock(); if (info) { boost::mutex::scoped_lock lock(info->waiting_mutex); --info->waiting_callbacks; } } CallResult call() { TimerInfoPtr info = info_.lock(); if (!info) { return Invalid; } { ++info->total_calls; called_ = true; VoidConstPtr tracked; if (info->has_tracked_object) { tracked = info->tracked_object.lock(); if (!tracked) { return Invalid; } } E event; event.last_expected = last_expected_; event.last_real = last_real_; event.current_expected = current_expected_; event.current_real = T::now(); event.profile.last_duration = info->last_cb_duration; WallTime cb_start = WallTime::now(); info->callback(event); WallTime cb_end = WallTime::now(); info->last_cb_duration = cb_end - cb_start; info->last_real = event.current_real; parent_->schedule(info); } return Success; } private: TimerManager<T, D, E>* parent_; TimerInfoWPtr info_; T last_expected_; T last_real_; T current_expected_; bool called_; }; }; template<class T, class D, class E> TimerManager<T, D, E>::TimerManager() : new_timer_(false), id_counter_(0), thread_started_(false), quit_(false) { } template<class T, class D, class E> TimerManager<T, D, E>::~TimerManager() { quit_ = true; { boost::mutex::scoped_lock lock(timers_mutex_); timers_cond_.notify_all(); } if (thread_started_) { thread_.join(); } } template<class T, class D, class E> bool TimerManager<T, D, E>::waitingCompare(int32_t lhs, int32_t rhs) { TimerInfoPtr infol = findTimer(lhs); TimerInfoPtr infor = findTimer(rhs); if (!infol || !infor) { return infol < infor; } return infol->next_expected < infor->next_expected; } template<class T, class D, class E> typename TimerManager<T, D, E>::TimerInfoPtr TimerManager<T, D, E>::findTimer(int32_t handle) { typename V_TimerInfo::iterator it = timers_.begin(); typename V_TimerInfo::iterator end = timers_.end(); for (; it != end; ++it) { if ((*it)->handle == handle) { return *it; } } return TimerInfoPtr(); } template<class T, class D, class E> bool TimerManager<T, D, E>::hasPending(int32_t handle) { boost::mutex::scoped_lock lock(timers_mutex_); TimerInfoPtr info = findTimer(handle); if (!info) { return false; } if (info->has_tracked_object) { VoidConstPtr tracked = info->tracked_object.lock(); if (!tracked) { return false; } } boost::mutex::scoped_lock lock2(info->waiting_mutex); return info->next_expected <= T::now() || info->waiting_callbacks != 0; } template<class T, class D, class E> int32_t TimerManager<T, D, E>::add(const D& period, const boost::function<void(const E&)>& callback, CallbackQueueInterface* callback_queue, const VoidConstPtr& tracked_object, bool oneshot) { TimerInfoPtr info(boost::make_shared<TimerInfo>()); info->period = period; info->callback = callback; info->callback_queue = callback_queue; info->last_expected = T::now(); info->next_expected = info->last_expected + period; info->removed = false; info->has_tracked_object = false; info->waiting_callbacks = 0; info->total_calls = 0; info->oneshot = oneshot; if (tracked_object) { info->tracked_object = tracked_object; info->has_tracked_object = true; } { boost::mutex::scoped_lock lock(id_mutex_); info->handle = id_counter_++; } { boost::mutex::scoped_lock lock(timers_mutex_); timers_.push_back(info); if (!thread_started_) { thread_ = boost::thread(boost::bind(&TimerManager::threadFunc, this)); thread_started_ = true; } { boost::mutex::scoped_lock lock(waiting_mutex_); waiting_.push_back(info->handle); waiting_.sort(boost::bind(&TimerManager::waitingCompare, this, _1, _2)); } new_timer_ = true; timers_cond_.notify_all(); } return info->handle; } template<class T, class D, class E> void TimerManager<T, D, E>::remove(int32_t handle) { CallbackQueueInterface* callback_queue = 0; uint64_t remove_id = 0; { boost::mutex::scoped_lock lock(timers_mutex_); typename V_TimerInfo::iterator it = timers_.begin(); typename V_TimerInfo::iterator end = timers_.end(); for (; it != end; ++it) { const TimerInfoPtr& info = *it; if (info->handle == handle) { info->removed = true; callback_queue = info->callback_queue; remove_id = (uint64_t)info.get(); timers_.erase(it); break; } } { boost::mutex::scoped_lock lock2(waiting_mutex_); // Remove from the waiting list if it's in it L_int32::iterator it = std::find(waiting_.begin(), waiting_.end(), handle); if (it != waiting_.end()) { waiting_.erase(it); } } } if (callback_queue) { callback_queue->removeByID(remove_id); } } template<class T, class D, class E> void TimerManager<T, D, E>::schedule(const TimerInfoPtr& info) { boost::mutex::scoped_lock lock(timers_mutex_); if (info->removed) { return; } updateNext(info, T::now()); { boost::mutex::scoped_lock lock(waiting_mutex_); waiting_.push_back(info->handle); // waitingCompare requires a lock on the timers_mutex_ waiting_.sort(boost::bind(&TimerManager::waitingCompare, this, _1, _2)); } new_timer_ = true; timers_cond_.notify_one(); } template<class T, class D, class E> void TimerManager<T, D, E>::updateNext(const TimerInfoPtr& info, const T& current_time) { if (info->oneshot) { info->next_expected = T(INT_MAX, 999999999); } else { // Protect against someone having called setPeriod() // If the next expected time is already past the current time // don't update it if (info->next_expected <= current_time) { info->last_expected = info->next_expected; info->next_expected += info->period; } // detect time jumping forward, as well as callbacks that are too slow if (info->next_expected + info->period < current_time) { ROS_DEBUG("Time jumped forward by [%f] for timer of period [%f], resetting timer (current=%f, next_expected=%f)", (current_time - info->next_expected).toSec(), info->period.toSec(), current_time.toSec(), info->next_expected.toSec()); info->next_expected = current_time; } } } template<class T, class D, class E> void TimerManager<T, D, E>::setPeriod(int32_t handle, const D& period, bool reset) { boost::mutex::scoped_lock lock(timers_mutex_); TimerInfoPtr info = findTimer(handle); if (!info) { return; } { boost::mutex::scoped_lock lock(waiting_mutex_); if(reset) { info->next_expected = T::now() + period; } // else if some time has elapsed since last cb (called outside of cb) else if( (T::now() - info->last_real) < info->period) { // if elapsed time is greater than the new period // do the callback now if( (T::now() - info->last_real) > period) { info->next_expected = T::now(); } // else, account for elapsed time by using last_real+period else { info->next_expected = info->last_real + period; } } // Else if called in a callback, last_real has not been updated yet => (now - last_real) > period // In this case, let next_expected be updated only in updateNext info->period = period; waiting_.sort(boost::bind(&TimerManager::waitingCompare, this, _1, _2)); } new_timer_ = true; timers_cond_.notify_one(); } template<class T, class D, class E> void TimerManager<T, D, E>::threadFunc() { T current; while (!quit_) { T sleep_end; boost::mutex::scoped_lock lock(timers_mutex_); // detect time jumping backwards if (T::now() < current) { ROSCPP_LOG_DEBUG("Time jumped backward, resetting timers"); current = T::now(); typename V_TimerInfo::iterator it = timers_.begin(); typename V_TimerInfo::iterator end = timers_.end(); for (; it != end; ++it) { const TimerInfoPtr& info = *it; // Timer may have been added after the time jump, so also check if time has jumped past its last call time if (current < info->last_expected) { info->last_expected = current; info->next_expected = current + info->period; } } } current = T::now(); { boost::mutex::scoped_lock waitlock(waiting_mutex_); if (waiting_.empty()) { sleep_end = current + D(0.1); } else { TimerInfoPtr info = findTimer(waiting_.front()); while (!waiting_.empty() && info && info->next_expected <= current) { current = T::now(); //ROS_DEBUG("Scheduling timer callback for timer [%d] of period [%f], [%f] off expected", info->handle, info->period.toSec(), (current - info->next_expected).toSec()); CallbackInterfacePtr cb(boost::make_shared<TimerQueueCallback>(this, info, info->last_expected, info->last_real, info->next_expected)); info->callback_queue->addCallback(cb, (uint64_t)info.get()); waiting_.pop_front(); if (waiting_.empty()) { break; } info = findTimer(waiting_.front()); } if (info) { sleep_end = info->next_expected; } } } while (!new_timer_ && T::now() < sleep_end && !quit_) { // detect backwards jumps in time if (T::now() < current) { ROSCPP_LOG_DEBUG("Time jumped backwards, breaking out of sleep"); break; } current = T::now(); if (current >= sleep_end) { break; } // If we're on simulation time we need to check now() against sleep_end more often than on system time, // since simulation time may be running faster than real time. if (!T::isSystemTime()) { timers_cond_.timed_wait(lock, boost::posix_time::milliseconds(1)); } else { // On system time we can simply sleep for the rest of the wait time, since anything else requiring processing will // signal the condition variable int32_t remaining_time = std::max((int32_t)((sleep_end - current).toSec() * 1000.0f), 1); timers_cond_.timed_wait(lock, boost::posix_time::milliseconds(remaining_time)); } } new_timer_ = false; } } } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_callback_helper.h
/* * 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. */ #ifndef ROSCPP_SERVICE_MESSAGE_HELPER_H #define ROSCPP_SERVICE_MESSAGE_HELPER_H #include "ros/forwards.h" #include "ros/common.h" #include "ros/message.h" #include "ros/message_traits.h" #include "ros/service_traits.h" #include "ros/serialization.h" #include <boost/type_traits/is_base_of.hpp> #include <boost/utility/enable_if.hpp> namespace ros { struct ROSCPP_DECL ServiceCallbackHelperCallParams { SerializedMessage request; SerializedMessage response; boost::shared_ptr<M_string> connection_header; }; template<typename M> inline boost::shared_ptr<M> defaultServiceCreateFunction() { return boost::make_shared<M>(); } template<typename MReq, typename MRes> struct ServiceSpecCallParams { boost::shared_ptr<MReq> request; boost::shared_ptr<MRes> response; boost::shared_ptr<M_string> connection_header; }; /** * \brief Event type for services, ros::ServiceEvent<MReq, MRes>& can be used in your callback instead of MReq&, MRes& * * Useful if you need to retrieve meta-data about the call, such as the full connection header, or the caller's node name */ template<typename MReq, typename MRes> class ServiceEvent { public: typedef MReq RequestType; typedef MRes ResponseType; typedef boost::shared_ptr<RequestType> RequestPtr; typedef boost::shared_ptr<ResponseType> ResponsePtr; typedef boost::function<bool(ServiceEvent<RequestType, ResponseType>&)> CallbackType; static bool call(const CallbackType& cb, ServiceSpecCallParams<RequestType, ResponseType>& params) { ServiceEvent<RequestType, ResponseType> event(params.request, params.response, params.connection_header); return cb(event); } ServiceEvent(const boost::shared_ptr<MReq const>& req, const boost::shared_ptr<MRes>& res, const boost::shared_ptr<M_string>& connection_header) : request_(req) , response_(res) , connection_header_(connection_header) {} /** * \brief Returns a const-reference to the request */ const RequestType& getRequest() const { return *request_; } /** * \brief Returns a non-const reference to the response */ ResponseType& getResponse() const { return *response_; } /** * \brief Returns a reference to the connection header. */ M_string& getConnectionHeader() const { return *connection_header_; } /** * \brief Returns the name of the node which called this service */ const std::string& getCallerName() const { return (*connection_header_)["callerid"]; } private: boost::shared_ptr<RequestType const> request_; boost::shared_ptr<ResponseType> response_; boost::shared_ptr<M_string> connection_header_; }; template<typename MReq, typename MRes> struct ServiceSpec { typedef MReq RequestType; typedef MRes ResponseType; typedef boost::shared_ptr<RequestType> RequestPtr; typedef boost::shared_ptr<ResponseType> ResponsePtr; typedef boost::function<bool(RequestType&, ResponseType&)> CallbackType; static bool call(const CallbackType& cb, ServiceSpecCallParams<RequestType, ResponseType>& params) { return cb(*params.request, *params.response); } }; /** * \brief Abstract base class used by service servers to deal with concrete message types through a common * interface. This is one part of the roscpp API that is \b not fully stable, so overloading this class * is not recommended */ class ROSCPP_DECL ServiceCallbackHelper { public: virtual ~ServiceCallbackHelper() {} virtual bool call(ServiceCallbackHelperCallParams& params) = 0; }; typedef boost::shared_ptr<ServiceCallbackHelper> ServiceCallbackHelperPtr; /** * \brief Concrete generic implementation of ServiceCallbackHelper for any normal service type */ template<typename Spec> class ServiceCallbackHelperT : public ServiceCallbackHelper { public: typedef typename Spec::RequestType RequestType; typedef typename Spec::ResponseType ResponseType; typedef typename Spec::RequestPtr RequestPtr; typedef typename Spec::ResponsePtr ResponsePtr; typedef typename Spec::CallbackType Callback; typedef boost::function<RequestPtr()> ReqCreateFunction; typedef boost::function<ResponsePtr()> ResCreateFunction; ServiceCallbackHelperT(const Callback& callback, const ReqCreateFunction& create_req = // these static casts are legally unnecessary, but // here to keep clang 2.8 from getting confused static_cast<RequestPtr(*)()>(defaultServiceCreateFunction<RequestType>), const ResCreateFunction& create_res = static_cast<ResponsePtr(*)()>(defaultServiceCreateFunction<ResponseType>)) : callback_(callback) , create_req_(create_req) , create_res_(create_res) { } virtual bool call(ServiceCallbackHelperCallParams& params) { namespace ser = serialization; RequestPtr req(create_req_()); ResponsePtr res(create_res_()); ser::deserializeMessage(params.request, *req); ServiceSpecCallParams<RequestType, ResponseType> call_params; call_params.request = req; call_params.response = res; call_params.connection_header = params.connection_header; bool ok = Spec::call(callback_, call_params); params.response = ser::serializeServiceResponse(ok, *res); return ok; } private: Callback callback_; ReqCreateFunction create_req_; ResCreateFunction create_res_; }; } #endif // ROSCPP_SERVICE_MESSAGE_HELPER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_manager.h
/* * 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. */ #ifndef ROSCPP_SERVICE_MANAGER_H #define ROSCPP_SERVICE_MANAGER_H #include "forwards.h" #include "common.h" #include "advertise_service_options.h" #include "service_client_options.h" #include <boost/thread/mutex.hpp> #include <boost/thread/recursive_mutex.hpp> namespace ros { class ServiceManager; typedef boost::shared_ptr<ServiceManager> ServiceManagerPtr; class PollManager; typedef boost::shared_ptr<PollManager> PollManagerPtr; class XMLRPCManager; typedef boost::shared_ptr<XMLRPCManager> XMLRPCManagerPtr; class ConnectionManager; typedef boost::shared_ptr<ConnectionManager> ConnectionManagerPtr; class ROSCPP_DECL ServiceManager { public: static const ServiceManagerPtr& instance(); ServiceManager(); ~ServiceManager(); /** @brief Lookup an advertised service. * * This method iterates over advertised_services, looking for one with name * matching the given topic name. The advertised_services_mutex is locked * during this search. This method is only used internally. * * @param service The service name to look for. * * @returns Pointer to the matching ServicePublication, NULL if none is found. */ ServicePublicationPtr lookupServicePublication(const std::string& service); /** @brief Create a new client to the specified service. If a client to that service already exists, returns the existing one. * * @param service The service to connect to * @param persistent Whether to keep this connection alive for more than one service call * @param request_md5sum The md5sum of the request message * @param response_md5sum The md5sum of the response message * * @returns Shared pointer to the ServiceServerLink, empty shared pointer if none is found. */ ServiceServerLinkPtr createServiceServerLink(const std::string& service, bool persistent, const std::string& request_md5sum, const std::string& response_md5sum, const M_string& header_values); /** @brief Remove the specified service client from our list * * @param client The client to remove */ void removeServiceServerLink(const ServiceServerLinkPtr& client); /** @brief Lookup the host/port of a service. * * @param name The name of the service * @param serv_host OUT -- The host of the service * @param serv_port OUT -- The port of the service */ bool lookupService(const std::string& name, std::string& serv_host, uint32_t& serv_port); /** @brief Unadvertise a service. * * This call unadvertises a service, which must have been previously * advertised, using advertiseService(). * * After this call completes, it is guaranteed that no further * callbacks will be invoked for this service. * * This method can be safely called from within a service callback. * * @param serv_name The service to be unadvertised. * * @return true on successful unadvertisement, false otherwise. */ bool unadvertiseService(const std::string& serv_name); bool advertiseService(const AdvertiseServiceOptions& ops); void start(); void shutdown(); private: bool isServiceAdvertised(const std::string& serv_name); bool unregisterService(const std::string& service); bool isShuttingDown() { return shutting_down_; } L_ServicePublication service_publications_; boost::mutex service_publications_mutex_; L_ServiceServerLink service_server_links_; boost::mutex service_server_links_mutex_; volatile bool shutting_down_; boost::recursive_mutex shutting_down_mutex_; PollManagerPtr poll_manager_; ConnectionManagerPtr connection_manager_; XMLRPCManagerPtr xmlrpc_manager_; }; } // namespace ros #endif // ROSCPP_SERVICE_MANAGER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/transport_subscriber_link.h
/* * 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. */ #ifndef ROSCPP_TRANSPORT_SUBSCRIBER_LINK_H #define ROSCPP_TRANSPORT_SUBSCRIBER_LINK_H #include "common.h" #include "subscriber_link.h" #include <boost/signals2/connection.hpp> namespace ros { /** * \brief SubscriberLink handles broadcasting messages to a single subscriber on a single topic */ class ROSCPP_DECL TransportSubscriberLink : public SubscriberLink { public: TransportSubscriberLink(); virtual ~TransportSubscriberLink(); // bool initialize(const ConnectionPtr& connection); bool handleHeader(const Header& header); const ConnectionPtr& getConnection() { return connection_; } virtual void enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy); virtual void drop(); virtual std::string getTransportType(); virtual std::string getTransportInfo(); private: void onConnectionDropped(const ConnectionPtr& conn); void onHeaderWritten(const ConnectionPtr& conn); void onMessageWritten(const ConnectionPtr& conn); void startMessageWrite(bool immediate_write); bool writing_message_; bool header_written_; ConnectionPtr connection_; boost::signals2::connection dropped_conn_; std::queue<SerializedMessage> outbox_; boost::mutex outbox_mutex_; bool queue_full_; }; typedef boost::shared_ptr<TransportSubscriberLink> TransportSubscriberLinkPtr; } // namespace ros #endif // ROSCPP_TRANSPORT_SUBSCRIBER_LINK_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/forwards.h
/* * 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. */ #ifndef ROSCPP_FORWARDS_H #define ROSCPP_FORWARDS_H #include <string> #include <vector> #include <map> #include <set> #include <list> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <boost/weak_ptr.hpp> #include <boost/function.hpp> #include <ros/time.h> #include <ros/macros.h> #include "exceptions.h" #include "ros/datatypes.h" namespace ros { typedef boost::shared_ptr<void> VoidPtr; typedef boost::weak_ptr<void> VoidWPtr; typedef boost::shared_ptr<void const> VoidConstPtr; typedef boost::weak_ptr<void const> VoidConstWPtr; class Header; class Transport; typedef boost::shared_ptr<Transport> TransportPtr; class TransportTCP; typedef boost::shared_ptr<TransportTCP> TransportTCPPtr; class TransportUDP; typedef boost::shared_ptr<TransportUDP> TransportUDPPtr; class Connection; typedef boost::shared_ptr<Connection> ConnectionPtr; typedef std::set<ConnectionPtr> S_Connection; typedef std::vector<ConnectionPtr> V_Connection; class Publication; typedef boost::shared_ptr<Publication> PublicationPtr; typedef std::vector<PublicationPtr> V_Publication; class SubscriberLink; typedef boost::shared_ptr<SubscriberLink> SubscriberLinkPtr; typedef std::vector<SubscriberLinkPtr> V_SubscriberLink; class Subscription; typedef boost::shared_ptr<Subscription> SubscriptionPtr; typedef boost::weak_ptr<Subscription> SubscriptionWPtr; typedef std::list<SubscriptionPtr> L_Subscription; typedef std::vector<SubscriptionPtr> V_Subscription; typedef std::set<SubscriptionPtr> S_Subscription; class PublisherLink; typedef boost::shared_ptr<PublisherLink> PublisherLinkPtr; typedef std::vector<PublisherLinkPtr> V_PublisherLink; class ServicePublication; typedef boost::shared_ptr<ServicePublication> ServicePublicationPtr; typedef std::list<ServicePublicationPtr> L_ServicePublication; typedef std::vector<ServicePublicationPtr> V_ServicePublication; class ServiceServerLink; typedef boost::shared_ptr<ServiceServerLink> ServiceServerLinkPtr; typedef std::list<ServiceServerLinkPtr> L_ServiceServerLink; class Transport; typedef boost::shared_ptr<Transport> TransportPtr; class NodeHandle; typedef boost::shared_ptr<NodeHandle> NodeHandlePtr; class SingleSubscriberPublisher; typedef boost::function<void(const SingleSubscriberPublisher&)> SubscriberStatusCallback; class CallbackQueue; class CallbackQueueInterface; class CallbackInterface; typedef boost::shared_ptr<CallbackInterface> CallbackInterfacePtr; struct SubscriberCallbacks { SubscriberCallbacks(const SubscriberStatusCallback& connect = SubscriberStatusCallback(), const SubscriberStatusCallback& disconnect = SubscriberStatusCallback(), const VoidConstPtr& tracked_object = VoidConstPtr(), CallbackQueueInterface* callback_queue = 0) : connect_(connect) , disconnect_(disconnect) , callback_queue_(callback_queue) { has_tracked_object_ = false; if (tracked_object) { has_tracked_object_ = true; tracked_object_ = tracked_object; } } SubscriberStatusCallback connect_; SubscriberStatusCallback disconnect_; bool has_tracked_object_; VoidConstWPtr tracked_object_; CallbackQueueInterface* callback_queue_; }; typedef boost::shared_ptr<SubscriberCallbacks> SubscriberCallbacksPtr; /** * \brief Structure passed as a parameter to the callback invoked by a ros::Timer */ struct TimerEvent { Time last_expected; ///< In a perfect world, this is when the last callback should have happened Time last_real; ///< When the last callback actually happened Time current_expected; ///< In a perfect world, this is when the current callback should be happening Time current_real; ///< This is when the current callback was actually called (Time::now() as of the beginning of the callback) struct { WallDuration last_duration; ///< How long the last callback ran for } profile; }; typedef boost::function<void(const TimerEvent&)> TimerCallback; /** * \brief Structure passed as a parameter to the callback invoked by a ros::WallTimer */ struct WallTimerEvent { WallTime last_expected; ///< In a perfect world, this is when the last callback should have happened WallTime last_real; ///< When the last callback actually happened WallTime current_expected; ///< In a perfect world, this is when the current callback should be happening WallTime current_real; ///< This is when the current callback was actually called (Time::now() as of the beginning of the callback) struct { WallDuration last_duration; ///< How long the last callback ran for } profile; }; typedef boost::function<void(const WallTimerEvent&)> WallTimerCallback; class ServiceManager; typedef boost::shared_ptr<ServiceManager> ServiceManagerPtr; class TopicManager; typedef boost::shared_ptr<TopicManager> TopicManagerPtr; class ConnectionManager; typedef boost::shared_ptr<ConnectionManager> ConnectionManagerPtr; class XMLRPCManager; typedef boost::shared_ptr<XMLRPCManager> XMLRPCManagerPtr; class PollManager; typedef boost::shared_ptr<PollManager> PollManagerPtr; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/intraprocess_publisher_link.h
/* * 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. */ #ifndef ROSCPP_INTRAPROCESS_PUBLISHER_LINK_H #define ROSCPP_INTRAPROCESS_PUBLISHER_LINK_H #include "publisher_link.h" #include "common.h" #include <boost/thread/recursive_mutex.hpp> namespace ros { class Subscription; typedef boost::shared_ptr<Subscription> SubscriptionPtr; typedef boost::weak_ptr<Subscription> SubscriptionWPtr; class IntraProcessSubscriberLink; typedef boost::shared_ptr<IntraProcessSubscriberLink> IntraProcessSubscriberLinkPtr; /** * \brief Handles a connection to a single publisher on a given topic. Receives messages from a publisher * and hands them off to its parent Subscription */ class ROSCPP_DECL IntraProcessPublisherLink : public PublisherLink { public: IntraProcessPublisherLink(const SubscriptionPtr& parent, const std::string& xmlrpc_uri, const TransportHints& transport_hints); virtual ~IntraProcessPublisherLink(); void setPublisher(const IntraProcessSubscriberLinkPtr& publisher); virtual std::string getTransportType(); virtual std::string getTransportInfo(); virtual void drop(); /** * \brief Handles handing off a received message to the subscription, where it will be deserialized and called back */ virtual void handleMessage(const SerializedMessage& m, bool ser, bool nocopy); void getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti); private: IntraProcessSubscriberLinkPtr publisher_; bool dropped_; boost::recursive_mutex drop_mutex_; }; typedef boost::shared_ptr<IntraProcessPublisherLink> IntraProcessPublisherLinkPtr; } // namespace ros #endif // ROSCPP_INTRAPROCESS_PUBLISHER_LINK_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/service_client_link.h
/* * 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. */ #ifndef ROSCPP_SERVICE_CLIENT_LINK_H #define ROSCPP_SERVICE_CLIENT_LINK_H #include "ros/common.h" #include <boost/thread/mutex.hpp> #include <boost/shared_array.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/signals2/connection.hpp> #include <queue> namespace ros { class Header; class ServicePublication; typedef boost::weak_ptr<ServicePublication> ServicePublicationWPtr; typedef boost::shared_ptr<ServicePublication> ServicePublicationPtr; class Connection; typedef boost::shared_ptr<Connection> ConnectionPtr; /** * \brief Handles a connection to a single incoming service client. */ class ROSCPP_DECL ServiceClientLink : public boost::enable_shared_from_this<ServiceClientLink> { public: ServiceClientLink(); virtual ~ServiceClientLink(); // bool initialize(const ConnectionPtr& connection); bool handleHeader(const Header& header); /** * \brief Writes a response to the current request. * \param ok Whether the callback was successful or not * \param resp The message response. ServiceClientLink will delete this */ void processResponse(bool ok, const SerializedMessage& res); const ConnectionPtr& getConnection() { return connection_; } private: void onConnectionDropped(const ConnectionPtr& conn); void onHeaderWritten(const ConnectionPtr& conn); void onRequestLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success); void onRequest(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success); void onResponseWritten(const ConnectionPtr& conn); ConnectionPtr connection_; ServicePublicationWPtr parent_; bool persistent_; boost::signals2::connection dropped_conn_; }; typedef boost::shared_ptr<ServiceClientLink> ServiceClientLinkPtr; } // namespace ros #endif // ROSCPP_PUBLISHER_DATA_HANDLER_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/publication.h
/* * 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. */ #ifndef ROSCPP_PUBLICATION_H #define ROSCPP_PUBLICATION_H #include "ros/forwards.h" #include "ros/advertise_options.h" #include "common.h" #include "XmlRpc.h" #include <boost/thread/mutex.hpp> #include <boost/shared_ptr.hpp> #include <boost/shared_array.hpp> #include <vector> namespace ros { class SubscriberLink; typedef boost::shared_ptr<SubscriberLink> SubscriberLinkPtr; typedef std::vector<SubscriberLinkPtr> V_SubscriberLink; enum TransportType { SHARED_MEMORY, SOCKET, BOTH }; /** * \brief A Publication manages an advertised topic */ class ROSCPP_DECL Publication { public: Publication(const std::string &name, const std::string& datatype, const std::string& _md5sum, const std::string& message_definition, size_t max_queue, bool latch, bool has_header); ~Publication(); void addCallbacks(const SubscriberCallbacksPtr& callbacks); void removeCallbacks(const SubscriberCallbacksPtr& callbacks); /** * \brief queues an outgoing message into each of the publishers, so that it gets sent to every subscriber */ bool enqueueMessage(const SerializedMessage& m); /** * \brief returns the max queue size of this publication */ inline size_t getMaxQueue() { return max_queue_; } /** * \brief Get the accumulated stats for this publication */ XmlRpc::XmlRpcValue getStats(); /** * \brief Get the accumulated info for this publication */ void getInfo(XmlRpc::XmlRpcValue& info); /** * \brief Returns whether or not this publication has any subscribers */ bool hasSubscribers(); /** * \brief Returns the number of subscribers this publication has */ uint32_t getNumSubscribers(); TransportType getSubscriberlinksTransport(); void getPublishTypes(bool& serialize, bool& nocopy, const std::type_info& ti); /** * \brief Returns the name of the topic this publication broadcasts to */ const std::string& getName() const { return name_; } /** * \brief Returns the data type of the message published by this publication */ const std::string& getDataType() const { return datatype_; } /** * \brief Returns the md5sum of the message published by this publication */ const std::string& getMD5Sum() const { return md5sum_; } /** * \brief Returns the full definition of the message published by this publication */ const std::string& getMessageDefinition() const { return message_definition_; } /** * \brief Returns the sequence number */ uint32_t getSequence() { return seq_; } bool isLatched() { return latch_; } /** * \brief Adds a publisher to our list */ void addSubscriberLink(const SubscriberLinkPtr& sub_link); /** * \brief Removes a publisher from our list (deleting it if it's the last reference) */ void removeSubscriberLink(const SubscriberLinkPtr& sub_link); /** * \brief Drop this publication. Disconnects all publishers. */ void drop(); /** * \brief Returns if this publication is valid or not */ bool isDropped() { return dropped_; } uint32_t incrementSequence(); size_t getNumCallbacks(); bool isLatching() { return latch_; } void publish(SerializedMessage& m); void processPublishQueue(); bool validateHeader(const Header& h, std::string& error_msg); void setSelfPublished(bool self_published); bool getSelfPublished(); private: void dropAllConnections(); /** * \brief Called when a new peer has connected. Calls the connection callback */ void peerConnect(const SubscriberLinkPtr& sub_link); /** * \brief Called when a peer has disconnected. Calls the disconnection callback */ void peerDisconnect(const SubscriberLinkPtr& sub_link); std::string name_; std::string datatype_; std::string md5sum_; std::string message_definition_; size_t max_queue_; uint32_t seq_; boost::mutex seq_mutex_; typedef std::vector<SubscriberCallbacksPtr> V_Callback; V_Callback callbacks_; boost::mutex callbacks_mutex_; V_SubscriberLink subscriber_links_; // We use a recursive mutex here for the rare case that a publish call causes another one (like in the case of a rosconsole call) boost::mutex subscriber_links_mutex_; bool dropped_; bool latch_; bool has_header_; SerializedMessage last_message_; bool self_published_; uint32_t intraprocess_subscriber_count_; typedef std::vector<SerializedMessage> V_SerializedMessage; V_SerializedMessage publish_queue_; boost::mutex publish_queue_mutex_; }; } #endif // ROSCPP_PUBLICATION_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/transport/transport_tcp.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 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 ROSCPP_TRANSPORT_TCP_H #define ROSCPP_TRANSPORT_TCP_H #include <ros/types.h> #include <ros/transport/transport.h> #include <boost/thread/recursive_mutex.hpp> #include "ros/io.h" #include <ros/common.h> namespace ros { class TransportTCP; typedef boost::shared_ptr<TransportTCP> TransportTCPPtr; class PollSet; /** * \brief TCPROS transport */ class ROSCPP_DECL TransportTCP : public Transport { public: static bool s_use_keepalive_; static bool s_use_ipv6_; public: enum Flags { SYNCHRONOUS = 1<<0, }; TransportTCP(PollSet* poll_set, int flags = 0); virtual ~TransportTCP(); /** * \brief Connect to a remote host. * \param host The hostname/IP to connect to * \param port The port to connect to * \return Whether or not the connection was successful */ bool connect(const std::string& host, int port); /** * \brief Returns the URI of the remote host */ std::string getClientURI(); std::string getLocalIp(); typedef boost::function<void(const TransportTCPPtr&)> AcceptCallback; /** * \brief Start a server socket and listen on a port * \param port The port to listen on * \param backlog defines the maximum length for the queue of pending connections. Identical to the backlog parameter to the ::listen function * \param accept_cb The function to call when a client socket has connected */ bool listen(int port, int backlog, const AcceptCallback& accept_cb); /** * \brief Accept a connection on a server socket. Blocks until a connection is available */ TransportTCPPtr accept(); /** * \brief Returns the port this transport is listening on */ int getServerPort() { return server_port_; } int getLocalPort() { return local_port_; } void setNoDelay(bool nodelay); void setKeepAlive(bool use, uint32_t idle, uint32_t interval, uint32_t count); const std::string& getConnectedHost() { return connected_host_; } int getConnectedPort() { return connected_port_; } // overrides from Transport virtual int32_t read(uint8_t* buffer, uint32_t size); virtual int32_t write(uint8_t* buffer, uint32_t size); virtual void enableWrite(); virtual void disableWrite(); virtual void enableRead(); virtual void disableRead(); virtual void close(); virtual std::string getTransportInfo(); virtual void parseHeader(const Header& header); virtual const char* getType() { return "TCPROS"; } virtual int getSocket() { return sock_; } private: /** * \brief Initializes the assigned socket -- sets it to non-blocking and enables reading */ bool initializeSocket(); bool setNonBlocking(); /** * \brief Set the socket to be used by this transport * \param sock A valid TCP socket * \return Whether setting the socket was successful */ bool setSocket(int sock); void socketUpdate(int events); socket_fd_t sock_; bool closed_; boost::recursive_mutex close_mutex_; bool expecting_read_; bool expecting_write_; bool is_server_; sockaddr_storage server_address_; socklen_t sa_len_; sockaddr_storage local_address_; socklen_t la_len_; int server_port_; int local_port_; AcceptCallback accept_cb_; std::string cached_remote_host_; PollSet* poll_set_; int flags_; std::string connected_host_; int connected_port_; }; } #endif // ROSCPP_TRANSPORT_TCP_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/transport/transport.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 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 ROSCPP_TRANSPORT_H #define ROSCPP_TRANSPORT_H #include <ros/types.h> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <vector> namespace ros { class Transport; typedef boost::shared_ptr<Transport> TransportPtr; class Header; /** * \brief Abstract base class that allows abstraction of the transport type, eg. TCP, shared memory, UDP... */ class Transport : public boost::enable_shared_from_this<Transport> { public: Transport(); virtual ~Transport() {} /** * \brief Read a number of bytes into the supplied buffer. Not guaranteed to actually read that number of bytes. * \param buffer Buffer to read from * \param size Size, in bytes, to read * \return The number of bytes actually read, or -1 if there was an error */ virtual int32_t read(uint8_t* buffer, uint32_t size) = 0; /** * \brief Write a number of bytes from the supplied buffer. Not guaranteed to actually write that number of bytes. * \param buffer Buffer to write from * \param size Size, in bytes, to write * \return The number of bytes actually written, or -1 if there was an error */ virtual int32_t write(uint8_t* buffer, uint32_t size) = 0; /** * \brief Enable writing on this transport. Allows derived classes to, for example, enable write polling for asynchronous sockets */ virtual void enableWrite() = 0; /** * \brief Disable writing on this transport. Allows derived classes to, for example, disable write polling for asynchronous sockets */ virtual void disableWrite() = 0; /** * \brief Enable reading on this transport. Allows derived classes to, for example, enable read polling for asynchronous sockets */ virtual void enableRead() = 0; /** * \brief Disable reading on this transport. Allows derived classes to, for example, disable read polling for asynchronous sockets */ virtual void disableRead() = 0; /** * \brief Close this transport. Once this call has returned, writing on this transport should always return an error. */ virtual void close() = 0; /** * \brief Return a string that details the type of transport (Eg. TCPROS) * \return The stringified transport type */ virtual const char* getType() = 0; typedef boost::function<void(const TransportPtr&)> Callback; /** * \brief Set the function to call when this transport has disconnected, either through a call to close(). Or a disconnect from the remote host. */ void setDisconnectCallback(const Callback& cb) { disconnect_cb_ = cb; } /** * \brief Set the function to call when there is data available to be read by this transport */ void setReadCallback(const Callback& cb) { read_cb_ = cb; } /** * \brief Set the function to call when there is space available to write on this transport */ void setWriteCallback(const Callback& cb) { write_cb_ = cb; } /** * \brief Returns a string description of both the type of transport and who the transport is connected to */ virtual std::string getTransportInfo() = 0; virtual std::string getClientURI() = 0; virtual std::string getLocalIp() = 0; /** * \brief Returns a boolean to indicate if the transport mechanism is reliable or not */ virtual bool requiresHeader() {return true;} /** * \brief Provides an opportunity for transport-specific options to come in through the header */ virtual void parseHeader(const Header& header) { (void)header; } /** * \brief get socket */ virtual int getSocket() = 0; protected: Callback disconnect_cb_; Callback read_cb_; Callback write_cb_; /** * \brief returns true if the transport is allowed to connect to the host passed to it. */ bool isHostAllowed(const std::string &host) const; /** * \brief returns true if this transport is only allowed to talk to localhost */ bool isOnlyLocalhostAllowed() const { return only_localhost_allowed_; } private: bool only_localhost_allowed_; std::vector<std::string> allowed_hosts_; }; } #endif // ROSCPP_TRANSPORT_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/ros/transport/transport_udp.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 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 ROSCPP_TRANSPORT_UDP_H #define ROSCPP_TRANSPORT_UDP_H #include <ros/types.h> #include <ros/transport/transport.h> #include <boost/thread/mutex.hpp> #include "ros/io.h" #include <ros/common.h> namespace ros { class TransportUDP; typedef boost::shared_ptr<TransportUDP> TransportUDPPtr; class PollSet; #define ROS_UDP_DATA0 0 #define ROS_UDP_DATAN 1 #define ROS_UDP_PING 2 #define ROS_UDP_ERR 3 typedef struct TransportUDPHeader { uint32_t connection_id_; uint8_t op_; uint8_t message_id_; uint16_t block_; } TransportUDPHeader; /** * \brief UDPROS transport */ class ROSCPP_DECL TransportUDP : public Transport { public: enum Flags { SYNCHRONOUS = 1<<0, }; TransportUDP(PollSet* poll_set, int flags = 0, int max_datagram_size = 0); virtual ~TransportUDP(); /** * \brief Connect to a remote host. * \param host The hostname/IP to connect to * \param port The port to connect to * \return Whether or not the connection was successful */ bool connect(const std::string& host, int port, int conn_id); /** * \brief Returns the URI of the remote host */ std::string getClientURI(); std::string getLocalIp(); /** * \brief Start a server socket and listen on a port * \param port The port to listen on */ bool createIncoming(int port, bool is_server); /** * \brief Create a connection to a server socket. */ TransportUDPPtr createOutgoing(std::string host, int port, int conn_id, int max_datagram_size); /** * \brief Returns the port this transport is listening on */ int getServerPort() const {return server_port_;} // overrides from Transport virtual int32_t read(uint8_t* buffer, uint32_t size); virtual int32_t write(uint8_t* buffer, uint32_t size); virtual void enableWrite(); virtual void disableWrite(); virtual void enableRead(); virtual void disableRead(); virtual void close(); virtual std::string getTransportInfo(); virtual bool requiresHeader() {return false;} virtual const char* getType() {return "UDPROS";} int getMaxDatagramSize() const {return max_datagram_size_;} virtual int getSocket() { return sock_; } private: /** * \brief Initializes the assigned socket -- sets it to non-blocking and enables reading */ bool initializeSocket(); /** * \brief Set the socket to be used by this transport * \param sock A valid UDP socket * \return Whether setting the socket was successful */ bool setSocket(int sock); void socketUpdate(int events); socket_fd_t sock_; bool closed_; boost::mutex close_mutex_; bool expecting_read_; bool expecting_write_; bool is_server_; sockaddr_in server_address_; sockaddr_in local_address_; int server_port_; int local_port_; std::string cached_remote_host_; PollSet* poll_set_; int flags_; uint32_t connection_id_; uint8_t current_message_id_; uint16_t total_blocks_; uint16_t last_block_; uint32_t max_datagram_size_; uint8_t* data_buffer_; uint8_t* data_start_; uint32_t data_filled_; uint8_t* reorder_buffer_; uint8_t* reorder_start_; TransportUDPHeader reorder_header_; uint32_t reorder_bytes_; }; } #endif // ROSCPP_TRANSPORT_UDP_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/sharedmem_transport/sharedmem_segment.h
/* * 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. */ #ifndef SHAREDMEM_TRANSPORT_SHAREDMEM_SEGMENT_H #define SHAREDMEM_TRANSPORT_SHAREDMEM_SEGMENT_H #include "sharedmem_transport/sharedmem_block.h" #include "ros/message_deserializer.h" #include "ros/subscription_callback_helper.h" #include "ros/forwards.h" #include "ros/datatypes.h" namespace sharedmem_transport { /** * \brief Class for Shared Memory Segment, which is defined to describer the segment * */ class SharedMemorySegment { public: SharedMemorySegment() : _wrote_num(-1) { } virtual ~SharedMemorySegment() { } /** * \brief Init all blocks from publisher, before publisher write fisrt msg * * @param segment: segment pointer * @param queue_size: total block num which needs to be allocated * @param msg_size: single block size which needs to be allocated * @param real_alloc_size: single block size which has been allocated * @param descriptors_pub: descriptors maped address from sharedmem publisher * @param addr_pub: block maped address from sharedmem publisher * Return init result, true or false */ bool 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); /** * \brief Map all blocks from subscriber, before subscriber read first msg * * @param segment: segment pointer * @param queue_size: total block num * @param addr_sub: block maped address from sharedmem subscriber * Return map result, true or false */ bool map_all_blocks(boost::interprocess::managed_shared_memory*& segment, uint32_t queue_size, uint8_t** addr_sub); /** * \brief Write data to block for sharedmem publisher * * @param msg: msg waited to be wrote * @param queue_size: total block num * @param descriptors_pub: descriptors maped address from sharedmem publisher * @param addr_pub: block maped address from sharedmem publisher * @param last_index: index which publisher wrote last * Return write result, true or false */ bool write_data(const ros::SerializedMessage& msg, uint32_t queue_size, SharedMemoryBlock* descriptors_pub, uint8_t** addr_pub, int32_t& last_index); /** * \brief Read data from block for sharedmem subscriber * * @param msg: msg waited to be read * @param last_read_index: index which is used to record last readable block * @param descriptors_sub: descriptors maped address from sharedmem subscriber * @param addr_sub: block maped address from sharedmem subscriber * @param helper: subscription callback helper * @param topic: topic name * @param header_ptr: header pointer * Return read result, true or false */ bool 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); /** * \brief Set _wrote_num, after publisher wrote data to block * * @param wrote_num: block index which has been wrote last */ inline void set_wrote_num(int32_t wrote_num) { boost::interprocess::scoped_lock < boost::interprocess::interprocess_mutex > lock( _wrote_num_mutex); _wrote_num = wrote_num; } /** * \brief Get _wrote_num, when publisher or subscriber needs * * Return block index which has been wrote last */ inline int32_t get_wrote_num() { boost::interprocess::scoped_lock < boost::interprocess::interprocess_mutex > lock( _wrote_num_mutex); return _wrote_num; } private: /** * \brief Reserve writable block according _wrote_num * * @param queue_size: block num * @param descriptors_pub: descriptors maped address from sharedmem publisher * Return block index which is used to record writable block */ int32_t reserve_radical_writable_block(uint32_t queue_size, SharedMemoryBlock* descriptors_pub); /** * \brief Reserve readable block according _wrote_num * * @param descriptors_sub: descriptors maped address from sharedmem subscriber * Return result for reserve readable block, true or false */ bool reserve_radical_readable_block(SharedMemoryBlock* descriptors_sub); private: // Mutex to protect access _wrote_num boost::interprocess::interprocess_mutex _wrote_num_mutex; boost::interprocess::interprocess_condition _wrote_num_cond; int32_t _wrote_num; }; } // namespace sharedmem_transport #endif // SHAREDMEM_TRANSPORT_SHAREDMEM_SEGMENT_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/sharedmem_transport/sharedmem_util.h
/* * 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. */ #ifndef SHAREDMEM_TRANSPORT_SHAREDMEM_UTIL_H #define SHAREDMEM_TRANSPORT_SHAREDMEM_UTIL_H #include "sharedmem_transport/sharedmem_segment.h" namespace sharedmem_transport { typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> CharAllocator; typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> SHMString; /** * \brief Class for SharedMemoryUtil, defines some util functions of shared memory. * 1) create segment, get segment * 2) create segment mgr, get segment mgr * 3) get block descriptors * 4) remove segment */ class SharedMemoryUtil { public: SharedMemoryUtil() { } virtual ~SharedMemoryUtil() { } /** * \brief Get segment pointer, according to topic name * * @param topic_name: topic name * Return segment pointer */ bool init_sharedmem(const char* topic_name, boost::interprocess::managed_shared_memory*& segment, SharedMemorySegment*& _segment_mgr, SharedMemoryBlock*& _descriptors_sub, uint32_t& queue_size); /** * \brief Get segment pointer, according to topic name * * @param topic_name: topic name * Return segment pointer */ boost::interprocess::managed_shared_memory* get_segment(const char* topic_name); /** * \brief Create segment, according to topic name and segment size * * @param topic_name: topic name * @param segment_size: segment size * Return segment pointer */ boost::interprocess::managed_shared_memory* create_segment(const char* topic_name, uint64_t segment_size); /** * \brief Get segment manager, according to segment pointer * * @param segment: segment pointer * Return segment manager pointer */ SharedMemorySegment* get_segment_mgr(boost::interprocess::managed_shared_memory*& segment); /** * \brief Create segment manager, according to segment pointer * * @param segment: segment pointer * Return segment manager pointer */ SharedMemorySegment* create_segment_mgr(boost::interprocess::managed_shared_memory*& segment); /** * \brief Remove segment, according to segment name * * @param topic_name: topic name * Return result for remove segment */ bool remove_segment(const char* topic_name); /** * \brief save datatype to shm * * @param segment: managed shared memory * @param content: save content */ void set_datatype(boost::interprocess::managed_shared_memory*& segment, std::string content); /** * \brief get datatype from shm * * @param segment: managed shared memory * Return result for datatype */ std::string get_datatype(boost::interprocess::managed_shared_memory*& segment); /** * \brief save md5sum to shm * * @param segment: managed shared memory * @param content: save content */ void set_md5sum(boost::interprocess::managed_shared_memory*& segment, std::string content); /** * \brief get md5sum from shm * * @param segment: managed shared memory * Return result for md5sum */ std::string get_md5sum(boost::interprocess::managed_shared_memory*& segment); /** * \brief save message_definition to shm * * @param segment: managed shared memory * @param content: save content */ void set_msg_def(boost::interprocess::managed_shared_memory*& segment, std::string content); /** * \brief get message_definition from shm * * @param segment: managed shared memory * Return result for message_definition */ std::string get_msg_def(boost::interprocess::managed_shared_memory*& segment); private: /** * \brief save object field to shm * * @param segment: managed shared memory * @param string_name: object field * @param string_content: save content */ void set_segment_string(boost::interprocess::managed_shared_memory*& segment, std::string string_name, std::string string_content); /** * \brief save object field to shm * * @param segment: managed shared memory * @param string_name: object field * Return result for object field */ std::string get_segment_string(boost::interprocess::managed_shared_memory*& segment, std::string string_name); /** * \brief Get segment name, according to topic name * * @param topic_name: topic name * @param segment_name: segment name */ void get_segment_name(const char* topic_name, char* segment_name); /** * \brief Replace all old_char with new_char in src * * @param src: string which needs to replace * @param old_char: char which is replaced * @param new_char: char which is used to replace * Return string which has been replaced */ char* replace_all(char* src, char old_char, char new_char); }; } // namespace sharedmem_transport #endif // SHAREDMEM_TRANSPORT_SHAREDMEM_UTIL_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/sharedmem_transport/sharedmem_block.h
/* * 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. */ #ifndef SHAREDMEM_TRANSPORT_SHAREDMEM_BLOCK_H #define SHAREDMEM_TRANSPORT_SHAREDMEM_BLOCK_H #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/interprocess_condition.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <boost/interprocess/containers/string.hpp> #include "ros/message.h" #include "ros/serialization.h" #include "ros/init.h" #include <time.h> #include <signal.h> #include <setjmp.h> #include <inttypes.h> #include "ros/forwards.h" #include "ros/message_deserializer.h" #include "ros/subscription_callback_helper.h" #include "ros/config_comm.h" namespace sharedmem_transport { const float ROS_SHM_BLOCK_SIZE_RATIO = 1.5; // Allocated size compared to msg size for each block, default 1.5 const int ROS_SHM_UTIL_SEGMENT_NAME_SIZE = 1000; // Util segment name temp size const int32_t ROS_SHM_SEGMENT_WROTE_NUM = -2; // Reallocated flag const uint64_t ROS_SHM_BLOCK_MAX_SIZE = 12000000; // Block max size, Bit const uint64_t ROS_SHM_BLOCK_SIZE = 2000000; // Block size, Bit const uint64_t ROS_SHM_SEGMENT_SIZE = 3000000; // Segment size, Bit const uint32_t ROS_SHM_BLOCK_MUTEX_TIMEOUT_SEC = 1; // Timeout for block mutex, sec /** * \brief Class for Shared Memory Block, which is defined to describer the block. * */ class SharedMemoryBlock { public: SharedMemoryBlock(); SharedMemoryBlock(bool wf, uint32_t rc, uint32_t ms, uint32_t as); virtual ~SharedMemoryBlock() { } /** * \brief Try reserve block for write * * Return result for try, true or false */ bool try_reserve_for_radical_write(); /** * \brief Try reserve block for read * * Return result for try, true or false */ bool try_reserve_for_radical_read(); /** * \brief Release reserve block for write * */ void release_reserve_for_radical_write(); /** * \brief Release reserve block for read * */ void release_reserve_for_radical_read(); /** * \brief Write to block * * @param dest: block address * @param msg: msg waited to be wrote * Return write result, true or false */ bool write_to_block(uint8_t* dest, const ros::SerializedMessage& msg); /** * \brief Read from block * * @param src: block address * @param msg: msg waited to be deserialized to * @param helper: subscription callback helper * @param header_ptr: header pointer * Return read result, true or false */ bool read_from_block(uint8_t* src, ros::VoidConstPtr& msg, ros::SubscriptionCallbackHelperPtr& helper, ros::M_stringPtr& header_ptr); /** * \brief Get real alloc_size * * @param real_alloc_size: alloc size which block is allocated */ inline void get_alloc_size(uint64_t& real_alloc_size) { real_alloc_size = _alloc_size; } private: /** * \brief Serialize msg to block * * @param dest: block address * @param msg: msg waited to be serialized * Return serialize result, true or false */ inline bool serialize(uint8_t* dest, const ros::SerializedMessage& msg) { ROS_DEBUG("Serialize start!!!"); { // Check size msg, before serialize _msg_size = msg.num_bytes - 4; if (_msg_size >= _alloc_size) { ROS_WARN("Msg size overflows the block, serialize failed"); return false; } // Serialize msg to block ROS_DEBUG("Serialising to %p, %" PRIu64 " Bit", dest, _msg_size); memcpy(dest, msg.message_start, _msg_size); } ROS_DEBUG("Serialize end!!!"); return true; } private: // Mutex to protect access to _writing_flag, _reading_count boost::interprocess::interprocess_mutex _write_read_mutex; // When use conservative mechanism, publisher notified subscribers after writing msg boost::interprocess::interprocess_condition _read_cond; bool _writing_flag; uint32_t _reading_count; uint64_t _msg_size; uint64_t _alloc_size; }; } // namespace sharedmem_transport #endif // SHAREDMEM_TRANSPORT_SHAREDMEM_BLOCK_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/sharedmem_transport/sharedmem_publisher_impl.h
/* * 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. */ #ifndef SHAREDMEM_TRANSPORT_SHAREDMEM_PUBLISHER_IMPL_H #define SHAREDMEM_TRANSPORT_SHAREDMEM_PUBLISHER_IMPL_H #include "roscpp/SharedMemoryRegisterSegment.h" #include "sharedmem_transport/sharedmem_util.h" #include "ros/serialization.h" namespace sharedmem_transport { /** * \brief Class for SharedMemoryPublisherImpl, which implements basic functions * for SharedMemoryPublisher. * */ class SharedMemoryPublisherImpl { public: SharedMemoryPublisherImpl(); virtual ~SharedMemoryPublisherImpl(); /** * \brief Create topic segment when pulish first msg * * @param topic: topic name * @param index: index which publish_fn needs * @param queue_size: block num * @param msg_size: msg size * @param real_alloc_size: alloc size * @param datatype: datatype * @param md5sum: md5sum * @param msg_def: msg_def * Return result for create topic segment, true or false; */ bool 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); /** * \brief Publish msg * * @param message: message which will be published * @param queue_size: block num * @param sub_num: num of subscribers which needs to read the block * @param first_run: reallocated flag */ void publish_msg(const ros::SerializedMessage& message, uint32_t queue_size, bool& first_run) { // Publish msg to shared memory int32_t last_index = 0; if (!_segment_mgr->write_data(message, queue_size, _descriptors_pub, _addr_pub, last_index)) { ROS_WARN("Publish message failed"); if (last_index == ROS_SHM_SEGMENT_WROTE_NUM) { first_run = true; } } } private: /** * \brief Check if size ratio is valid * * Return result for size ratio, true or false */ bool check_size_ratio(); boost::interprocess::managed_shared_memory* _segment; SharedMemorySegment* _segment_mgr; SharedMemoryBlock* _descriptors_pub; uint8_t** _addr_pub; }; } // namespace sharedmem_transport #endif // SHAREDMEM_TRANSPORT_SHAREDMEM_PUBLISHER_IMPL_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/discovery/participant.h
/* * 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. */ #ifndef ROSCPP_DISCOVERY_PARTICIPANT_H #define ROSCPP_DISCOVERY_PARTICIPANT_H #include <inttypes.h> #include <functional> #include <string> #include <vector> #include <mutex> #include <fastrtps/participant/Participant.h> #include <fastrtps/attributes/ParticipantAttributes.h> #include <fastrtps/attributes/PublisherAttributes.h> #include <fastrtps/publisher/Publisher.h> #include <fastrtps/publisher/PublisherListener.h> #include <fastrtps/attributes/SubscriberAttributes.h> #include <fastrtps/subscriber/Subscriber.h> #include <fastrtps/subscriber/SubscriberListener.h> #include <fastrtps/subscriber/SampleInfo.h> #include <fastrtps/Domain.h> #include <fastrtps/utils/eClock.h> #include "MetaMessagePubSubTypes.h" #include "MetaMessage.h" namespace ros { typedef std::function<void (const std::string&)> user_callback; class Listener : public eprosima::fastrtps::SubscriberListener { public: Listener(const eprosima::fastrtps::rtps::GUID_t &guid) : _local_publisher_guid(guid) {} ~Listener() {} void onSubscriptionMatched(eprosima::fastrtps::Subscriber* /*sub*/, eprosima::fastrtps::MatchingInfo& /*info*/) {} void onNewDataMessage(eprosima::fastrtps::Subscriber* sub) { eprosima::fastrtps::SampleInfo_t m_info; eprosima::fastrtps::SubscriberAttributes attr = sub->getAttributes(); MetaMessage m; if (sub->takeNextData((void*)&m, &m_info) && m_info.sampleKind == eprosima::fastrtps::ALIVE) { if (_local_publisher_guid == m_info.sample_identity.writer_guid()) { return; } std::lock_guard<std::mutex> lock(_internal_mutex); if (_meta_callback) { _meta_callback(m.data()); } } } bool register_callback(user_callback cb) { _meta_callback = cb; return true; } private: eprosima::fastrtps::rtps::GUID_t _local_publisher_guid; std::mutex _internal_mutex; user_callback _meta_callback; }; class Participant { public: Participant(const std::string& name) : _inited(false), _name(name), _participant(nullptr), _meta_publisher(nullptr), _meta_subscriber(nullptr), _meta_listener(nullptr) {} ~Participant() { if (_participant) { Domain::removeParticipant(_participant); } if (_meta_listener) { delete _meta_listener; } } bool init(user_callback cb); bool init_py(); void cache_msg(const std::string& msg); std::string read_msg(); void send(const std::string& message) { if (_meta_publisher) { MetaMessage m; m.data(message); _meta_publisher->write((void*)&m); } } private: bool _inited; std::string _name; eprosima::fastrtps::Participant* _participant; std::deque<std::string> _unread_msg; std::mutex _msg_lock; std::condition_variable _msg_cond; std::string _meta_topic_name; eprosima::fastrtps::Publisher * _meta_publisher; eprosima::fastrtps::Subscriber * _meta_subscriber; Listener* _meta_listener; eprosima::fastrtps::PublisherListener _pub_listener; ::MetaMessagePubSubType _type; }; } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/discovery/MetaMessage.h
// 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.h * This header file contains the declaration of the described types in the IDL file. * * This file was generated by the tool gen. */ #ifndef _MetaMessage_H_ #define _MetaMessage_H_ // TODO Poner en el contexto. #include <stdint.h> #include <array> #include <string> #include <vector> #if defined(_WIN32) #if defined(EPROSIMA_USER_DLL_EXPORT) #define eProsima_user_DllExport __declspec( dllexport ) #else #define eProsima_user_DllExport #endif #else #define eProsima_user_DllExport #endif #if defined(_WIN32) #if defined(EPROSIMA_USER_DLL_EXPORT) #if defined(MetaMessage_SOURCE) #define MetaMessage_DllAPI __declspec( dllexport ) #else #define MetaMessage_DllAPI __declspec( dllimport ) #endif // MetaMessage_SOURCE #else #define MetaMessage_DllAPI #endif #else #define MetaMessage_DllAPI #endif // _WIN32 namespace eprosima { namespace fastcdr { class Cdr; } } /*! * @brief This class represents the structure MetaMessage defined by the user in the IDL file. * @ingroup METAMESSAGE */ class MetaMessage { public: /*! * @brief Default constructor. */ eProsima_user_DllExport MetaMessage(); /*! * @brief Default destructor. */ eProsima_user_DllExport ~MetaMessage(); /*! * @brief Copy constructor. * @param x Reference to the object MetaMessage that will be copied. */ eProsima_user_DllExport MetaMessage(const MetaMessage &x); /*! * @brief Move constructor. * @param x Reference to the object MetaMessage that will be copied. */ eProsima_user_DllExport MetaMessage(MetaMessage &&x); /*! * @brief Copy assignment. * @param x Reference to the object MetaMessage that will be copied. */ eProsima_user_DllExport MetaMessage& operator=(const MetaMessage &x); /*! * @brief Move assignment. * @param x Reference to the object MetaMessage that will be copied. */ eProsima_user_DllExport MetaMessage& operator=(MetaMessage &&x); /*! * @brief This function sets a value in member message_id * @param _message_id New value for member message_id */ inline eProsima_user_DllExport void message_id(uint32_t _message_id) { m_message_id = _message_id; } /*! * @brief This function returns the value of member message_id * @return Value of member message_id */ inline eProsima_user_DllExport uint32_t message_id() const { return m_message_id; } /*! * @brief This function returns a reference to member message_id * @return Reference to member message_id */ inline eProsima_user_DllExport uint32_t& message_id() { return m_message_id; } /*! * @brief This function copies the value in member data * @param _data New value to be copied in member data */ inline eProsima_user_DllExport void data(const std::string &_data) { m_data = _data; } /*! * @brief This function moves the value in member data * @param _data New value to be moved in member data */ inline eProsima_user_DllExport void data(std::string &&_data) { m_data = std::move(_data); } /*! * @brief This function returns a constant reference to member data * @return Constant reference to member data */ inline eProsima_user_DllExport const std::string& data() const { return m_data; } /*! * @brief This function returns a reference to member data * @return Reference to member data */ inline eProsima_user_DllExport std::string& data() { return m_data; } /*! * @brief This function returns the maximum serialized size of an object * depending on the buffer alignment. * @param current_alignment Buffer alignment. * @return Maximum serialized size. */ eProsima_user_DllExport static size_t getMaxCdrSerializedSize(size_t current_alignment = 0); /*! * @brief This function returns the serialized size of a data depending on the buffer alignment. * @param data Data which is calculated its serialized size. * @param current_alignment Buffer alignment. * @return Serialized size. */ eProsima_user_DllExport static size_t getCdrSerializedSize(const MetaMessage& data, size_t current_alignment = 0); /*! * @brief This function serializes an object using CDR serialization. * @param cdr CDR serialization object. */ eProsima_user_DllExport void serialize(eprosima::fastcdr::Cdr &cdr) const; /*! * @brief This function deserializes an object using CDR serialization. * @param cdr CDR serialization object. */ eProsima_user_DllExport void deserialize(eprosima::fastcdr::Cdr &cdr); /*! * @brief This function returns the maximum serialized size of the Key of an object * depending on the buffer alignment. * @param current_alignment Buffer alignment. * @return Maximum serialized size. */ eProsima_user_DllExport static size_t getKeyMaxCdrSerializedSize(size_t current_alignment = 0); /*! * @brief This function tells you if the Key has been defined for this type */ eProsima_user_DllExport static bool isKeyDefined(); /*! * @brief This function serializes the key members of an object using CDR serialization. * @param cdr CDR serialization object. */ eProsima_user_DllExport void serializeKey(eprosima::fastcdr::Cdr &cdr) const; private: uint32_t m_message_id; std::string m_data; }; #endif // _MetaMessage_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/include/discovery/MetaMessagePubSubTypes.h
// 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.h * This header file contains the declaration of the serialization functions. * * This file was generated by the tool fastcdrgen. */ #ifndef _METAMESSAGE_PUBSUBTYPES_H_ #define _METAMESSAGE_PUBSUBTYPES_H_ #include <fastrtps/TopicDataType.h> using namespace eprosima::fastrtps; #include "MetaMessage.h" /*! * @brief This class represents the TopicDataType of the type MetaMessage defined by the user in the IDL file. * @ingroup METAMESSAGE */ class MetaMessagePubSubType : public TopicDataType { public: typedef MetaMessage type; MetaMessagePubSubType(); virtual ~MetaMessagePubSubType(); bool serialize(void *data, SerializedPayload_t *payload); bool deserialize(SerializedPayload_t *payload, void *data); std::function<uint32_t()> getSerializedSizeProvider(void* data); bool getKey(void *data, InstanceHandle_t *ihandle); void* createData(); void deleteData(void * data); MD5 m_md5; unsigned char* m_keyBuffer; }; #endif // _MetaMessage_PUBSUBTYPE_H_
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/test_node/talker.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. */ // Simple talker demo that published std_msgs/Strings messages // to the 'chatter' topic #include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> int main(int argc, char **argv) { ros::init(argc, argv, "talker", ros::init_options::AnonymousName); ros::NodeHandle n; ros::Publisher chatter_pub = n.advertise<std_msgs::String>("/chatter", 10); int count = 0; ros::Rate loop_rate(10); while (ros::ok()) { std_msgs::String msg; std::stringstream ss; ss << "Hello World " << count; msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str()); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/test_node/listener.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. */ // Simple talker demo that listens to std_msgs/Strings published // to the 'chatter' topic #include "ros/ros.h" #include "std_msgs/String.h" ros::Subscriber _sub; void chatterCallback(const std_msgs::String msg) { ROS_INFO_STREAM("I heard:" << msg.data); } void fun(ros::NodeHandle n) { _sub = n.subscribe("/chatter", 10, chatterCallback); } int main(int argc, char **argv) { ros::init(argc, argv, "listener", ros::init_options::AnonymousName); ros::NodeHandle n; fun(n); ros::spin(); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/srv/SetLoggerLevel.srv
string logger string level ---
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/srv/SharedMemoryRegisterSegment.srv
string topic --- int32 result
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/srv/GetLoggers.srv
--- Logger[] loggers
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/srv/Empty.srv
---
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/message_deserializer.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/message_deserializer.h" #include "ros/subscription_callback_helper.h" #include <ros/console.h> namespace ros { MessageDeserializer::MessageDeserializer(const SubscriptionCallbackHelperPtr& helper, const SerializedMessage& m, const boost::shared_ptr<M_string>& connection_header) : helper_(helper) , serialized_message_(m) , connection_header_(connection_header) { if (serialized_message_.message && *serialized_message_.type_info != helper->getTypeInfo()) { serialized_message_.message.reset(); } } VoidConstPtr MessageDeserializer::deserialize() { boost::mutex::scoped_lock lock(mutex_); if (msg_) { return msg_; } if (serialized_message_.message) { msg_ = serialized_message_.message; return msg_; } if (!serialized_message_.buf && serialized_message_.num_bytes > 0) { // If the buffer has been reset it means we tried to deserialize and failed return VoidConstPtr(); } try { SubscriptionCallbackHelperDeserializeParams params; params.buffer = serialized_message_.message_start; params.length = serialized_message_.num_bytes - (serialized_message_.message_start - serialized_message_.buf.get()); params.connection_header = connection_header_; msg_ = helper_->deserialize(params); } catch (std::exception& e) { ROS_ERROR("Exception thrown when deserializing message of length [%d] from [%s]: %s", (uint32_t)serialized_message_.num_bytes, (*connection_header_)["callerid"].c_str(), e.what()); } serialized_message_.buf.reset(); return msg_; } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service_publication.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_publication.h" #include "ros/service_client_link.h" #include "ros/connection.h" #include "ros/callback_queue_interface.h" #include <boost/bind.hpp> #include <std_msgs/String.h> namespace ros { ServicePublication::ServicePublication(const std::string& name, const std::string &md5sum, const std::string& data_type, const std::string& request_data_type, const std::string& response_data_type, const ServiceCallbackHelperPtr& helper, CallbackQueueInterface* callback_queue, const VoidConstPtr& tracked_object) : name_(name) , md5sum_(md5sum) , data_type_(data_type) , request_data_type_(request_data_type) , response_data_type_(response_data_type) , helper_(helper) , dropped_(false) , callback_queue_(callback_queue) , has_tracked_object_(false) , tracked_object_(tracked_object) { if (tracked_object) { has_tracked_object_ = true; } } ServicePublication::~ServicePublication() { drop(); } void ServicePublication::drop() { // grab a lock here, to ensure that no subscription callback will // be invoked after we return { boost::mutex::scoped_lock lock(client_links_mutex_); dropped_ = true; } dropAllConnections(); callback_queue_->removeByID((uint64_t)this); } class ServiceCallback : public CallbackInterface { public: ServiceCallback(const ServiceCallbackHelperPtr& helper, const boost::shared_array<uint8_t>& buf, size_t num_bytes, const ServiceClientLinkPtr& link, bool has_tracked_object, const VoidConstWPtr& tracked_object) : helper_(helper) , buffer_(buf) , num_bytes_(num_bytes) , link_(link) , has_tracked_object_(has_tracked_object) , tracked_object_(tracked_object) { } virtual CallResult call() { if (link_->getConnection()->isDropped()) { return Invalid; } VoidConstPtr tracker; if (has_tracked_object_) { tracker = tracked_object_.lock(); if (!tracker) { SerializedMessage res = serialization::serializeServiceResponse<uint32_t>(false, 0); link_->processResponse(false, res); return Invalid; } } ServiceCallbackHelperCallParams params; params.request = SerializedMessage(buffer_, num_bytes_); params.connection_header = link_->getConnection()->getHeader().getValues(); try { bool ok = helper_->call(params); if (ok != 0) { link_->processResponse(true, params.response); } else { SerializedMessage res = serialization::serializeServiceResponse<uint32_t>(false, 0); link_->processResponse(false, res); } } catch (std::exception& e) { ROS_ERROR("Exception thrown while processing service call: %s", e.what()); std_msgs::String error_string; error_string.data = e.what(); SerializedMessage res = serialization::serializeServiceResponse(false, error_string); link_->processResponse(false, res); return Invalid; } return Success; } private: ServiceCallbackHelperPtr helper_; boost::shared_array<uint8_t> buffer_; uint32_t num_bytes_; ServiceClientLinkPtr link_; bool has_tracked_object_; VoidConstWPtr tracked_object_; }; void ServicePublication::processRequest(boost::shared_array<uint8_t> buf, size_t num_bytes, const ServiceClientLinkPtr& link) { CallbackInterfacePtr cb(boost::make_shared<ServiceCallback>(helper_, buf, num_bytes, link, has_tracked_object_, tracked_object_)); callback_queue_->addCallback(cb, (uint64_t)this); } void ServicePublication::addServiceClientLink(const ServiceClientLinkPtr& link) { boost::mutex::scoped_lock lock(client_links_mutex_); client_links_.push_back(link); } void ServicePublication::removeServiceClientLink(const ServiceClientLinkPtr& link) { boost::mutex::scoped_lock lock(client_links_mutex_); V_ServiceClientLink::iterator it = std::find(client_links_.begin(), client_links_.end(), link); if (it != client_links_.end()) { client_links_.erase(it); } } void ServicePublication::dropAllConnections() { // Swap our client_links_ 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 client_links_ mutex V_ServiceClientLink local_links; { boost::mutex::scoped_lock lock(client_links_mutex_); local_links.swap(client_links_); } for (V_ServiceClientLink::iterator i = local_links.begin(); i != local_links.end(); ++i) { (*i)->getConnection()->drop(Connection::Destructing); } } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/network.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 "config.h" #include "ros/network.h" #include "ros/file_log.h" #include "ros/exceptions.h" #include "ros/io.h" // cross-platform headers needed #include <ros/console.h> #include <ros/assert.h> #ifdef HAVE_IFADDRS_H #include <ifaddrs.h> #endif #include <boost/lexical_cast.hpp> namespace ros { namespace network { std::string g_host; uint16_t g_tcpros_server_port = 0; const std::string& getHost() { return g_host; } bool splitURI(const std::string& uri, std::string& host, uint32_t& port) { // skip over the protocol if it's there if (uri.substr(0, 7) == std::string("http://")) host = uri.substr(7); else if (uri.substr(0, 9) == std::string("rosrpc://")) host = uri.substr(9); // split out the port std::string::size_type colon_pos = host.find_first_of(":"); if (colon_pos == std::string::npos) return false; std::string port_str = host.substr(colon_pos+1); std::string::size_type slash_pos = port_str.find_first_of("/"); if (slash_pos != std::string::npos) port_str = port_str.erase(slash_pos); port = atoi(port_str.c_str()); host = host.erase(colon_pos); return true; } uint16_t getTCPROSPort() { return g_tcpros_server_port; } static bool isPrivateIP(const char *ip) { bool b = !strncmp("192.168", ip, 7) || !strncmp("10.", ip, 3) || !strncmp("169.254", ip, 7); return b; } std::string determineHost() { std::string ip_env; // First, did the user set ROS_HOSTNAME? if ( get_environment_variable(ip_env, "ROS_HOSTNAME")) { ROSCPP_LOG_DEBUG( "determineIP: using value of ROS_HOSTNAME:%s:", ip_env.c_str()); if (ip_env.size() == 0) { ROS_WARN("invalid ROS_HOSTNAME (an empty string)"); } return ip_env; } // Second, did the user set ROS_IP? if ( get_environment_variable(ip_env, "ROS_IP")) { ROSCPP_LOG_DEBUG( "determineIP: using value of ROS_IP:%s:", ip_env.c_str()); if (ip_env.size() == 0) { ROS_WARN("invalid ROS_IP (an empty string)"); } return ip_env; } // Third, try the hostname char host[1024]; memset(host,0,sizeof(host)); if(gethostname(host,sizeof(host)-1) != 0) { ROS_ERROR("determineIP: gethostname failed"); } // We don't want localhost to be our ip else if(strlen(host) && strcmp("localhost", host)) { return std::string(host); } // Fourth, fall back on interface search, which will yield an IP address #ifdef HAVE_IFADDRS_H struct ifaddrs *ifa = NULL, *ifp = NULL; int rc; if ((rc = getifaddrs(&ifp)) < 0) { ROS_FATAL("error in getifaddrs: [%s]", strerror(rc)); ROS_BREAK(); } char preferred_ip[200] = {0}; for (ifa = ifp; ifa; ifa = ifa->ifa_next) { char ip_[200]; socklen_t salen; if (!ifa->ifa_addr) continue; // evidently this interface has no ip address if (ifa->ifa_addr->sa_family == AF_INET) salen = sizeof(struct sockaddr_in); else if (ifa->ifa_addr->sa_family == AF_INET6) salen = sizeof(struct sockaddr_in6); else continue; if (getnameinfo(ifa->ifa_addr, salen, ip_, sizeof(ip_), NULL, 0, NI_NUMERICHOST) < 0) { ROSCPP_LOG_DEBUG( "getnameinfo couldn't get the ip of interface [%s]", ifa->ifa_name); continue; } //ROS_INFO( "ip of interface [%s] is [%s]", ifa->ifa_name, ip); // prefer non-private IPs over private IPs if (!strcmp("127.0.0.1", ip_) || strchr(ip_,':')) continue; // ignore loopback unless we have no other choice if (ifa->ifa_addr->sa_family == AF_INET6 && !preferred_ip[0]) strcpy(preferred_ip, ip_); else if (isPrivateIP(ip_) && !preferred_ip[0]) strcpy(preferred_ip, ip_); else if (!isPrivateIP(ip_) && (isPrivateIP(preferred_ip) || !preferred_ip[0])) strcpy(preferred_ip, ip_); } freeifaddrs(ifp); if (!preferred_ip[0]) { ROS_ERROR( "Couldn't find a preferred IP via the getifaddrs() call; I'm assuming that your IP " "address is 127.0.0.1. This should work for local processes, " "but will almost certainly not work if you have remote processes." "Report to the ROS development team to seek a fix."); return std::string("127.0.0.1"); } ROSCPP_LOG_DEBUG( "preferred IP is guessed to be %s", preferred_ip); return std::string(preferred_ip); #else // @todo Fix IP determination in the case where getifaddrs() isn't // available. ROS_ERROR( "You don't have the getifaddrs() call; I'm assuming that your IP " "address is 127.0.0.1. This should work for local processes, " "but will almost certainly not work if you have remote processes." "Report to the ROS development team to seek a fix."); return std::string("127.0.0.1"); #endif } void init(const M_string& remappings) { M_string::const_iterator it = remappings.find("__hostname"); if (it != remappings.end()) { g_host = it->second; } else { it = remappings.find("__ip"); if (it != remappings.end()) { g_host = it->second; } } it = remappings.find("__tcpros_server_port"); if (it != remappings.end()) { try { g_tcpros_server_port = boost::lexical_cast<uint16_t>(it->second); } catch (boost::bad_lexical_cast&) { throw ros::InvalidPortException("__tcpros_server_port [" + it->second + "] was not specified as a number within the 0-65535 range"); } } if (g_host.empty()) { g_host = determineHost(); } } } // namespace network } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/common.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/common.h" #include <cstdlib> #include <cstdio> #include <cerrno> #include <cassert> #include <sys/types.h> #if !defined(WIN32) #include <unistd.h> #include <pthread.h> #endif #include <signal.h> using std::string; void ros::disableAllSignalsInThisThread() { #if !defined(WIN32) // pthreads_win32, despite having an implementation of pthread_sigmask, // doesn't have an implementation of sigset_t, and also doesn't expose its // pthread_sigmask externally. sigset_t signal_set; /* block all signals */ sigfillset( &signal_set ); pthread_sigmask( SIG_BLOCK, &signal_set, NULL ); #endif }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/spinner.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/spinner.h" #include "ros/ros.h" #include "ros/callback_queue.h" #include <boost/thread/thread.hpp> #include <boost/thread/recursive_mutex.hpp> namespace { boost::recursive_mutex spinmutex; } namespace ros { void SingleThreadedSpinner::spin(CallbackQueue* queue) { boost::recursive_mutex::scoped_try_lock spinlock(spinmutex); if(!spinlock.owns_lock()) { ROS_ERROR("SingleThreadedSpinner: You've attempted to call spin " "from multiple threads. Use a MultiThreadedSpinner instead."); return; } ros::WallDuration timeout(0.1f); if (!queue) { queue = getGlobalCallbackQueue(); } ros::NodeHandle n; while (n.ok()) { queue->callAvailable(timeout); } } MultiThreadedSpinner::MultiThreadedSpinner(uint32_t thread_count) : thread_count_(thread_count) { } void MultiThreadedSpinner::spin(CallbackQueue* queue) { boost::recursive_mutex::scoped_try_lock spinlock(spinmutex); if (!spinlock.owns_lock()) { ROS_ERROR("MultiThreadeSpinner: You've attempted to call ros::spin " "from multiple threads... " "but this spinner is already multithreaded."); return; } AsyncSpinner s(thread_count_, queue); s.start(); ros::waitForShutdown(); } class AsyncSpinnerImpl { public: AsyncSpinnerImpl(uint32_t thread_count, CallbackQueue* queue); ~AsyncSpinnerImpl(); bool canStart(); void start(); void stop(); private: void threadFunc(); boost::mutex mutex_; boost::recursive_mutex::scoped_try_lock member_spinlock; boost::thread_group threads_; uint32_t thread_count_; CallbackQueue* callback_queue_; volatile bool continue_; ros::NodeHandle nh_; }; AsyncSpinnerImpl::AsyncSpinnerImpl(uint32_t thread_count, CallbackQueue* queue) : thread_count_(thread_count) , callback_queue_(queue) , continue_(false) { if (thread_count == 0) { thread_count_ = boost::thread::hardware_concurrency(); if (thread_count_ == 0) { thread_count_ = 1; } } if (!queue) { callback_queue_ = getGlobalCallbackQueue(); } } AsyncSpinnerImpl::~AsyncSpinnerImpl() { stop(); } bool AsyncSpinnerImpl::canStart() { boost::recursive_mutex::scoped_try_lock spinlock(spinmutex); return spinlock.owns_lock(); } void AsyncSpinnerImpl::start() { boost::mutex::scoped_lock lock(mutex_); if (continue_) return; boost::recursive_mutex::scoped_try_lock spinlock(spinmutex); if (!spinlock.owns_lock()) { ROS_WARN("AsyncSpinnerImpl: Attempt to start() an AsyncSpinner failed " "because another AsyncSpinner is already running. Note that the " "other AsyncSpinner might not be using the same callback queue " "as this AsyncSpinner, in which case no callbacks in your " "callback queue will be serviced."); return; } spinlock.swap(member_spinlock); continue_ = true; for (uint32_t i = 0; i < thread_count_; ++i) { threads_.create_thread(boost::bind(&AsyncSpinnerImpl::threadFunc, this)); } } void AsyncSpinnerImpl::stop() { boost::mutex::scoped_lock lock(mutex_); if (!continue_) return; ROS_ASSERT_MSG(member_spinlock.owns_lock(), "Async spinner's member lock doesn't own the global spinlock, hrm."); ROS_ASSERT_MSG(member_spinlock.mutex() == &spinmutex, "Async spinner's member lock owns a lock on the wrong mutex?!?!?"); member_spinlock.unlock(); continue_ = false; threads_.join_all(); } void AsyncSpinnerImpl::threadFunc() { disableAllSignalsInThisThread(); CallbackQueue* queue = callback_queue_; bool use_call_available = thread_count_ == 1; WallDuration timeout(0.1); while (continue_ && nh_.ok()) { if (use_call_available) { queue->callAvailable(timeout); } else { queue->callOne(timeout); } } } AsyncSpinner::AsyncSpinner(uint32_t thread_count) : impl_(new AsyncSpinnerImpl(thread_count, 0)) { } AsyncSpinner::AsyncSpinner(uint32_t thread_count, CallbackQueue* queue) : impl_(new AsyncSpinnerImpl(thread_count, queue)) { } bool AsyncSpinner::canStart() { return impl_->canStart(); } void AsyncSpinner::start() { impl_->start(); } void AsyncSpinner::stop() { impl_->stop(); } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/topic.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/topic.h" #include "ros/callback_queue.h" namespace ros { namespace topic { void waitForMessageImpl(SubscribeOptions& ops, const boost::function<bool(void)>& ready_pred, NodeHandle& nh, ros::Duration timeout) { ros::CallbackQueue queue; ops.callback_queue = &queue; ros::Subscriber sub = nh.subscribe(ops); ros::Time end = ros::Time::now() + timeout; while (!ready_pred() && nh.ok()) { queue.callAvailable(ros::WallDuration(0.1)); if (!timeout.isZero() && ros::Time::now() >= end) { ops.callback_queue = NULL; return; } } ops.callback_queue = NULL; } } // namespace topic } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/intraprocess_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/intraprocess_subscriber_link.h" #include "ros/intraprocess_publisher_link.h" #include "ros/publication.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/topic_manager.h" #include "ros/file_log.h" #include <boost/bind.hpp> namespace ros { IntraProcessSubscriberLink::IntraProcessSubscriberLink(const PublicationPtr& parent) : dropped_(false) { ROS_ASSERT(parent); parent_ = parent; topic_ = parent->getName(); } IntraProcessSubscriberLink::~IntraProcessSubscriberLink() { } void IntraProcessSubscriberLink::setSubscriber(const IntraProcessPublisherLinkPtr& subscriber) { subscriber_ = subscriber; connection_id_ = ConnectionManager::instance()->getNewConnectionID(); destination_caller_id_ = this_node::getName(); } bool IntraProcessSubscriberLink::isLatching() { if (PublicationPtr parent = parent_.lock()) { return parent->isLatching(); } return false; } void IntraProcessSubscriberLink::enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy) { boost::recursive_mutex::scoped_lock lock(drop_mutex_); if (dropped_) { return; } ROS_ASSERT(subscriber_); subscriber_->handleMessage(m, ser, nocopy); } std::string IntraProcessSubscriberLink::getTransportType() { return std::string("INTRAPROCESS"); } std::string IntraProcessSubscriberLink::getTransportInfo() { // TODO: Check if we can dump more useful information here return getTransportType(); } void IntraProcessSubscriberLink::drop() { { boost::recursive_mutex::scoped_lock lock(drop_mutex_); if (dropped_) { return; } dropped_ = true; } if (subscriber_) { subscriber_->drop(); subscriber_.reset(); } if (PublicationPtr parent = parent_.lock()) { ROSCPP_LOG_DEBUG("Connection to local subscriber on topic [%s] dropped", topic_.c_str()); parent->removeSubscriberLink(shared_from_this()); } } void IntraProcessSubscriberLink::getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti) { boost::recursive_mutex::scoped_lock lock(drop_mutex_); if (dropped_) { return; } subscriber_->getPublishTypes(ser, nocopy, ti); } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/transport_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/transport_subscriber_link.h" #include "ros/publication.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/topic_manager.h" #include "ros/file_log.h" #include <boost/bind.hpp> namespace ros { TransportSubscriberLink::TransportSubscriberLink() : writing_message_(false) , header_written_(false) , queue_full_(false) { } TransportSubscriberLink::~TransportSubscriberLink() { drop(); } bool TransportSubscriberLink::initialize(const ConnectionPtr& connection) { connection_ = connection; dropped_conn_ = connection_->addDropListener(boost::bind(&TransportSubscriberLink::onConnectionDropped, this, _1)); return true; } bool TransportSubscriberLink::handleHeader(const Header& header) { std::string topic; if (!header.getValue("topic", topic)) { std::string msg("Header from subscriber did not have the required element: topic"); ROS_ERROR("%s", msg.c_str()); connection_->sendHeaderError(msg); return false; } // This will get validated by validateHeader below std::string client_callerid; header.getValue("callerid", client_callerid); PublicationPtr pt = TopicManager::instance()->lookupPublication(topic); if (!pt) { std::string msg = std::string("received a connection for a nonexistent topic [") + topic + std::string("] from [" + connection_->getTransport()->getTransportInfo() + "] [" + client_callerid +"]."); ROSCPP_LOG_DEBUG("%s", msg.c_str()); connection_->sendHeaderError(msg); return false; } std::string error_msg; if (!pt->validateHeader(header, error_msg)) { ROSCPP_LOG_DEBUG("%s", error_msg.c_str()); connection_->sendHeaderError(error_msg); return false; } std::string node_type; if (header.getValue("node_type", node_type) && node_type == "rospy") { setRospy(true); } else { setRospy(false); } destination_caller_id_ = client_callerid; connection_id_ = ConnectionManager::instance()->getNewConnectionID(); topic_ = pt->getName(); parent_ = PublicationWPtr(pt); // Send back a success, with info M_string m; m["type"] = pt->getDataType(); m["md5sum"] = pt->getMD5Sum(); m["message_definition"] = pt->getMessageDefinition(); m["callerid"] = this_node::getName(); m["latching"] = pt->isLatching() ? "1" : "0"; m["topic"] = topic_; connection_->writeHeader(m, boost::bind(&TransportSubscriberLink::onHeaderWritten, this, _1)); pt->addSubscriberLink(shared_from_this()); return true; } void TransportSubscriberLink::onConnectionDropped(const ConnectionPtr& conn) { ROS_ASSERT(conn == connection_); PublicationPtr parent = parent_.lock(); if (parent) { ROSCPP_LOG_DEBUG("Connection to subscriber [%s] to topic [%s] dropped", connection_->getRemoteString().c_str(), topic_.c_str()); parent->removeSubscriberLink(shared_from_this()); } } void TransportSubscriberLink::onHeaderWritten(const ConnectionPtr& conn) { (void)conn; header_written_ = true; startMessageWrite(true); } void TransportSubscriberLink::onMessageWritten(const ConnectionPtr& conn) { (void)conn; writing_message_ = false; startMessageWrite(true); } void TransportSubscriberLink::startMessageWrite(bool immediate_write) { boost::shared_array<uint8_t> dummy; SerializedMessage m(dummy, (uint32_t)0); { boost::mutex::scoped_lock lock(outbox_mutex_); if (writing_message_ || !header_written_) { return; } if (!outbox_.empty()) { writing_message_ = true; m = outbox_.front(); outbox_.pop(); } } if (m.num_bytes > 0) { connection_->write(m.buf, m.num_bytes, boost::bind(&TransportSubscriberLink::onMessageWritten, this, _1), immediate_write); } } void TransportSubscriberLink::enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy) { (void)nocopy; if (!ser) { return; } { boost::mutex::scoped_lock lock(outbox_mutex_); int max_queue = 0; if (PublicationPtr parent = parent_.lock()) { max_queue = parent->getMaxQueue(); } ROS_DEBUG_NAMED("superdebug", "TransportSubscriberLink on topic [%s] to caller [%s], queueing message (queue size [%d])", topic_.c_str(), destination_caller_id_.c_str(), (int)outbox_.size()); if (max_queue > 0 && (int)outbox_.size() >= max_queue) { if (!queue_full_) { ROS_DEBUG("Outgoing queue full for topic [%s]. " "Discarding oldest message\n", topic_.c_str()); } outbox_.pop(); // toss out the oldest thing in the queue to make room for us queue_full_ = true; } else { queue_full_ = false; } outbox_.push(m); } startMessageWrite(false); stats_.messages_sent_++; stats_.bytes_sent_ += m.num_bytes; stats_.message_data_sent_ += m.num_bytes; } std::string TransportSubscriberLink::getTransportType() { return connection_->getTransport()->getType(); } std::string TransportSubscriberLink::getTransportInfo() { return connection_->getTransport()->getTransportInfo(); } void TransportSubscriberLink::drop() { // Only drop the connection if it's not already sending a header error // If it is, it will automatically drop itself if (connection_->isSendingHeaderError()) { connection_->removeDropListener(dropped_conn_); } else { connection_->drop(Connection::Destructing); } } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/wall_timer.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/wall_timer.h" #include "ros/timer_manager.h" namespace ros { WallTimer::Impl::Impl() : started_(false) , timer_handle_(-1) { } WallTimer::Impl::~Impl() { ROS_DEBUG("WallTimer deregistering callbacks."); stop(); } void WallTimer::Impl::start() { if (!started_) { VoidConstPtr tracked_object; if (has_tracked_object_) { tracked_object = tracked_object_.lock(); } timer_handle_ = TimerManager<WallTime, WallDuration, WallTimerEvent>::global().add(period_, callback_, callback_queue_, tracked_object, oneshot_); started_ = true; } } void WallTimer::Impl::stop() { if (started_) { started_ = false; TimerManager<WallTime, WallDuration, WallTimerEvent>::global().remove(timer_handle_); timer_handle_ = -1; } } bool WallTimer::Impl::isValid() { return !period_.isZero(); } bool WallTimer::Impl::hasPending() { if (!isValid() || timer_handle_ == -1) { return false; } return TimerManager<WallTime, WallDuration, WallTimerEvent>::global().hasPending(timer_handle_); } void WallTimer::Impl::setPeriod(const WallDuration& period, bool reset) { period_ = period; TimerManager<WallTime, WallDuration, WallTimerEvent>::global().setPeriod(timer_handle_, period, reset); } WallTimer::WallTimer(const WallTimerOptions& ops) : impl_(new Impl) { impl_->period_ = ops.period; impl_->callback_ = ops.callback; impl_->callback_queue_ = ops.callback_queue; impl_->tracked_object_ = ops.tracked_object; impl_->has_tracked_object_ = (ops.tracked_object != NULL); impl_->oneshot_ = ops.oneshot; } WallTimer::WallTimer(const WallTimer& rhs) { impl_ = rhs.impl_; } WallTimer::~WallTimer() { } void WallTimer::start() { if (impl_) { impl_->start(); } } void WallTimer::stop() { if (impl_) { impl_->stop(); } } bool WallTimer::hasPending() { if (impl_) { return impl_->hasPending(); } return false; } void WallTimer::setPeriod(const WallDuration& period, bool reset) { if (impl_) { impl_->setPeriod(period, reset); } } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/shm_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/shm_manager.h" namespace ros { ShmManagerPtr g_shm_manager; std::mutex g_shm_manager_mutex; extern struct ConfigComm g_config_comm; const ShmManagerPtr& ShmManager::instance() { if (!g_shm_manager) { std::lock_guard<std::mutex> lg(g_shm_manager_mutex); if (!g_shm_manager) { g_shm_manager.reset(new ShmManager); } } return g_shm_manager; } ShmManager::ShmManager() :started_(false) { } ShmManager::~ShmManager() { if (started_) { shutdown(); } } void ShmManager::start() { started_ = true; ROS_DEBUG("roscpp shm manager start!"); server_thread_ = std::thread([this]() { this->threadFunc(); }); } void ShmManager::shutdown() { if (!started_) { return; } started_ = false; for (std::vector <std::thread>::iterator th = shm_threads_.begin(); th != shm_threads_.end(); ++th) { th->join(); } shm_threads_.clear(); server_thread_.join(); for (std::map<std::string, ItemShm>::iterator sh = shm_map_.begin(); sh != shm_map_.end(); ++sh) { if (sh->second.addr_sub) { delete [](sh->second.addr_sub); } if (sh->second.segment) { delete sh->second.segment; } if (sh->second.segment_mgr) { delete sh->second.segment_mgr; } } ROS_DEBUG("roscpp shm manager exit!"); } void ShmManager::threadFunc() { sharedmem_transport::SharedMemoryUtil sharedmem_util; std::string topic; while (started_ && ros::ok()) { if (TopicManager::instance()->getNumSubscriptions() > 0) { L_Subscription subs = TopicManager::instance()->getAllSubscription(); L_Subscription::iterator it; if (!g_config_comm.transport_mode && shm_map_.size() < TopicManager::instance()->getNumSubscriptions()) { for (it = subs.begin(); it != subs.end(); ++it) { topic = ros::names::resolve((*it)->getName()); if (g_config_comm.topic_white_list.find(topic) != g_config_comm.topic_white_list.end() || shm_map_.find(topic) != shm_map_.end() || (*it)->get_publisher_links().size() == 0) { continue; } boost::interprocess::managed_shared_memory* segment = NULL; sharedmem_transport::SharedMemorySegment* segment_mgr = NULL; sharedmem_transport::SharedMemoryBlock* descriptors_sub = NULL; uint32_t queue_size = 0; if (sharedmem_util.init_sharedmem(topic.c_str(), segment, segment_mgr, descriptors_sub, queue_size)) { uint8_t** addr_sub = new uint8_t*[queue_size]; if (!addr_sub) { ROS_DEBUG_STREAM("Init address for subscriber failed"); continue; } if (!segment_mgr->map_all_blocks(segment, queue_size, addr_sub)) { ROS_DEBUG_STREAM("Map all blocks failed"); if (addr_sub) { delete []addr_sub; } continue; } ItemShm item; item.segment = segment; item.segment_mgr = segment_mgr; item.descriptors_sub = descriptors_sub; item.queue_size = queue_size; item.addr_sub = addr_sub; item.shm_poll_flag = false; item.shm_sub_ptr = (*it); item.topic_name = (*it)->getName(); item.callerid = this_node::getName(); item.md5sum = sharedmem_util.get_md5sum(segment); item.datatype = sharedmem_util.get_datatype(segment); item.message_definition = sharedmem_util.get_msg_def(segment); boost::mutex::scoped_lock lock(shm_map_mutex_); shm_map_[topic] = item; } boost::mutex::scoped_lock lock(shm_first_msg_map_mutex_); if (shm_skip_first_msg_.find(topic) == shm_skip_first_msg_.end()) { if (segment == NULL) { shm_skip_first_msg_[topic] = false; } else { shm_skip_first_msg_[topic] = true; } } } } if (shm_map_.size() != 0) { for (it = subs.begin(); it != subs.end(); ++it) { topic = ros::names::resolve((*it)->getName()); if (shm_map_.find(topic) != shm_map_.end() && !shm_map_[topic].shm_poll_flag) { // Set tag true, when we start thread for the topic shm_map_[topic].shm_poll_flag = true; // Start thread for each topic shm_threads_.push_back(std::thread([&, topic]() { bool exit = false; int32_t read_index = -1; bool is_new_msg = false; M_stringPtr header_ptr(new M_string()); ros::VoidConstPtr msg; SerializedMessage m; (*header_ptr)["topic"] = shm_map_[topic].topic_name; (*header_ptr)["md5sum"] = shm_map_[topic].md5sum; (*header_ptr)["message_definition"] = shm_map_[topic].message_definition; (*header_ptr)["callerid"] = shm_map_[topic].callerid; (*header_ptr)["type"] = shm_map_[topic].datatype; while (!exit && started_ && ros::ok()) { { if (!((shm_map_[topic].shm_sub_ptr)->get_helper())) { continue; } is_new_msg = shm_map_[topic].segment_mgr->read_data(msg, read_index, shm_map_[topic].descriptors_sub, shm_map_[topic].addr_sub, (shm_map_[topic].shm_sub_ptr)->get_helper(), topic, header_ptr); // Block needs to be allocated if (read_index == sharedmem_transport::ROS_SHM_SEGMENT_WROTE_NUM || shm_map_[topic].shm_sub_ptr->get_publisher_links().size() == 0) { { boost::mutex::scoped_lock lock(shm_map_mutex_); if (shm_map_[topic].addr_sub) { delete [](shm_map_[topic].addr_sub); } shm_map_.erase(topic); } { boost::mutex::scoped_lock lock(shm_first_msg_map_mutex_); shm_skip_first_msg_.erase(topic); } is_new_msg = false; exit = true; } // New message is coming if (is_new_msg) { if (shm_skip_first_msg_[topic] == true) { // Skip first message shm_skip_first_msg_[topic] = false; continue; } m.message = msg; m.type_info = &((shm_map_[topic].shm_sub_ptr)->get_helper()->getTypeInfo()); shm_map_[topic].shm_sub_ptr->handleMessage(m, false, true, header_ptr, NULL); } } } })); } } } } // Sleep 10ms for next cycle usleep(10000); } } } /* vim: set ts=4 sw=4 sts=4 tw=100 */
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/file_log.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 <cstdio> #include "ros/file_log.h" #include "ros/this_node.h" #include <ros/io.h> #include <ros/console.h> #include <boost/filesystem.hpp> #ifdef _MSC_VER #ifdef snprintf #undef snprintf #endif #define snprintf _snprintf_s #endif namespace fs = boost::filesystem; namespace ros { namespace file_log { std::string g_log_directory; const std::string& getLogDirectory() { return g_log_directory; } void init(const M_string& remappings) { std::string log_file_name; M_string::const_iterator it = remappings.find("__log"); if (it != remappings.end()) { log_file_name = it->second; } { // Log filename can be specified on the command line through __log // If it's been set, don't create our own name if (log_file_name.empty()) { // Setup the logfile appender // Can't do this in rosconsole because the node name is not known pid_t pid = getpid(); std::string ros_log_env; if ( get_environment_variable(ros_log_env, "ROS_LOG_DIR")) { log_file_name = ros_log_env + std::string("/"); } else { if ( get_environment_variable(ros_log_env, "ROS_HOME")) { log_file_name = ros_log_env + std::string("/log/"); } else { // Not cross-platform? if( get_environment_variable(ros_log_env, "HOME") ) { std::string dotros = ros_log_env + std::string("/.ros/"); fs::create_directory(dotros); log_file_name = dotros + "log/"; fs::create_directory(log_file_name); } } } // sanitize the node name and tack it to the filename for (size_t i = 1; i < this_node::getName().length(); i++) { if (!isalnum(this_node::getName()[i])) { log_file_name += '_'; } else { log_file_name += this_node::getName()[i]; } } char pid_str[100]; snprintf(pid_str, sizeof(pid_str), "%d", pid); log_file_name += std::string("_") + std::string(pid_str) + std::string(".log"); } log_file_name = fs::system_complete(log_file_name).string(); g_log_directory = fs::path(log_file_name).parent_path().string(); } } } // namespace file_log } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/this_node.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 <cstdio> #include "ros/this_node.h" #include "ros/names.h" #include "ros/topic_manager.h" #include "ros/init.h" #ifdef _MSC_VER #ifdef snprintf #undef snprintf #endif #define snprintf _snprintf_s #endif namespace ros { namespace names { void init(const M_string& remappings); } namespace this_node { std::string g_name = "empty"; std::string g_namespace; const std::string& getName() { return g_name; } const std::string& getNamespace() { return g_namespace; } void getAdvertisedTopics(V_string& topics) { TopicManager::instance()->getAdvertisedTopics(topics); } void getSubscribedTopics(V_string& topics) { TopicManager::instance()->getSubscribedTopics(topics); } void init(const std::string& name, const M_string& remappings, uint32_t options) { char *ns_env = NULL; #ifdef _MSC_VER _dupenv_s(&ns_env, NULL, "ROS_NAMESPACE"); #else ns_env = getenv("ROS_NAMESPACE"); #endif if (ns_env) { g_namespace = ns_env; #ifdef _MSC_VER free(ns_env); #endif } g_name = name; bool disable_anon = false; M_string::const_iterator it = remappings.find("__name"); if (it != remappings.end()) { g_name = it->second; disable_anon = true; } it = remappings.find("__ns"); if (it != remappings.end()) { g_namespace = it->second; } if (g_namespace.empty()) { g_namespace = "/"; } g_namespace = (g_namespace == "/") ? std::string("/") : ("/" + g_namespace) ; std::string error; if (!names::validate(g_namespace, error)) { std::stringstream ss; ss << "Namespace [" << g_namespace << "] is invalid: " << error; throw InvalidNameException(ss.str()); } // names must be initialized here, because it requires the namespace to already be known so that it can properly resolve names. // It must be done before we resolve g_name, because otherwise the name will not get remapped. names::init(remappings); if (g_name.find("/") != std::string::npos) { throw InvalidNodeNameException(g_name, "node names cannot contain /"); } if (g_name.find("~") != std::string::npos) { throw InvalidNodeNameException(g_name, "node names cannot contain ~"); } g_name = names::resolve(g_namespace, g_name); if (options & init_options::AnonymousName && !disable_anon) { char buf[200]; snprintf(buf, sizeof(buf), "_%llu", (unsigned long long)WallTime::now().toNSec()); g_name += buf; } ros::console::setFixedFilterToken("node", g_name); } } // namespace this_node } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service_server.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/service_server.h" #include "ros/node_handle.h" #include "ros/service_manager.h" namespace ros { ServiceServer::Impl::Impl() : unadvertised_(false) { } ServiceServer::Impl::~Impl() { ROS_DEBUG("ServiceServer on '%s' deregistering callbacks.", service_.c_str()); unadvertise(); } bool ServiceServer::Impl::isValid() const { return !unadvertised_; } void ServiceServer::Impl::unadvertise() { if (!unadvertised_) { unadvertised_ = true; ServiceManager::instance()->unadvertiseService(service_); node_handle_.reset(); } } ServiceServer::ServiceServer(const std::string& service, const NodeHandle& node_handle) : impl_(boost::make_shared<Impl>()) { impl_->service_ = service; impl_->node_handle_ = boost::make_shared<NodeHandle>(node_handle); } ServiceServer::ServiceServer(const ServiceServer& rhs) { impl_ = rhs.impl_; } ServiceServer::~ServiceServer() { } void ServiceServer::shutdown() { if (impl_) { impl_->unadvertise(); } } std::string ServiceServer::getService() const { if (impl_ && impl_->isValid()) { return impl_->service_; } return std::string(); } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/rosout_appender.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/rosout_appender.h" #include "ros/this_node.h" #include "ros/node_handle.h" #include "ros/topic_manager.h" #include "ros/advertise_options.h" #include "ros/names.h" #include <rosgraph_msgs/Log.h> namespace ros { ROSOutAppender::ROSOutAppender() : shutting_down_(false) , publish_thread_(boost::bind(&ROSOutAppender::logThread, this)) { AdvertiseOptions ops; ops.init<rosgraph_msgs::Log>(names::resolve("/rosout"), 0); ops.latch = true; SubscriberCallbacksPtr cbs(boost::make_shared<SubscriberCallbacks>()); TopicManager::instance()->advertise(ops, cbs); } ROSOutAppender::~ROSOutAppender() { shutting_down_ = true; { boost::mutex::scoped_lock lock(queue_mutex_); queue_condition_.notify_all(); } publish_thread_.join(); } const std::string& ROSOutAppender::getLastError() const { return last_error_; } void ROSOutAppender::log(::ros::console::Level level, const char* str, const char* file, const char* function, int line) { rosgraph_msgs::LogPtr msg(boost::make_shared<rosgraph_msgs::Log>()); msg->header.stamp = ros::Time::now(); if (level == ros::console::levels::Debug) { msg->level = rosgraph_msgs::Log::DEBUG; } else if (level == ros::console::levels::Info) { msg->level = rosgraph_msgs::Log::INFO; } else if (level == ros::console::levels::Warn) { msg->level = rosgraph_msgs::Log::WARN; } else if (level == ros::console::levels::Error) { msg->level = rosgraph_msgs::Log::ERROR; } else if (level == ros::console::levels::Fatal) { msg->level = rosgraph_msgs::Log::FATAL; } msg->name = this_node::getName(); msg->msg = str; msg->file = file; msg->function = function; msg->line = line; this_node::getAdvertisedTopics(msg->topics); if (level == ::ros::console::levels::Fatal || level == ::ros::console::levels::Error) { last_error_ = str; } boost::mutex::scoped_lock lock(queue_mutex_); log_queue_.push_back(msg); queue_condition_.notify_all(); } void ROSOutAppender::logThread() { while (!shutting_down_) { V_Log local_queue; { boost::mutex::scoped_lock lock(queue_mutex_); if (shutting_down_) { return; } queue_condition_.wait(lock); if (shutting_down_) { return; } local_queue.swap(log_queue_); } V_Log::iterator it = local_queue.begin(); V_Log::iterator end = local_queue.end(); for (; it != end; ++it) { TopicManager::instance()->publish(names::resolve("/rosout"), *(*it)); } } } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service_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 <cstdio> #include "ros/service_manager.h" #include "ros/broadcast_manager.h" #include "ros/xmlrpc_manager.h" #include "ros/connection_manager.h" #include "ros/poll_manager.h" #include "ros/service_publication.h" #include "ros/service_client_link.h" #include "ros/service_server_link.h" #include "ros/this_node.h" #include "ros/network.h" #include "ros/master.h" #include "ros/transport/transport_tcp.h" #include "ros/transport/transport_udp.h" #include "ros/init.h" #include "ros/connection.h" #include "ros/file_log.h" #include "XmlRpc.h" #include <ros/console.h> using namespace XmlRpc; // A battle to be fought later using namespace std; // sigh namespace ros { ServiceManagerPtr g_service_manager; boost::mutex g_service_manager_mutex; const ServiceManagerPtr& ServiceManager::instance() { if (!g_service_manager) { boost::mutex::scoped_lock lock(g_service_manager_mutex); if (!g_service_manager) { g_service_manager = boost::make_shared<ServiceManager>(); } } return g_service_manager; } ServiceManager::ServiceManager() : shutting_down_(false) { } ServiceManager::~ServiceManager() { shutdown(); } void ServiceManager::start() { shutting_down_ = false; poll_manager_ = PollManager::instance(); connection_manager_ = ConnectionManager::instance(); xmlrpc_manager_ = XMLRPCManager::instance(); } void ServiceManager::shutdown() { boost::recursive_mutex::scoped_lock shutdown_lock(shutting_down_mutex_); if (shutting_down_) { return; } shutting_down_ = true; ROSCPP_LOG_DEBUG("ServiceManager::shutdown(): unregistering our advertised services"); { boost::mutex::scoped_lock ss_lock(service_publications_mutex_); for (L_ServicePublication::iterator i = service_publications_.begin(); i != service_publications_.end(); ++i) { unregisterService((*i)->getName()); //ROSCPP_LOG_DEBUG( "shutting down service %s", (*i)->getName().c_str()); (*i)->drop(); } service_publications_.clear(); } L_ServiceServerLink local_service_clients; { boost::mutex::scoped_lock lock(service_server_links_mutex_); local_service_clients.swap(service_server_links_); } { L_ServiceServerLink::iterator it = local_service_clients.begin(); L_ServiceServerLink::iterator end = local_service_clients.end(); for (; it != end; ++it) { (*it)->getConnection()->drop(Connection::Destructing); } local_service_clients.clear(); } } bool ServiceManager::advertiseService(const AdvertiseServiceOptions& ops) { boost::recursive_mutex::scoped_lock shutdown_lock(shutting_down_mutex_); if (shutting_down_) { return false; } { boost::mutex::scoped_lock lock(service_publications_mutex_); if (isServiceAdvertised(ops.service)) { ROS_ERROR("Tried to advertise a service that is already advertised in this node [%s]", ops.service.c_str()); return false; } ServicePublicationPtr pub(boost::make_shared<ServicePublication>(ops.service, ops.md5sum, ops.datatype, ops.req_datatype, ops.res_datatype, ops.helper, ops.callback_queue, ops.tracked_object)); service_publications_.push_back(pub); } char uri_buf[1024]; snprintf(uri_buf, sizeof(uri_buf), "rosrpc://%s:%d", network::getHost().c_str(), connection_manager_->getTCPPort()); BroadcastManager::instance()->registerService(this_node::getName(), ops.service, string(uri_buf), xmlrpc_manager_->getServerURI()); return true; } bool ServiceManager::unadvertiseService(const string &serv_name) { boost::recursive_mutex::scoped_lock shutdown_lock(shutting_down_mutex_); if (shutting_down_) { return false; } ServicePublicationPtr pub; { boost::mutex::scoped_lock lock(service_publications_mutex_); for (L_ServicePublication::iterator i = service_publications_.begin(); i != service_publications_.end(); ++i) { if((*i)->getName() == serv_name && !(*i)->isDropped()) { pub = *i; service_publications_.erase(i); break; } } } if (pub) { unregisterService(pub->getName()); ROSCPP_LOG_DEBUG( "shutting down service [%s]", pub->getName().c_str()); pub->drop(); return true; } return false; } bool ServiceManager::unregisterService(const std::string& service) { char uri_buf[1024]; snprintf(uri_buf, sizeof(uri_buf), "rosrpc://%s:%d", network::getHost().c_str(), connection_manager_->getTCPPort()); BroadcastManager::instance()->unregisterService(service, string(uri_buf)); return true; } bool ServiceManager::isServiceAdvertised(const string& serv_name) { for (L_ServicePublication::iterator s = service_publications_.begin(); s != service_publications_.end(); ++s) { if (((*s)->getName() == serv_name) && !(*s)->isDropped()) { return true; } } return false; } ServicePublicationPtr ServiceManager::lookupServicePublication(const std::string& service) { boost::mutex::scoped_lock lock(service_publications_mutex_); for (L_ServicePublication::iterator t = service_publications_.begin(); t != service_publications_.end(); ++t) { if ((*t)->getName() == service) { return *t; } } return ServicePublicationPtr(); } ServiceServerLinkPtr ServiceManager::createServiceServerLink(const std::string& service, bool persistent, const std::string& request_md5sum, const std::string& response_md5sum, const M_string& header_values) { boost::recursive_mutex::scoped_lock shutdown_lock(shutting_down_mutex_); if (shutting_down_) { return ServiceServerLinkPtr(); } uint32_t serv_port; std::string serv_host; if (!lookupService(service, serv_host, serv_port)) { return ServiceServerLinkPtr(); } TransportTCPPtr transport(boost::make_shared<TransportTCP>(&poll_manager_->getPollSet())); // Make sure to initialize the connection *before* transport->connect() // is called, otherwise we might miss a connect error (see #434). ConnectionPtr connection(boost::make_shared<Connection>()); connection_manager_->addConnection(connection); connection->initialize(transport, false, HeaderReceivedFunc()); if (transport->connect(serv_host, serv_port)) { ServiceServerLinkPtr client(boost::make_shared<ServiceServerLink>(service, persistent, request_md5sum, response_md5sum, header_values)); { boost::mutex::scoped_lock lock(service_server_links_mutex_); service_server_links_.push_back(client); } client->initialize(connection); return client; } ROSCPP_LOG_DEBUG("Failed to connect to service [%s] (mapped=[%s]) at [%s:%d]", service.c_str(), service.c_str(), serv_host.c_str(), serv_port); return ServiceServerLinkPtr(); } void ServiceManager::removeServiceServerLink(const ServiceServerLinkPtr& client) { // Guard against this getting called as a result of shutdown() dropping all connections (where shutting_down_mutex_ is already locked) if (shutting_down_) { return; } boost::recursive_mutex::scoped_lock shutdown_lock(shutting_down_mutex_); // Now check again, since the state may have changed between pre-lock/now if (shutting_down_) { return; } boost::mutex::scoped_lock lock(service_server_links_mutex_); L_ServiceServerLink::iterator it = std::find(service_server_links_.begin(), service_server_links_.end(), client); if (it != service_server_links_.end()) { service_server_links_.erase(it); } } bool ServiceManager::lookupService(const string &name, string &serv_host, uint32_t &serv_port) { string serv_uri; if (!BroadcastManager::instance()->lookupService(name, serv_uri)) { return false; } if (!serv_uri.length()) // shouldn't happen. but let's be sure. { ROS_ERROR("lookupService: Empty server URI returned from master"); return false; } if (!network::splitURI(serv_uri, serv_host, serv_port)) { ROS_ERROR("lookupService: Bad service uri [%s]", serv_uri.c_str()); return false; } return true; } } // 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.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/publisher.h" #include "ros/publication.h" #include "ros/node_handle.h" #include "ros/topic_manager.h" #include "ros/config_comm.h" #include "ros/this_node.h" #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> namespace ros { Publisher::Impl::Impl() : unadvertised_(false), first_run_(true), default_transport_(SHARED_MEMORY) { } Publisher::Impl::~Impl() { ROS_DEBUG("Publisher on '%s' deregistering callbacks.", topic_.c_str()); unadvertise(); } bool Publisher::Impl::isValid() const { return !unadvertised_; } void Publisher::Impl::unadvertise() { if (!unadvertised_) { unadvertised_ = true; TopicManager::instance()->unadvertise(topic_, callbacks_); node_handle_.reset(); } } Publisher::Publisher(const std::string& topic, const std::string& md5sum, const std::string& datatype, const std::string& message_definition, const NodeHandle& node_handle, const SubscriberCallbacksPtr& callbacks, const uint32_t& queue_size) : impl_(boost::make_shared<Impl>()) { impl_->topic_ = topic; impl_->queue_size_ = queue_size; impl_->alloc_size_ = 0; impl_->md5sum_ = md5sum; impl_->datatype_ = datatype; impl_->message_definition_ = message_definition; impl_->node_handle_ = boost::make_shared<NodeHandle>(node_handle); impl_->callbacks_ = callbacks; } Publisher::Publisher(const Publisher& rhs) { impl_ = rhs.impl_; } Publisher::~Publisher() { } boost::interprocess::interprocess_mutex shm_pub_mutex_; extern struct ConfigComm g_config_comm ; void Publisher::publish(const boost::function<SerializedMessage(void)>& serfunc, SerializedMessage& m) const { if (!impl_) { ROS_ASSERT_MSG(false, "Call to publish() on an invalid Publisher (topic [%s])", impl_->topic_.c_str()); return; } if (!impl_->isValid()) { ROS_ASSERT_MSG(false, "Call to publish() on an invalid Publisher (topic [%s])", impl_->topic_.c_str()); return; } if (impl_ && impl_->isValid()) { if (!g_config_comm.transport_mode && g_config_comm.topic_white_list.find(impl_->topic_) == g_config_comm.topic_white_list.end()) { PublicationPtr publication_ptr = TopicManager::instance()->lookupPublication(impl_->topic_); if (!publication_ptr) { return; } impl_->default_transport_ = publication_ptr->getSubscriberlinksTransport(); if (impl_->default_transport_ == SHARED_MEMORY) { boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(shm_pub_mutex_); ROS_DEBUG_STREAM("Publish Tranport: " << impl_->topic_ << ", SHARED_MEMORY"); publishShm(serfunc, m, impl_->datatype_, impl_->md5sum_, impl_->message_definition_); } else if (impl_->default_transport_ == SOCKET) { ROS_DEBUG_STREAM("Publish Tranport: " << impl_->topic_ << ", SOCKET"); TopicManager::instance()->publish(impl_->topic_, serfunc, m); } else if (impl_->default_transport_ == BOTH) { ROS_DEBUG_STREAM("Publish Tranport: " << impl_->topic_ << ", BOTH"); TopicManager::instance()->publish(impl_->topic_, serfunc, m); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(shm_pub_mutex_); publishShm(serfunc, m, impl_->datatype_, impl_->md5sum_, impl_->message_definition_); } else { ROS_ERROR_STREAM("Publish Tranport: " << impl_->default_transport_ << ", UNKNOWN"); } } else { ROS_DEBUG_STREAM("Publish Tranport: " << impl_->topic_ << ", SOCKET"); TopicManager::instance()->publish(impl_->topic_, serfunc, m); } } } void Publisher::publishShm(const boost::function<SerializedMessage(void)>& serfunc, SerializedMessage& message, std::string datatype, std::string md5sum, std::string msg_def) const { SerializedMessage m2 = serfunc(); message.buf = m2.buf; message.num_bytes = m2.num_bytes; message.message_start = m2.message_start; // Change queue_size to suitable size uint32_t queue_size_real = 5; if (!impl_->first_run_ && message.num_bytes - 4 >= impl_->alloc_size_) { ROS_DEBUG_STREAM("Reallocated msg queue start"); // Get segment handler to remove segment boost::shared_ptr<sharedmem_transport::SharedMemoryUtil> shm_util(new sharedmem_transport::SharedMemoryUtil()); boost::interprocess::managed_shared_memory* segment = NULL; sharedmem_transport::SharedMemorySegment* segment_mgr = NULL; sharedmem_transport::SharedMemoryBlock* descriptors_sub = NULL; if (shm_util->init_sharedmem(impl_->topic_.c_str(), segment, segment_mgr, descriptors_sub, queue_size_real)) { // Set reallocated flag segment_mgr->set_wrote_num(sharedmem_transport::ROS_SHM_SEGMENT_WROTE_NUM); delete segment; // Remove segment bool status = shm_util->remove_segment(impl_->topic_.c_str()); // Set flag to init shared memory if (status) { impl_->first_run_ = true; } } ROS_DEBUG_STREAM("Reallocated msg queue end"); } if (impl_->first_run_) { // Define variables int32_t index = 0; uint64_t msg_size = message.num_bytes - 4 ; // Create topic segment if (!impl_->shared_impl_.create_topic_segement(impl_->topic_, index, queue_size_real, msg_size, impl_->alloc_size_, datatype, md5sum, msg_def)) { ROS_FATAL("Create topic segment failed"); return; } // Reset first_run_ flag impl_->first_run_ = false; } // Publishing SHM message impl_->shared_impl_.publish_msg(message, queue_size_real, impl_->first_run_); } void Publisher::incrementSequence() const { if (impl_ && impl_->isValid()) { TopicManager::instance()->incrementSequence(impl_->topic_); } } void Publisher::shutdown() { if (impl_) { impl_->unadvertise(); impl_.reset(); } } std::string Publisher::getTopic() const { if (impl_) { return impl_->topic_; } return std::string(); } uint32_t Publisher::getNumSubscribers() const { if (impl_ && impl_->isValid()) { return TopicManager::instance()->getNumSubscribers(impl_->topic_); } return 0; } bool Publisher::isLatched() const { PublicationPtr publication_ptr; if (impl_ && impl_->isValid()) { publication_ptr = TopicManager::instance()->lookupPublication(impl_->topic_); } else { ROS_ASSERT_MSG(false, "Call to isLatched() on an invalid Publisher"); throw ros::Exception("Call to isLatched() on an invalid Publisher"); } if (publication_ptr) { return publication_ptr->isLatched(); } else { ROS_ASSERT_MSG(false, "Call to isLatched() on an invalid Publisher"); throw ros::Exception("Call to isLatched() on an invalid Publisher"); } } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service_server_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_server_link.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> #include <sstream> namespace ros { ServiceServerLink::ServiceServerLink(const std::string& service_name, bool persistent, const std::string& request_md5sum, const std::string& response_md5sum, const M_string& header_values) : service_name_(service_name) , persistent_(persistent) , request_md5sum_(request_md5sum) , response_md5sum_(response_md5sum) , extra_outgoing_header_values_(header_values) , header_written_(false) , header_read_(false) , dropped_(false) { } ServiceServerLink::~ServiceServerLink() { ROS_ASSERT(connection_->isDropped()); clearCalls(); } void ServiceServerLink::cancelCall(const CallInfoPtr& info) { CallInfoPtr local = info; { boost::mutex::scoped_lock lock(local->finished_mutex_); local->finished_ = true; local->finished_condition_.notify_all(); } if (boost::this_thread::get_id() != info->caller_thread_id_) { while (!local->call_finished_) { boost::this_thread::yield(); } } } void ServiceServerLink::clearCalls() { CallInfoPtr local_current; { boost::mutex::scoped_lock lock(call_queue_mutex_); local_current = current_call_; } if (local_current) { cancelCall(local_current); } boost::mutex::scoped_lock lock(call_queue_mutex_); while (!call_queue_.empty()) { CallInfoPtr info = call_queue_.front(); cancelCall(info); call_queue_.pop(); } } bool ServiceServerLink::initialize(const ConnectionPtr& connection) { connection_ = connection; connection_->addDropListener(boost::bind(&ServiceServerLink::onConnectionDropped, this, _1)); connection_->setHeaderReceivedCallback(boost::bind(&ServiceServerLink::onHeaderReceived, this, _1, _2)); M_string header; header["service"] = service_name_; header["md5sum"] = request_md5sum_; header["callerid"] = this_node::getName(); header["persistent"] = persistent_ ? "1" : "0"; header.insert(extra_outgoing_header_values_.begin(), extra_outgoing_header_values_.end()); connection_->writeHeader(header, boost::bind(&ServiceServerLink::onHeaderWritten, this, _1)); return true; } void ServiceServerLink::onHeaderWritten(const ConnectionPtr& conn) { (void)conn; header_written_ = true; } bool ServiceServerLink::onHeaderReceived(const ConnectionPtr& conn, const Header& header) { (void)conn; std::string md5sum, type; if (!header.getValue("md5sum", md5sum)) { ROS_ERROR("TCPROS header from service server did not have required element: md5sum"); return false; } bool empty = false; { boost::mutex::scoped_lock lock(call_queue_mutex_); empty = call_queue_.empty(); if (empty) { header_read_ = true; } } if (!empty) { processNextCall(); header_read_ = true; } return true; } void ServiceServerLink::onConnectionDropped(const ConnectionPtr& conn) { ROS_ASSERT(conn == connection_); ROSCPP_LOG_DEBUG("Service client from [%s] for [%s] dropped", conn->getRemoteString().c_str(), service_name_.c_str()); dropped_ = true; clearCalls(); ServiceManager::instance()->removeServiceServerLink(shared_from_this()); } void ServiceServerLink::onRequestWritten(const ConnectionPtr& conn) { (void)conn; //ros::WallDuration(0.1).sleep(); connection_->read(5, boost::bind(&ServiceServerLink::onResponseOkAndLength, this, _1, _2, _3, _4)); } void ServiceServerLink::onResponseOkAndLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success) { ROS_ASSERT(conn == connection_); ROS_ASSERT(size == 5); if (!success) return; uint8_t ok = buffer[0]; uint32_t len = *((uint32_t*)(buffer.get() + 1)); 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; } { boost::mutex::scoped_lock lock(call_queue_mutex_); if ( ok != 0 ) { current_call_->success_ = true; } else { current_call_->success_ = false; } } if (len > 0) { connection_->read(len, boost::bind(&ServiceServerLink::onResponse, this, _1, _2, _3, _4)); } else { onResponse(conn, boost::shared_array<uint8_t>(), 0, true); } } void ServiceServerLink::onResponse(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success) { ROS_ASSERT(conn == connection_); if (!success) return; { boost::mutex::scoped_lock queue_lock(call_queue_mutex_); if (current_call_->success_) { *current_call_->resp_ = SerializedMessage(buffer, size); } else { current_call_->exception_string_ = std::string(reinterpret_cast<char*>(buffer.get()), size); } } callFinished(); } void ServiceServerLink::callFinished() { CallInfoPtr saved_call; ServiceServerLinkPtr self; { boost::mutex::scoped_lock queue_lock(call_queue_mutex_); boost::mutex::scoped_lock finished_lock(current_call_->finished_mutex_); ROS_DEBUG_NAMED("superdebug", "Client to service [%s] call finished with success=[%s]", service_name_.c_str(), current_call_->success_ ? "true" : "false"); current_call_->finished_ = true; current_call_->finished_condition_.notify_all(); saved_call = current_call_; current_call_ = CallInfoPtr(); // If the call queue is empty here, we may be deleted as soon as we release these locks, so keep a shared pointer to ourselves until we return // ugly // jfaust TODO there's got to be a better way self = shared_from_this(); } saved_call = CallInfoPtr(); processNextCall(); } void ServiceServerLink::processNextCall() { bool empty = false; { boost::mutex::scoped_lock lock(call_queue_mutex_); if (current_call_) { return; } if (!call_queue_.empty()) { ROS_DEBUG_NAMED("superdebug", "[%s] Client to service [%s] processing next service call", persistent_ ? "persistent" : "non-persistent", service_name_.c_str()); current_call_ = call_queue_.front(); call_queue_.pop(); } else { empty = true; } } if (empty) { if (!persistent_) { ROS_DEBUG_NAMED("superdebug", "Dropping non-persistent client to service [%s]", service_name_.c_str()); connection_->drop(Connection::Destructing); } else { ROS_DEBUG_NAMED("superdebug", "Keeping persistent client to service [%s]", service_name_.c_str()); } } else { SerializedMessage request; { boost::mutex::scoped_lock lock(call_queue_mutex_); request = current_call_->req_; } connection_->write(request.buf, request.num_bytes, boost::bind(&ServiceServerLink::onRequestWritten, this, _1)); } } bool ServiceServerLink::call(const SerializedMessage& req, SerializedMessage& resp) { CallInfoPtr info(boost::make_shared<CallInfo>()); info->req_ = req; info->resp_ = &resp; info->success_ = false; info->finished_ = false; info->call_finished_ = false; info->caller_thread_id_ = boost::this_thread::get_id(); //ros::WallDuration(0.1).sleep(); bool immediate = false; { boost::mutex::scoped_lock lock(call_queue_mutex_); if (connection_->isDropped()) { ROSCPP_LOG_DEBUG("ServiceServerLink::call called on dropped connection for service [%s]", service_name_.c_str()); info->call_finished_ = true; return false; } if (call_queue_.empty() && header_written_ && header_read_) { immediate = true; } call_queue_.push(info); } if (immediate) { processNextCall(); } { boost::mutex::scoped_lock lock(info->finished_mutex_); while (!info->finished_) { info->finished_condition_.wait(lock); } } info->call_finished_ = true; if (info->exception_string_.length() > 0) { ROS_ERROR("Service call failed: service [%s] responded with an error: %s", service_name_.c_str(), info->exception_string_.c_str()); } return info->success_; } bool ServiceServerLink::isValid() const { return !dropped_; } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/statistics.cpp
/* * Copyright (C) 2013-2014, Dariush Forouher * * 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/statistics.h" #include "ros/node_handle.h" #include <rosgraph_msgs/TopicStatistics.h> #include "ros/this_node.h" #include "ros/message_traits.h" #include "std_msgs/Header.h" #include "ros/param.h" namespace ros { StatisticsLogger::StatisticsLogger() : pub_frequency_(1.0) { } void StatisticsLogger::init(const SubscriptionCallbackHelperPtr& helper) { hasHeader_ = helper->hasHeader(); param::param("/enable_statistics", enable_statistics, false); param::param("/statistics_window_min_elements", min_elements, 10); param::param("/statistics_window_max_elements", max_elements, 100); param::param("/statistics_window_min_size", min_window, 4); param::param("/statistics_window_max_size", max_window, 64); } void StatisticsLogger::callback(const boost::shared_ptr<M_string>& connection_header, const std::string& topic, const std::string& callerid, const SerializedMessage& m, const uint64_t& bytes_sent, const ros::Time& received_time, bool dropped) { (void)connection_header; struct StatData stats; if (!enable_statistics) { return; } // ignore /clock for safety and /statistics to reduce noise if (topic == "/statistics" || topic == "/clock") { return; } // callerid identifies the connection std::map<std::string, struct StatData>::iterator stats_it = map_.find(callerid); if (stats_it == map_.end()) { // this is the first time, we received something on this connection stats.stat_bytes_last = 0; stats.dropped_msgs = 0; stats.last_seq = 0; stats.last_publish = ros::Time::now(); map_[callerid] = stats; } else { stats = map_[callerid]; } stats.arrival_time_list.push_back(received_time); if (dropped) { stats.dropped_msgs++; } // try to extract header, if the message has one. this fails sometimes, // therefore the try-catch if (hasHeader_) { try { std_msgs::Header header; ros::serialization::IStream stream(m.message_start, m.num_bytes - (m.message_start - m.buf.get())); ros::serialization::deserialize(stream, header); stats.age_list.push_back(received_time - header.stamp); } catch (ros::serialization::StreamOverrunException& e) { ROS_DEBUG("Error during header extraction for statistics (topic=%s, message_length=%li)", topic.c_str(), m.num_bytes - (m.message_start - m.buf.get())); hasHeader_ = false; } } // should publish new statistics? if (stats.last_publish + ros::Duration(pub_frequency_) < received_time) { ros::Time window_start = stats.last_publish; stats.last_publish = received_time; // fill the message with the aggregated data rosgraph_msgs::TopicStatistics msg; msg.topic = topic; msg.node_pub = callerid; msg.node_sub = ros::this_node::getName(); msg.window_start = window_start; msg.window_stop = received_time; msg.delivered_msgs = stats.arrival_time_list.size(); msg.dropped_msgs = stats.dropped_msgs; msg.traffic = bytes_sent - stats.stat_bytes_last; // not all message types have this if (stats.age_list.size() > 0) { msg.stamp_age_mean = ros::Duration(0); msg.stamp_age_max = ros::Duration(0); for(std::list<ros::Duration>::iterator it = stats.age_list.begin(); it != stats.age_list.end(); it++) { ros::Duration age = *it; msg.stamp_age_mean += age; if (age > msg.stamp_age_max) { msg.stamp_age_max = age; } } msg.stamp_age_mean *= 1.0 / stats.age_list.size(); double stamp_age_variance = 0.0; for(std::list<ros::Duration>::iterator it = stats.age_list.begin(); it != stats.age_list.end(); it++) { ros::Duration t = msg.stamp_age_mean - *it; stamp_age_variance += t.toSec() * t.toSec(); } double stamp_age_stddev = sqrt(stamp_age_variance / stats.age_list.size()); try { msg.stamp_age_stddev = ros::Duration(stamp_age_stddev); } catch(std::runtime_error& e) { msg.stamp_age_stddev = ros::Duration(0); ROS_WARN_STREAM("Error updating stamp_age_stddev for topic [" << topic << "]" << " from node [" << callerid << "]," << " likely due to the time between the mean stamp age and this message being exceptionally large." << " Exception was: " << e.what()); ROS_DEBUG_STREAM("Mean stamp age was: " << msg.stamp_age_mean << " - std_dev of: " << stamp_age_stddev); } } else { // in that case, set to NaN msg.stamp_age_mean = ros::Duration(0); msg.stamp_age_stddev = ros::Duration(0); msg.stamp_age_max = ros::Duration(0); } // first, calculate the mean period between messages in this connection // we need at least two messages in the window for this. if (stats.arrival_time_list.size() > 1) { msg.period_mean = ros::Duration(0); msg.period_max = ros::Duration(0); ros::Time prev; for(std::list<ros::Time>::iterator it = stats.arrival_time_list.begin(); it != stats.arrival_time_list.end(); it++) { if (it == stats.arrival_time_list.begin()) { prev = *it; continue; } ros::Duration period = *it - prev; msg.period_mean += period; if (period > msg.period_max) msg.period_max = period; prev = *it; } msg.period_mean *= 1.0 / (stats.arrival_time_list.size() - 1); // then, calc the stddev msg.period_stddev = ros::Duration(0); for(std::list<ros::Time>::iterator it = stats.arrival_time_list.begin(); it != stats.arrival_time_list.end(); it++) { if (it == stats.arrival_time_list.begin()) { prev = *it; continue; } ros::Duration period = *it - prev; ros::Duration t = msg.period_mean - period; msg.period_stddev += ros::Duration(t.toSec() * t.toSec()); prev = *it; } msg.period_stddev = ros::Duration(sqrt(msg.period_stddev.toSec() / (stats.arrival_time_list.size() - 1))); } else { // in that case, set to NaN msg.period_mean = ros::Duration(0); msg.period_stddev = ros::Duration(0); msg.period_max = ros::Duration(0); } if (!pub_.getTopic().length()) { ros::NodeHandle n("~"); // creating the publisher in the constructor results in a deadlock. so do it here. pub_ = n.advertise<rosgraph_msgs::TopicStatistics>("/statistics", 1); } pub_.publish(msg); // dynamic window resizing if (stats.arrival_time_list.size() > static_cast<size_t>(max_elements) && pub_frequency_ * 2 <= max_window) { pub_frequency_ *= 2; } if (stats.arrival_time_list.size() < static_cast<size_t>(min_elements) && pub_frequency_ / 2 >= min_window) { pub_frequency_ /= 2; } // clear the window stats.age_list.clear(); stats.arrival_time_list.clear(); stats.dropped_msgs = 0; stats.stat_bytes_last = bytes_sent; } // store the stats for this connection map_[callerid] = stats; } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/timer.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/timer.h" #include "ros/timer_manager.h" namespace ros { Timer::Impl::Impl() : started_(false) , timer_handle_(-1) { } Timer::Impl::~Impl() { ROS_DEBUG("Timer deregistering callbacks."); stop(); } bool Timer::Impl::isValid() { return !period_.isZero(); } void Timer::Impl::start() { if (!started_) { VoidConstPtr tracked_object; if (has_tracked_object_) { tracked_object = tracked_object_.lock(); } timer_handle_ = TimerManager<Time, Duration, TimerEvent>::global().add(period_, callback_, callback_queue_, tracked_object, oneshot_); started_ = true; } } void Timer::Impl::stop() { if (started_) { started_ = false; TimerManager<Time, Duration, TimerEvent>::global().remove(timer_handle_); timer_handle_ = -1; } } bool Timer::Impl::hasPending() { if (!isValid() || timer_handle_ == -1) { return false; } return TimerManager<Time, Duration, TimerEvent>::global().hasPending(timer_handle_); } void Timer::Impl::setPeriod(const Duration& period, bool reset) { period_ = period; TimerManager<Time, Duration, TimerEvent>::global().setPeriod(timer_handle_, period, reset); } Timer::Timer(const TimerOptions& ops) : impl_(new Impl) { impl_->period_ = ops.period; impl_->callback_ = ops.callback; impl_->callback_queue_ = ops.callback_queue; impl_->tracked_object_ = ops.tracked_object; impl_->has_tracked_object_ = (ops.tracked_object != NULL); impl_->oneshot_ = ops.oneshot; } Timer::Timer(const Timer& rhs) { impl_ = rhs.impl_; } Timer::~Timer() { } void Timer::start() { if (impl_) { impl_->start(); } } void Timer::stop() { if (impl_) { impl_->stop(); } } bool Timer::hasPending() { if (impl_) { return impl_->hasPending(); } return false; } void Timer::setPeriod(const Duration& period, bool reset) { if (impl_) { impl_->setPeriod(period, reset); } } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/subscriber.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/subscriber.h" #include "ros/node_handle.h" #include "ros/topic_manager.h" namespace ros { Subscriber::Impl::Impl() : unsubscribed_(false) { } Subscriber::Impl::~Impl() { ROS_DEBUG("Subscriber on '%s' deregistering callbacks.", topic_.c_str()); unsubscribe(); } bool Subscriber::Impl::isValid() const { return !unsubscribed_; } void Subscriber::Impl::unsubscribe() { if (!unsubscribed_) { unsubscribed_ = true; TopicManager::instance()->unsubscribe(topic_, helper_); node_handle_.reset(); helper_.reset(); } } Subscriber::Subscriber(const std::string& topic, const NodeHandle& node_handle, const SubscriptionCallbackHelperPtr& helper) : impl_(boost::make_shared<Impl>()) { impl_->topic_ = topic; impl_->node_handle_ = boost::make_shared<NodeHandle>(node_handle); impl_->helper_ = helper; } Subscriber::Subscriber(const Subscriber& rhs) { impl_ = rhs.impl_; } Subscriber::~Subscriber() { } void Subscriber::shutdown() { if (impl_) { impl_->unsubscribe(); } } std::string Subscriber::getTopic() const { if (impl_) { return impl_->topic_; } return std::string(); } uint32_t Subscriber::getNumPublishers() const { if (impl_ && impl_->isValid()) { return TopicManager::instance()->getNumPublishers(impl_->topic_); } return 0; } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/config.h.in
#cmakedefine HAVE_TRUNC #cmakedefine HAVE_IFADDRS_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/poll_set.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/poll_set.h" #include "ros/file_log.h" #include "ros/transport/transport.h" #include <ros/assert.h> #include <boost/bind.hpp> #include <fcntl.h> namespace ros { PollSet::PollSet() : sockets_changed_(false) { if ( create_signal_pair(signal_pipe_) != 0 ) { ROS_FATAL("create_signal_pair() failed"); ROS_BREAK(); } addSocket(signal_pipe_[0], boost::bind(&PollSet::onLocalPipeEvents, this, _1)); addEvents(signal_pipe_[0], POLLIN); } PollSet::~PollSet() { close_signal_pair(signal_pipe_); } bool PollSet::addSocket(int fd, const SocketUpdateFunc& update_func, const TransportPtr& transport) { SocketInfo info; info.fd_ = fd; info.events_ = 0; info.transport_ = transport; info.func_ = update_func; { boost::mutex::scoped_lock lock(socket_info_mutex_); bool b = socket_info_.insert(std::make_pair(fd, info)).second; if (!b) { ROSCPP_LOG_DEBUG("PollSet: Tried to add duplicate fd [%d]", fd); return false; } sockets_changed_ = true; } signal(); return true; } bool PollSet::delSocket(int fd) { if(fd < 0) { return false; } boost::mutex::scoped_lock lock(socket_info_mutex_); M_SocketInfo::iterator it = socket_info_.find(fd); if (it != socket_info_.end()) { socket_info_.erase(it); { boost::mutex::scoped_lock lock(just_deleted_mutex_); just_deleted_.push_back(fd); } sockets_changed_ = true; signal(); return true; } ROSCPP_LOG_DEBUG("PollSet: Tried to delete fd [%d] which is not being tracked", fd); return false; } bool PollSet::addEvents(int sock, int events) { boost::mutex::scoped_lock lock(socket_info_mutex_); M_SocketInfo::iterator it = socket_info_.find(sock); if (it == socket_info_.end()) { ROSCPP_LOG_DEBUG("PollSet: Tried to add events [%d] to fd [%d] which does not exist in this pollset", events, sock); return false; } it->second.events_ |= events; signal(); return true; } bool PollSet::delEvents(int sock, int events) { boost::mutex::scoped_lock lock(socket_info_mutex_); M_SocketInfo::iterator it = socket_info_.find(sock); if (it != socket_info_.end()) { it->second.events_ &= ~events; } else { ROSCPP_LOG_DEBUG("PollSet: Tried to delete events [%d] to fd [%d] which does not exist in this pollset", events, sock); return false; } signal(); return true; } void PollSet::signal() { boost::mutex::scoped_try_lock lock(signal_mutex_); if (lock.owns_lock()) { char b = 0; if (write_signal(signal_pipe_[1], &b, 1) < 0) { // do nothing... this prevents warnings on gcc 4.3 } } } void PollSet::update(int poll_timeout) { createNativePollset(); // Poll across the sockets we're servicing int ret; size_t ufds_count = ufds_.size(); if((ret = poll_sockets(&ufds_.front(), ufds_count, poll_timeout)) < 0) { ROS_ERROR_STREAM("poll failed with error " << last_socket_error_string()); } else if (ret > 0) // ret = 0 implies the poll timed out, nothing to do { // We have one or more sockets to service for(size_t i=0; i<ufds_count; i++) { if (ufds_[i].revents == 0) { continue; } SocketUpdateFunc func; TransportPtr transport; int events = 0; { boost::mutex::scoped_lock lock(socket_info_mutex_); M_SocketInfo::iterator it = socket_info_.find(ufds_[i].fd); // the socket has been entirely deleted if (it == socket_info_.end()) { continue; } const SocketInfo& info = it->second; // Store off the function and transport in case the socket is deleted from another thread func = info.func_; transport = info.transport_; events = info.events_; } // If these are registered events for this socket, OR the events are ERR/HUP/NVAL, // call through to the registered function int revents = ufds_[i].revents; if (func && ((events & revents) || (revents & POLLERR) || (revents & POLLHUP) || (revents & POLLNVAL))) { bool skip = false; if (revents & (POLLNVAL|POLLERR|POLLHUP)) { // If a socket was just closed and then the file descriptor immediately reused, we can // get in here with what we think is a valid socket (since it was just re-added to our set) // but which is actually referring to the previous fd with the same #. If this is the case, // we ignore the first instance of one of these errors. If it's a real error we'll // hit it again next time through. boost::mutex::scoped_lock lock(just_deleted_mutex_); if (std::find(just_deleted_.begin(), just_deleted_.end(), ufds_[i].fd) != just_deleted_.end()) { skip = true; } } if (!skip) { func(revents & (events|POLLERR|POLLHUP|POLLNVAL)); } } ufds_[i].revents = 0; } boost::mutex::scoped_lock lock(just_deleted_mutex_); just_deleted_.clear(); } } void PollSet::createNativePollset() { boost::mutex::scoped_lock lock(socket_info_mutex_); if (!sockets_changed_) { return; } // Build the list of structures to pass to poll for the sockets we're servicing ufds_.resize(socket_info_.size()); M_SocketInfo::iterator sock_it = socket_info_.begin(); M_SocketInfo::iterator sock_end = socket_info_.end(); for (int i = 0; sock_it != sock_end; ++sock_it, ++i) { const SocketInfo& info = sock_it->second; socket_pollfd& pfd = ufds_[i]; pfd.fd = info.fd_; pfd.events = info.events_; pfd.revents = 0; } } void PollSet::onLocalPipeEvents(int events) { if(events & POLLIN) { char b; while(read_signal(signal_pipe_[0], &b, 1) > 0) { //do nothing keep draining }; } } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/master.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/master.h" #include "ros/broadcast_manager.h" #include "ros/xmlrpc_manager.h" #include "ros/this_node.h" #include "ros/init.h" #include "ros/network.h" #include <ros/console.h> #include <ros/assert.h> #include "XmlRpc.h" namespace ros { namespace master { uint32_t g_port = 0; std::string g_host; std::string g_uri; ros::WallDuration g_retry_timeout; void init(const M_string& remappings) { M_string::const_iterator it = remappings.find("__master"); if (it != remappings.end()) { g_uri = it->second; } if (g_uri.empty()) { char *master_uri_env = NULL; #ifdef _MSC_VER _dupenv_s(&master_uri_env, NULL, "ROS_MASTER_URI"); #else master_uri_env = getenv("ROS_MASTER_URI"); #endif if (!master_uri_env) { ROS_FATAL( "ROS_MASTER_URI is not defined in the environment. Either " \ "type the following or (preferrably) add this to your " \ "~/.bashrc file in order set up your " \ "local machine as a ROS master:\n\n" \ "export ROS_MASTER_URI=http://localhost:11311\n\n" \ "then, type 'roscore' in another shell to actually launch " \ "the master program."); ROS_BREAK(); } g_uri = master_uri_env; #ifdef _MSC_VER // http://msdn.microsoft.com/en-us/library/ms175774(v=vs.80).aspx free(master_uri_env); #endif } // Split URI into if (!network::splitURI(g_uri, g_host, g_port)) { ROS_FATAL( "Couldn't parse the master URI [%s] into a host:port pair.", g_uri.c_str()); ROS_BREAK(); } } const std::string& getHost() { return g_host; } uint32_t getPort() { return g_port; } const std::string& getURI() { return g_uri; } void setRetryTimeout(ros::WallDuration timeout) { if (timeout < ros::WallDuration(0)) { ROS_FATAL("retry timeout must not be negative."); ROS_BREAK(); } g_retry_timeout = timeout; } bool check() { XmlRpc::XmlRpcValue args, result, payload; args[0] = this_node::getName(); return execute("getPid", args, result, payload, false); } bool getTopics(V_TopicInfo& topics) { BroadcastManager::instance()->getTopicTypes(topics); return true; } bool getNodes(V_string& nodes) { BroadcastManager::instance()->getNodes(nodes); return true; } #if defined(__APPLE__) boost::mutex g_xmlrpc_call_mutex; #endif bool execute(const std::string& method, const XmlRpc::XmlRpcValue& request, XmlRpc::XmlRpcValue& response, XmlRpc::XmlRpcValue& payload, bool wait_for_master) { ros::WallTime start_time = ros::WallTime::now(); std::string master_host = getHost(); uint32_t master_port = getPort(); XmlRpc::XmlRpcClient *c = XMLRPCManager::instance()->getXMLRPCClient(master_host, master_port, "/"); bool printed = false; bool slept = false; bool ok = true; do { bool b = false; { #if defined(__APPLE__) boost::mutex::scoped_lock lock(g_xmlrpc_call_mutex); #endif b = c->execute(method.c_str(), request, response); } ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown(); if (!b && ok) { if (!printed && wait_for_master) { ROS_ERROR("[%s] Failed to contact master at [%s:%d]. %s", method.c_str(), master_host.c_str(), master_port, wait_for_master ? "Retrying..." : ""); printed = true; } if (!wait_for_master) { XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } if (!g_retry_timeout.isZero() && (ros::WallTime::now() - start_time) >= g_retry_timeout) { ROS_ERROR("[%s] Timed out trying to connect to the master after [%f] seconds", method.c_str(), g_retry_timeout.toSec()); XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } ros::WallDuration(0.05).sleep(); slept = true; } else { if (!XMLRPCManager::instance()->validateXmlrpcResponse(method, response, payload)) { XMLRPCManager::instance()->releaseXMLRPCClient(c); return false; } break; } ok = !ros::isShuttingDown() && !XMLRPCManager::instance()->isShuttingDown(); } while(ok); if (ok && slept) { ROS_INFO("Connected to master at [%s:%d]", master_host.c_str(), master_port); } XMLRPCManager::instance()->releaseXMLRPCClient(c); return true; } } // namespace master } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/names.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/names.h" #include "ros/this_node.h" #include "ros/file_log.h" #include <ros/console.h> #include <ros/assert.h> #include <cstring> namespace ros { namespace names { M_string g_remappings; M_string g_unresolved_remappings; const M_string& getRemappings() { return g_remappings; } const M_string& getUnresolvedRemappings() { return g_unresolved_remappings; } bool isValidCharInName(char c) { if (isalnum(c) || c == '/' || c == '_') { return true; } return false; } bool validate(const std::string& name, std::string& error) { if (name.empty()) { return true; } // First element is special, can be only ~ / or alpha char c = name[0]; if (!isalpha(c) && c != '/' && c != '~') { std::stringstream ss; ss << "Character [" << c << "] is not valid as the first character in Graph Resource Name [" << name << "]. Valid characters are a-z, A-Z, / and in some cases ~."; error = ss.str(); return false; } for (size_t i = 1; i < name.size(); ++i) { c = name[i]; if (!isValidCharInName(c)) { std::stringstream ss; ss << "Character [" << c << "] at element [" << i << "] is not valid in Graph Resource Name [" << name <<"]. Valid characters are a-z, A-Z, 0-9, / and _."; error = ss.str(); return false; } } return true; } std::string clean(const std::string& name) { std::string clean = name; size_t pos = clean.find("//"); while (pos != std::string::npos) { clean.erase(pos, 1); pos = clean.find("//", pos); } if (*clean.rbegin() == '/') { clean.erase(clean.size() - 1, 1); } return clean; } std::string append(const std::string& left, const std::string& right) { return clean(left + "/" + right); } std::string remap(const std::string& name) { std::string resolved = resolve(name, false); M_string::const_iterator it = g_remappings.find(resolved); if (it != g_remappings.end()) { return it->second; } return name; } std::string resolve(const std::string& name, bool _remap) { std::string s = resolve(this_node::getNamespace(), name, _remap); return s; } std::string resolve(const std::string& ns, const std::string& name, bool _remap) { std::string error; if (!validate(name, error)) { throw InvalidNameException(error); } if (name.empty()) { if (ns.empty()) { return "/"; } if (ns[0] == '/') { return ns; } return append("/", ns); } std::string copy = name; if (copy[0] == '~') { copy = append(this_node::getName(), copy.substr(1)); } if (copy[0] != '/') { copy = append("/", append(ns, copy)); } copy = clean(copy); if (_remap) { copy = remap(copy); } return copy; } void init(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& left = it->first; const std::string& right = it->second; if (!left.empty() && left[0] != '_' && left != this_node::getName()) { std::string resolved_left = resolve(left, false); std::string resolved_right = resolve(right, false); g_remappings[resolved_left] = resolved_right; g_unresolved_remappings[left] = right; } } } std::string parentNamespace(const std::string& name) { std::string error; if (!validate(name, error)) { throw InvalidNameException(error); } if (!name.compare("")) return ""; if (!name.compare("/")) return "/"; std::string stripped_name; // rstrip trailing slash if (name.find_last_of('/') == name.size()-1) stripped_name = name.substr(0, name.size() -2); else stripped_name = name; //pull everything up to the last / size_t last_pos = stripped_name.find_last_of('/'); if (last_pos == std::string::npos) { return ""; } else if (last_pos == 0) return "/"; return stripped_name.substr(0, last_pos); } } // namespace names } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/intraprocess_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/intraprocess_publisher_link.h" #include "ros/intraprocess_subscriber_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 { IntraProcessPublisherLink::IntraProcessPublisherLink(const SubscriptionPtr& parent, const std::string& xmlrpc_uri, const TransportHints& transport_hints) : PublisherLink(parent, xmlrpc_uri, transport_hints) , dropped_(false) { } IntraProcessPublisherLink::~IntraProcessPublisherLink() { } void IntraProcessPublisherLink::setPublisher(const IntraProcessSubscriberLinkPtr& publisher) { publisher_ = publisher; SubscriptionPtr parent = parent_.lock(); ROS_ASSERT(parent); Header header; M_stringPtr values = header.getValues(); (*values)["callerid"] = this_node::getName(); (*values)["topic"] = parent->getName(); (*values)["type"] = publisher->getDataType(); (*values)["md5sum"] = publisher->getMD5Sum(); (*values)["message_definition"] = publisher->getMessageDefinition(); (*values)["latching"] = publisher->isLatching() ? "1" : "0"; setHeader(header); } void IntraProcessPublisherLink::drop() { { boost::recursive_mutex::scoped_lock lock(drop_mutex_); if (dropped_) { return; } dropped_ = true; } if (publisher_) { publisher_->drop(); publisher_.reset(); } if (SubscriptionPtr parent = parent_.lock()) { ROSCPP_LOG_DEBUG("Connection to local publisher on topic [%s] dropped", parent->getName().c_str()); parent->removePublisherLink(shared_from_this()); } } void IntraProcessPublisherLink::handleMessage(const SerializedMessage& m, bool ser, bool nocopy) { boost::recursive_mutex::scoped_lock lock(drop_mutex_); if (dropped_) { return; } stats_.bytes_received_ += m.num_bytes; stats_.messages_received_++; SubscriptionPtr parent = parent_.lock(); if (parent) { stats_.drops_ += parent->handleMessage(m, ser, nocopy, header_.getValues(), shared_from_this()); } } std::string IntraProcessPublisherLink::getTransportType() { return std::string("INTRAPROCESS"); } std::string IntraProcessPublisherLink::getTransportInfo() { // TODO: Check if we can dump more useful information here return getTransportType(); } void IntraProcessPublisherLink::getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti) { boost::recursive_mutex::scoped_lock lock(drop_mutex_); if (dropped_) { ser = false; nocopy = false; return; } SubscriptionPtr parent = parent_.lock(); if (parent) { parent->getPublishTypes(ser, nocopy, ti); } else { ser = true; nocopy = false; } } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/io.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. */ /***************************************************************************** ** Includes *****************************************************************************/ #include <ros/io.h> #include <ros/assert.h> // don't need if we dont call the pipe functions. #include <errno.h> // for EFAULT and co. #include <iostream> #include <sstream> #ifdef WIN32 #else #include <cstring> // strerror #include <fcntl.h> // for non-blocking configuration #endif /***************************************************************************** ** Namespaces *****************************************************************************/ namespace ros { int last_socket_error() { #ifdef WIN32 return WSAGetLastError(); #else return errno; #endif } const char* last_socket_error_string() { #ifdef WIN32 // could fix this to use FORMAT_MESSAGE and print a real string later, // but not high priority. std::stringstream ostream; ostream << "WSA Error: " << WSAGetLastError(); return ostream.str().c_str(); #else return strerror(errno); #endif } bool last_socket_error_is_would_block() { #if defined(WIN32) if ( WSAGetLastError() == WSAEWOULDBLOCK ) { return true; } else { return false; } #else if ( ( errno == EAGAIN ) || ( errno == EWOULDBLOCK ) ) { // posix permits either return true; } else { return false; } #endif } /***************************************************************************** ** Service Robotics/Libssh Functions *****************************************************************************/ /** * @brief A cross platform polling function for sockets. * * Windows doesn't have a polling function until Vista (WSAPoll) and even then * its implementation is not supposed to be great. This works for a broader * range of platforms and will suffice. * @param fds - the socket set (descriptor's and events) to poll for. * @param nfds - the number of descriptors to poll for. * @param timeout - timeout in milliseconds. * @return int : -1 on error, 0 on timeout, +ve number of structures with received events. */ int poll_sockets(socket_pollfd *fds, nfds_t nfds, int timeout) { #if defined(WIN32) fd_set readfds, writefds, exceptfds; struct timeval tv, *ptv; socket_fd_t max_fd; int rc; nfds_t i; if (fds == NULL) { errno = EFAULT; return -1; } FD_ZERO (&readfds); FD_ZERO (&writefds); FD_ZERO (&exceptfds); /********************* ** Compute fd sets **********************/ // also find the largest descriptor. for (rc = -1, max_fd = 0, i = 0; i < nfds; i++) { if (fds[i].fd == INVALID_SOCKET) { continue; } if (fds[i].events & (POLLIN | POLLRDNORM)) { FD_SET (fds[i].fd, &readfds); } if (fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND)) { FD_SET (fds[i].fd, &writefds); } if (fds[i].events & (POLLPRI | POLLRDBAND)) { FD_SET (fds[i].fd, &exceptfds); } if (fds[i].fd > max_fd && (fds[i].events & (POLLIN | POLLOUT | POLLPRI | POLLRDNORM | POLLRDBAND | POLLWRNORM | POLLWRBAND))) { max_fd = fds[i].fd; rc = 0; } } if (rc == -1) { errno = EINVAL; return -1; } /********************* ** Setting the timeout **********************/ if (timeout < 0) { ptv = NULL; } else { ptv = &tv; if (timeout == 0) { tv.tv_sec = 0; tv.tv_usec = 0; } else { tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; } } rc = select (max_fd + 1, &readfds, &writefds, &exceptfds, ptv); if (rc < 0) { return -1; } else if ( rc == 0 ) { return 0; } for (rc = 0, i = 0; i < nfds; i++) { if (fds[i].fd != INVALID_SOCKET) { fds[i].revents = 0; if (FD_ISSET(fds[i].fd, &readfds)) { int save_errno = errno; char data[64] = {0}; int ret; /* support for POLLHUP */ // just check if there's incoming data, without removing it from the queue. ret = recv(fds[i].fd, data, 64, MSG_PEEK); #ifdef WIN32 if ((ret == -1) && (errno == WSAESHUTDOWN || errno == WSAECONNRESET || (errno == WSAECONNABORTED) || errno == WSAENETRESET)) #else if ((ret == -1) && (errno == ESHUTDOWN || errno == ECONNRESET || (errno == ECONNABORTED) || errno == ENETRESET)) #endif { fds[i].revents |= POLLHUP; } else { fds[i].revents |= fds[i].events & (POLLIN | POLLRDNORM); } errno = save_errno; } if (FD_ISSET(fds[i].fd, &writefds)) { fds[i].revents |= fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND); } if (FD_ISSET(fds[i].fd, &exceptfds)) { fds[i].revents |= fds[i].events & (POLLPRI | POLLRDBAND); } if (fds[i].revents & ~POLLHUP) { rc++; } } else { fds[i].revents = POLLNVAL; } } return rc; #else // use an existing poll implementation int result = poll(fds, nfds, timeout); if ( result < 0 ) { // EINTR means that we got interrupted by a signal, and is not an error if(errno == EINTR) { result = 0; } } return result; #endif // poll_sockets functions } /***************************************************************************** ** Socket Utilities *****************************************************************************/ /** * Sets the socket as non blocking. * @return int : 0 on success, WSAGetLastError()/errno on failure. */ int set_non_blocking(socket_fd_t &socket) { #ifdef WIN32 u_long non_blocking = 1; if(ioctlsocket( socket, FIONBIO, &non_blocking ) != 0 ) { return WSAGetLastError(); } #else if(fcntl(socket, F_SETFL, O_NONBLOCK) == -1) { return errno; } #endif return 0; } /** * @brief Close the socket. * * @return int : 0 on success, -1 on failure. */ int close_socket(socket_fd_t &socket) { #ifdef WIN32 if(::closesocket(socket) == SOCKET_ERROR ) { return -1; } else { return 0; } #else if (::close(socket) < 0) { return -1; } else { return 0; } #endif //WIN32 } /***************************************************************************** ** Signal Pair *****************************************************************************/ /** * This code is primarily from the msdn socket tutorials. * @param signal_pair : a pair of sockets linked to each other over localhost. * @return 0 on success, -1 on failure. */ int create_signal_pair(signal_fd_t signal_pair[2]) { #ifdef WIN32 // use a socket pair signal_pair[0] = INVALID_SOCKET; signal_pair[1] = INVALID_SOCKET; union { struct sockaddr_in inaddr; struct sockaddr addr; } a; socklen_t addrlen = sizeof(a.inaddr); /********************* ** Listen Socket **********************/ socket_fd_t listen_socket = INVALID_SOCKET; listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listen_socket == INVALID_SOCKET) { return -1; } // allow it to be bound to an address already in use - do we actually need this? int reuse = 1; if (setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &reuse, (socklen_t) sizeof(reuse)) == SOCKET_ERROR ) { ::closesocket(listen_socket); return -1; } memset(&a, 0, sizeof(a)); a.inaddr.sin_family = AF_INET; a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // For TCP/IP, if the port is specified as zero, the service provider assigns // a unique port to the application from the dynamic client port range. a.inaddr.sin_port = 0; if (bind(listen_socket, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) { ::closesocket(listen_socket); return -1; } // we need this below because the system auto filled in some entries, e.g. port # if (getsockname(listen_socket, &a.addr, &addrlen) == SOCKET_ERROR) { ::closesocket(listen_socket); return -1; } // max 1 connection permitted if (listen(listen_socket, 1) == SOCKET_ERROR) { ::closesocket(listen_socket); return -1; } /********************* ** Connection **********************/ // do we need io overlapping? // DWORD flags = (make_overlapped ? WSA_FLAG_OVERLAPPED : 0); DWORD overlapped_flag = 0; signal_pair[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, overlapped_flag); if (signal_pair[0] == INVALID_SOCKET) { ::closesocket(listen_socket); ::closesocket(signal_pair[0]); return -1; } // reusing the information from above to connect to the listener if (connect(signal_pair[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) { ::closesocket(listen_socket); ::closesocket(signal_pair[0]); return -1; } /********************* ** Accept **********************/ signal_pair[1] = accept(listen_socket, NULL, NULL); if (signal_pair[1] == INVALID_SOCKET) { ::closesocket(listen_socket); ::closesocket(signal_pair[0]); ::closesocket(signal_pair[1]); return -1; } /********************* ** Nonblocking **********************/ // should we do this or should we set io overlapping? if ( (set_non_blocking(signal_pair[0]) != 0) || (set_non_blocking(signal_pair[1]) != 0) ) { ::closesocket(listen_socket); ::closesocket(signal_pair[0]); ::closesocket(signal_pair[1]); return -1; } /********************* ** Cleanup **********************/ ::closesocket(listen_socket); // the listener has done its job. return 0; #else // use a pipe pair // initialize signal_pair[0] = -1; signal_pair[1] = -1; if(pipe(signal_pair) != 0) { ROS_FATAL( "pipe() failed"); return -1; } if(fcntl(signal_pair[0], F_SETFL, O_NONBLOCK) == -1) { ROS_FATAL( "fcntl() failed"); return -1; } if(fcntl(signal_pair[1], F_SETFL, O_NONBLOCK) == -1) { ROS_FATAL( "fcntl() failed"); return -1; } return 0; #endif // create_pipe } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/single_subscriber_publisher.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/single_subscriber_publisher.h" #include "ros/subscriber_link.h" namespace ros { SingleSubscriberPublisher::SingleSubscriberPublisher(const SubscriberLinkPtr& link) : link_(link) { } SingleSubscriberPublisher::~SingleSubscriberPublisher() { } void SingleSubscriberPublisher::publish(const SerializedMessage& m) const { link_->enqueueMessage(m, true, true); } std::string SingleSubscriberPublisher::getTopic() const { return link_->getTopic(); } std::string SingleSubscriberPublisher::getSubscriberName() const { return link_->getDestinationCallerID(); } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service_client.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/service_client.h" #include "ros/service_server_link.h" #include "ros/connection.h" #include "ros/service_manager.h" #include "ros/service.h" namespace ros { ServiceClient::Impl::Impl() : is_shutdown_(false) { } ServiceClient::Impl::~Impl() { shutdown(); } void ServiceClient::Impl::shutdown() { if (!is_shutdown_) { if (!persistent_) { is_shutdown_ = true; } if (server_link_) { server_link_->getConnection()->drop(Connection::Destructing); server_link_.reset(); } } } bool ServiceClient::Impl::isValid() const { // Non-persistent connections are always valid if (!persistent_) { return true; } if (is_shutdown_) { return false; } if (!server_link_) { return false; } return server_link_->isValid(); } ServiceClient::ServiceClient(const std::string& service_name, bool persistent, const M_string& header_values, const std::string& service_md5sum) : impl_(new Impl) { impl_->name_ = service_name; impl_->persistent_ = persistent; impl_->header_values_ = header_values; impl_->service_md5sum_ = service_md5sum; if (persistent) { impl_->server_link_ = ServiceManager::instance()->createServiceServerLink(impl_->name_, impl_->persistent_, impl_->service_md5sum_, impl_->service_md5sum_, impl_->header_values_); } } ServiceClient::ServiceClient(const ServiceClient& rhs) { impl_ = rhs.impl_; } ServiceClient::~ServiceClient() { } bool ServiceClient::call(const SerializedMessage& req, SerializedMessage& resp, const std::string& service_md5sum) { if (service_md5sum != impl_->service_md5sum_) { ROS_ERROR("Call to service [%s] with md5sum [%s] does not match md5sum when the handle was created ([%s])", impl_->name_.c_str(), service_md5sum.c_str(), impl_->service_md5sum_.c_str()); return false; } ServiceServerLinkPtr link; if (impl_->persistent_) { if (!impl_->server_link_) { impl_->server_link_ = ServiceManager::instance()->createServiceServerLink(impl_->name_, impl_->persistent_, service_md5sum, service_md5sum, impl_->header_values_); if (!impl_->server_link_) { return false; } } link = impl_->server_link_; } else { link = ServiceManager::instance()->createServiceServerLink(impl_->name_, impl_->persistent_, service_md5sum, service_md5sum, impl_->header_values_); if (!link) { return false; } } bool ret = link->call(req, resp); link.reset(); // If we're shutting down but the node haven't finished yet, wait until we do while (ros::isShuttingDown() && ros::ok()) { ros::WallDuration(0.001).sleep(); } return ret; } bool ServiceClient::isValid() const { if (!impl_) { return false; } return impl_->isValid(); } bool ServiceClient::isPersistent() const { if (impl_) { return impl_->persistent_; } return false; } void ServiceClient::shutdown() { if (impl_) { impl_->shutdown(); } } bool ServiceClient::waitForExistence(ros::Duration timeout) { if (impl_) { return service::waitForService(impl_->name_, timeout); } return false; } bool ServiceClient::exists() { if (impl_) { return service::exists(impl_->name_, false); } return false; } std::string ServiceClient::getService() { if (impl_) { return impl_->name_; } return ""; } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/callback_queue.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/callback_queue.h" #include "ros/assert.h" #include <boost/scope_exit.hpp> namespace ros { CallbackQueue::CallbackQueue(bool enabled) : calling_(0) , enabled_(enabled) { } CallbackQueue::~CallbackQueue() { disable(); } void CallbackQueue::enable() { boost::mutex::scoped_lock lock(mutex_); enabled_ = true; condition_.notify_all(); } void CallbackQueue::disable() { boost::mutex::scoped_lock lock(mutex_); enabled_ = false; condition_.notify_all(); } void CallbackQueue::clear() { boost::mutex::scoped_lock lock(mutex_); callbacks_.clear(); } bool CallbackQueue::isEmpty() { boost::mutex::scoped_lock lock(mutex_); return callbacks_.empty() && calling_ == 0; } bool CallbackQueue::isEnabled() { boost::mutex::scoped_lock lock(mutex_); return enabled_; } void CallbackQueue::setupTLS() { if (!tls_.get()) { tls_.reset(new TLS); } } void CallbackQueue::addCallback(const CallbackInterfacePtr& callback, uint64_t removal_id) { CallbackInfo info; info.callback = callback; info.removal_id = removal_id; { boost::mutex::scoped_lock lock(id_info_mutex_); M_IDInfo::iterator it = id_info_.find(removal_id); if (it == id_info_.end()) { IDInfoPtr id_info(boost::make_shared<IDInfo>()); id_info->id = removal_id; id_info_.insert(std::make_pair(removal_id, id_info)); } } { boost::mutex::scoped_lock lock(mutex_); if (!enabled_) { return; } callbacks_.push_back(info); } condition_.notify_one(); } CallbackQueue::IDInfoPtr CallbackQueue::getIDInfo(uint64_t id) { boost::mutex::scoped_lock lock(id_info_mutex_); M_IDInfo::iterator it = id_info_.find(id); if (it != id_info_.end()) { return it->second; } return IDInfoPtr(); } void CallbackQueue::removeByID(uint64_t removal_id) { setupTLS(); { IDInfoPtr id_info; { boost::mutex::scoped_lock lock(id_info_mutex_); M_IDInfo::iterator it = id_info_.find(removal_id); if (it != id_info_.end()) { id_info = it->second; } else { return; } } // If we're being called from within a callback from our queue, we must unlock the shared lock we already own // here so that we can take a unique lock. We'll re-lock it later. if (tls_->calling_in_this_thread == id_info->id) { id_info->calling_rw_mutex.unlock_shared(); } { boost::unique_lock<boost::shared_mutex> rw_lock(id_info->calling_rw_mutex); boost::mutex::scoped_lock lock(mutex_); D_CallbackInfo::iterator it = callbacks_.begin(); for (; it != callbacks_.end();) { CallbackInfo& info = *it; if (info.removal_id == removal_id) { it = callbacks_.erase(it); } else { ++it; } } } if (tls_->calling_in_this_thread == id_info->id) { id_info->calling_rw_mutex.lock_shared(); } } // If we're being called from within a callback, we need to remove the callbacks that match the id that have already been // popped off the queue { D_CallbackInfo::iterator it = tls_->callbacks.begin(); D_CallbackInfo::iterator end = tls_->callbacks.end(); for (; it != end; ++it) { CallbackInfo& info = *it; if (info.removal_id == removal_id) { info.marked_for_removal = true; } } } { boost::mutex::scoped_lock lock(id_info_mutex_); id_info_.erase(removal_id); } } CallbackQueue::CallOneResult CallbackQueue::callOne(ros::WallDuration timeout) { setupTLS(); TLS* tls = tls_.get(); CallbackInfo cb_info; { boost::mutex::scoped_lock lock(mutex_); if (!enabled_) { return Disabled; } if (callbacks_.empty()) { if (!timeout.isZero()) { condition_.timed_wait(lock, boost::posix_time::microseconds(timeout.toSec() * 1000000.0f)); } if (callbacks_.empty()) { return Empty; } if (!enabled_) { return Disabled; } } D_CallbackInfo::iterator it = callbacks_.begin(); for (; it != callbacks_.end();) { CallbackInfo& info = *it; if (info.marked_for_removal) { it = callbacks_.erase(it); continue; } if (info.callback->ready()) { cb_info = info; it = callbacks_.erase(it); break; } ++it; } if (!cb_info.callback) { return TryAgain; } ++calling_; } bool was_empty = tls->callbacks.empty(); tls->callbacks.push_back(cb_info); if (was_empty) { tls->cb_it = tls->callbacks.begin(); } CallOneResult res = callOneCB(tls); if (res != Empty) { boost::mutex::scoped_lock lock(mutex_); --calling_; } return res; } void CallbackQueue::callAvailable(ros::WallDuration timeout) { setupTLS(); TLS* tls = tls_.get(); { boost::mutex::scoped_lock lock(mutex_); if (!enabled_) { return; } if (callbacks_.empty()) { if (!timeout.isZero()) { condition_.timed_wait(lock, boost::posix_time::microseconds(timeout.toSec() * 1000000.0f)); } if (callbacks_.empty() || !enabled_) { return; } } bool was_empty = tls->callbacks.empty(); tls->callbacks.insert(tls->callbacks.end(), callbacks_.begin(), callbacks_.end()); callbacks_.clear(); calling_ += tls->callbacks.size(); if (was_empty) { tls->cb_it = tls->callbacks.begin(); } } size_t called = 0; while (!tls->callbacks.empty()) { if (callOneCB(tls) != Empty) { ++called; } } { boost::mutex::scoped_lock lock(mutex_); calling_ -= called; } } CallbackQueue::CallOneResult CallbackQueue::callOneCB(TLS* tls) { // Check for a recursive call. If recursive, increment the current iterator. Otherwise // set the iterator it the beginning of the thread-local callbacks if (tls->calling_in_this_thread == 0xffffffffffffffffULL) { tls->cb_it = tls->callbacks.begin(); } if (tls->cb_it == tls->callbacks.end()) { return Empty; } ROS_ASSERT(!tls->callbacks.empty()); ROS_ASSERT(tls->cb_it != tls->callbacks.end()); CallbackInfo info = *tls->cb_it; CallbackInterfacePtr& cb = info.callback; IDInfoPtr id_info = getIDInfo(info.removal_id); if (id_info) { boost::shared_lock<boost::shared_mutex> rw_lock(id_info->calling_rw_mutex); uint64_t last_calling = tls->calling_in_this_thread; tls->calling_in_this_thread = id_info->id; CallbackInterface::CallResult result = CallbackInterface::Invalid; { // Ensure that thread id gets restored, even if callback throws. // This is done with RAII rather than try-catch so that the source // of the original exception is not masked in a crash report. BOOST_SCOPE_EXIT(&tls, &last_calling) { tls->calling_in_this_thread = last_calling; } BOOST_SCOPE_EXIT_END if (info.marked_for_removal) { tls->cb_it = tls->callbacks.erase(tls->cb_it); } else { tls->cb_it = tls->callbacks.erase(tls->cb_it); result = cb->call(); } } // Push TryAgain callbacks to the back of the shared queue if (result == CallbackInterface::TryAgain && !info.marked_for_removal) { boost::mutex::scoped_lock lock(mutex_); callbacks_.push_back(info); return TryAgain; } return Called; } else { tls->cb_it = tls->callbacks.erase(tls->cb_it); } return Called; } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/topic_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/topic_manager.h" #include "ros/broadcast_manager.h" #include "ros/xmlrpc_manager.h" #include "ros/connection_manager.h" #include "ros/poll_manager.h" #include "ros/publication.h" #include "ros/subscription.h" #include "ros/this_node.h" #include "ros/network.h" #include "ros/master.h" #include "ros/transport/transport_tcp.h" #include "ros/transport/transport_udp.h" #include "ros/rosout_appender.h" #include "ros/init.h" #include "ros/file_log.h" #include "ros/subscribe_options.h" #include "XmlRpc.h" #include <ros/console.h> using namespace XmlRpc; // A battle to be fought later using namespace std; // sigh /// \todo Locking can be significantly simplified here once the Node API goes away. namespace ros { TopicManagerPtr g_topic_manager; boost::mutex g_topic_manager_mutex; const TopicManagerPtr& TopicManager::instance() { if (!g_topic_manager) { boost::mutex::scoped_lock lock(g_topic_manager_mutex); if (!g_topic_manager) { g_topic_manager = boost::make_shared<TopicManager>(); } } return g_topic_manager; } TopicManager::TopicManager() : shutting_down_(false) { } TopicManager::~TopicManager() { shutdown(); } void TopicManager::start() { boost::mutex::scoped_lock shutdown_lock(shutting_down_mutex_); shutting_down_ = false; poll_manager_ = PollManager::instance(); connection_manager_ = ConnectionManager::instance(); xmlrpc_manager_ = XMLRPCManager::instance(); xmlrpc_manager_->bind("publisherUpdate", boost::bind(&TopicManager::pubUpdateCallback, this, _1, _2)); xmlrpc_manager_->bind("requestTopic", boost::bind(&TopicManager::requestTopicCallback, this, _1, _2)); xmlrpc_manager_->bind("getBusStats", boost::bind(&TopicManager::getBusStatsCallback, this, _1, _2)); xmlrpc_manager_->bind("getBusInfo", boost::bind(&TopicManager::getBusInfoCallback, this, _1, _2)); xmlrpc_manager_->bind("getSubscriptions", boost::bind(&TopicManager::getSubscriptionsCallback, this, _1, _2)); xmlrpc_manager_->bind("getPublications", boost::bind(&TopicManager::getPublicationsCallback, this, _1, _2)); poll_manager_->addPollThreadListener(boost::bind(&TopicManager::processPublishQueues, this)); } void TopicManager::shutdown() { boost::mutex::scoped_lock shutdown_lock(shutting_down_mutex_); if (shutting_down_) { return; } { boost::recursive_mutex::scoped_lock lock1(advertised_topics_mutex_); boost::mutex::scoped_lock lock2(subs_mutex_); shutting_down_ = true; } xmlrpc_manager_->unbind("publisherUpdate"); xmlrpc_manager_->unbind("requestTopic"); xmlrpc_manager_->unbind("getBusStats"); xmlrpc_manager_->unbind("getBusInfo"); xmlrpc_manager_->unbind("getSubscriptions"); xmlrpc_manager_->unbind("getPublications"); ROSCPP_LOG_DEBUG("Shutting down topics..."); ROSCPP_LOG_DEBUG(" shutting down publishers"); { boost::recursive_mutex::scoped_lock adv_lock(advertised_topics_mutex_); for (V_Publication::iterator i = advertised_topics_.begin(); i != advertised_topics_.end(); ++i) { if(!(*i)->isDropped()) { unregisterPublisher((*i)->getName()); } (*i)->drop(); } advertised_topics_.clear(); } // unregister all of our subscriptions ROSCPP_LOG_DEBUG(" shutting down subscribers"); { boost::mutex::scoped_lock subs_lock(subs_mutex_); for (L_Subscription::iterator s = subscriptions_.begin(); s != subscriptions_.end(); ++s) { // Remove us as a subscriber from the master unregisterSubscriber((*s)->getName()); // now, drop our side of the connection (*s)->shutdown(); } subscriptions_.clear(); } } void TopicManager::checkAndRemoveSHMSegment(std::string topic) { if (!ros::ok()) { return; } // Get node info std::set<std::string> pi = BroadcastManager::instance()->getPubs(topic); std::set<std::string> si = BroadcastManager::instance()->getSubs(topic); // Count the num int count = pi.size() + si.size(); // Remove segment if (count == 1) { sharedmem_transport::SharedMemoryUtil sharedmem_util; sharedmem_util.remove_segment(topic.c_str()); } } void TopicManager::processPublishQueues() { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); V_Publication::iterator it = advertised_topics_.begin(); V_Publication::iterator end = advertised_topics_.end(); for (; it != end; ++it) { const PublicationPtr& pub = *it; pub->processPublishQueue(); } } void TopicManager::getAdvertisedTopics(V_string& topics) { boost::mutex::scoped_lock lock(advertised_topic_names_mutex_); topics.resize(advertised_topic_names_.size()); std::copy(advertised_topic_names_.begin(), advertised_topic_names_.end(), topics.begin()); } void TopicManager::getSubscribedTopics(V_string& topics) { boost::mutex::scoped_lock lock(subs_mutex_); topics.reserve(subscriptions_.size()); L_Subscription::const_iterator it = subscriptions_.begin(); L_Subscription::const_iterator end = subscriptions_.end(); for (; it != end; ++it) { const SubscriptionPtr& sub = *it; topics.push_back(sub->getName()); } } PublicationPtr TopicManager::lookupPublication(const std::string& topic) { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); return lookupPublicationWithoutLock(topic); } SubscriptionPtr TopicManager::lookupSubscription(const std::string& topic) { boost::mutex::scoped_lock lock(subs_mutex_); return lookupSubscriptionWithoutLock(topic); } L_Subscription TopicManager::getAllSubscription() { return subscriptions_ ; } bool md5sumsMatch(const std::string& lhs, const std::string& rhs) { return lhs == "*" || rhs == "*" || lhs == rhs; } bool TopicManager::addSubCallback(const SubscribeOptions& ops) { // spin through the subscriptions and see if we find a match. if so, use it. bool found = false; bool found_topic = false; SubscriptionPtr sub; { if (isShuttingDown()) { return false; } for (L_Subscription::iterator s = subscriptions_.begin(); s != subscriptions_.end() && !found; ++s) { sub = *s; if (!sub->isDropped() && sub->getName() == ops.topic) { found_topic = true; if (md5sumsMatch(ops.md5sum, sub->md5sum())) { found = true; } break; } } } if (found_topic && !found) { std::stringstream ss; ss << "Tried to subscribe to a topic with the same name but different md5sum as a topic that was already subscribed [" << ops.datatype << "/" << ops.md5sum << " vs. " << sub->datatype() << "/" << sub->md5sum() << "]"; throw ConflictingSubscriptionException(ss.str()); } else if (found) { if (!sub->addCallback(ops.helper, ops.md5sum, ops.callback_queue, ops.queue_size, ops.tracked_object, ops.allow_concurrent_callbacks)) { return false; } } return found; } // this function has the subscription code that doesn't need to be templated. bool TopicManager::subscribe(const SubscribeOptions& ops) { { boost::mutex::scoped_lock lock(subs_mutex_); if (addSubCallback(ops)) { return true; } if (isShuttingDown()) { return false; } if (ops.md5sum.empty()) { throw InvalidParameterException("Subscribing to topic [" + ops.topic + "] with an empty md5sum"); } if (ops.datatype.empty()) { throw InvalidParameterException("Subscribing to topic [" + ops.topic + "] with an empty datatype"); } if (!ops.helper) { throw InvalidParameterException("Subscribing to topic [" + ops.topic + "] without a callback"); } const std::string& md5sum = ops.md5sum; std::string datatype = ops.datatype; SubscriptionPtr s(boost::make_shared<Subscription>(ops.topic, md5sum, datatype, ops.transport_hints)); s->addCallback(ops.helper, ops.md5sum, ops.callback_queue, ops.queue_size, ops.tracked_object, ops.allow_concurrent_callbacks); if (!registerSubscriber(s, ops.datatype)) { ROS_WARN("couldn't register subscriber on topic [%s]", ops.topic.c_str()); s->shutdown(); return false; } subscriptions_.push_back(s); } BroadcastManager::instance()->publisherUpdate(ops.topic); return true; } bool TopicManager::advertise(const AdvertiseOptions& ops, const SubscriberCallbacksPtr& callbacks) { if (ops.datatype == "*") { std::stringstream ss; ss << "Advertising with * as the datatype is not allowed. Topic [" << ops.topic << "]"; throw InvalidParameterException(ss.str()); } if (ops.md5sum == "*") { std::stringstream ss; ss << "Advertising with * as the md5sum is not allowed. Topic [" << ops.topic << "]"; throw InvalidParameterException(ss.str()); } if (ops.md5sum.empty()) { throw InvalidParameterException("Advertising on topic [" + ops.topic + "] with an empty md5sum"); } if (ops.datatype.empty()) { throw InvalidParameterException("Advertising on topic [" + ops.topic + "] with an empty datatype"); } if (ops.message_definition.empty()) { ROS_WARN("Advertising on topic [%s] with an empty message definition. Some tools (e.g. rosbag) may not work correctly.", ops.topic.c_str()); } PublicationPtr pub; { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); if (isShuttingDown()) { return false; } pub = lookupPublicationWithoutLock(ops.topic); if (pub && pub->getNumCallbacks() == 0) { pub.reset(); } if (pub) { if (pub->getMD5Sum() != ops.md5sum) { ROS_ERROR("Tried to advertise on topic [%s] with md5sum [%s] and datatype [%s], but the topic is already advertised as md5sum [%s] and datatype [%s]", ops.topic.c_str(), ops.md5sum.c_str(), ops.datatype.c_str(), pub->getMD5Sum().c_str(), pub->getDataType().c_str()); return false; } pub->addCallbacks(callbacks); return true; } pub = PublicationPtr(boost::make_shared<Publication>(ops.topic, ops.datatype, ops.md5sum, ops.message_definition, ops.queue_size, ops.latch, ops.has_header)); pub->addCallbacks(callbacks); advertised_topics_.push_back(pub); } { boost::mutex::scoped_lock lock(advertised_topic_names_mutex_); advertised_topic_names_.push_back(ops.topic); } // Check whether we've already subscribed to this topic. If so, we'll do // the self-subscription here, to avoid the deadlock that would happen if // the ROS thread later got the publisherUpdate with its own XMLRPC URI. // The assumption is that advertise() is called from somewhere other // than the ROS thread. bool found = false; SubscriptionPtr sub; { boost::mutex::scoped_lock lock(subs_mutex_); for (L_Subscription::iterator s = subscriptions_.begin(); s != subscriptions_.end() && !found; ++s) { if ((*s)->getName() == ops.topic && md5sumsMatch((*s)->md5sum(), ops.md5sum) && !(*s)->isDropped()) { found = true; sub = *s; break; } } } if(found) { sub->addLocalConnection(pub); } registerPublisher(ops.topic, ops.datatype); return true; } bool TopicManager::unadvertise(const std::string &topic, const SubscriberCallbacksPtr& callbacks) { PublicationPtr pub; V_Publication::iterator i; { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); if (isShuttingDown()) { return false; } for (i = advertised_topics_.begin(); i != advertised_topics_.end(); ++i) { if(((*i)->getName() == topic) && (!(*i)->isDropped())) { pub = *i; break; } } } if (!pub) { return false; } pub->removeCallbacks(callbacks); { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); if (pub->getNumCallbacks() == 0) { unregisterPublisher(pub->getName()); pub->drop(); advertised_topics_.erase(i); { boost::mutex::scoped_lock lock(advertised_topic_names_mutex_); advertised_topic_names_.remove(pub->getName()); } } } return true; } bool TopicManager::unregisterPublisher(const std::string& topic) { checkAndRemoveSHMSegment(topic); BroadcastManager::instance()->unregisterPublisher(topic, xmlrpc_manager_->getServerURI()); return true; } bool TopicManager::isTopicAdvertised(const string &topic) { for (V_Publication::iterator t = advertised_topics_.begin(); t != advertised_topics_.end(); ++t) { if (((*t)->getName() == topic) && (!(*t)->isDropped())) { return true; } } return false; } bool TopicManager::registerSubscriber(const SubscriptionPtr& s, const string &datatype) { BroadcastManager::instance()->registerSubscriber(s->getName(), datatype, xmlrpc_manager_->getServerURI()); #if 0 // add pubs in registerPublisher callback vector<string> pub_uris; for (int i = 0; i < payload.size(); i++) { if (payload[i] != xmlrpc_manager_->getServerURI()) { pub_uris.push_back(string(payload[i])); } } #endif bool self_subscribed = false; PublicationPtr pub; const std::string& sub_md5sum = s->md5sum(); // Figure out if we have a local publisher { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); V_Publication::const_iterator it = advertised_topics_.begin(); V_Publication::const_iterator end = advertised_topics_.end(); for (; it != end; ++it) { pub = *it; const std::string& pub_md5sum = pub->getMD5Sum(); if (pub->getName() == s->getName() && !pub->isDropped()) { if (!md5sumsMatch(pub_md5sum, sub_md5sum)) { ROS_ERROR("md5sum mismatch making local subscription to topic %s.", s->getName().c_str()); ROS_ERROR("Subscriber expects type %s, md5sum %s", s->datatype().c_str(), s->md5sum().c_str()); ROS_ERROR("Publisher provides type %s, md5sum %s", pub->getDataType().c_str(), pub->getMD5Sum().c_str()); return false; } self_subscribed = true; pub->setSelfPublished(true); break; } } } s->setSelfSubscribed(self_subscribed); //s->pubUpdate(pub_uris); if (self_subscribed) { s->addLocalConnection(pub); } return true; } bool TopicManager::unregisterSubscriber(const string &topic) { checkAndRemoveSHMSegment(topic); #if 0 // TODO XmlRpcValue args, result, payload; args[0] = this_node::getName(); args[1] = topic; args[2] = xmlrpc_manager_->getServerURI(); master::execute("unregisterSubscriber", args, result, payload, false); #endif BroadcastManager::instance()->unregisterSubscriber(topic, xmlrpc_manager_->getServerURI()); return true; } bool TopicManager::pubUpdate(const string &topic, const vector<string> &pubs) { SubscriptionPtr sub; { boost::mutex::scoped_lock lock(subs_mutex_); if (isShuttingDown()) { return false; } ROS_DEBUG("Received update for topic [%s] (%d publishers)", topic.c_str(), (int)pubs.size()); // find the subscription for (L_Subscription::const_iterator s = subscriptions_.begin(); s != subscriptions_.end(); ++s) { if ((*s)->getName() != topic || (*s)->isDropped()) continue; sub = *s; break; } } if (sub) { return sub->pubUpdate(pubs); } else { ROSCPP_LOG_DEBUG("got a request for updating publishers of topic %s, but I " \ "don't have any subscribers to that topic.", topic.c_str()); } return false; } bool TopicManager::requestTopic(const string &topic, XmlRpcValue &protos, XmlRpcValue &ret) { for (int proto_idx = 0; proto_idx < protos.size(); proto_idx++) { XmlRpcValue proto = protos[proto_idx]; // save typing if (proto.getType() != XmlRpcValue::TypeArray) { ROSCPP_LOG_DEBUG( "requestTopic protocol list was not a list of lists"); return false; } if (proto[0].getType() != XmlRpcValue::TypeString) { ROSCPP_LOG_DEBUG( "requestTopic received a protocol list in which a sublist " \ "did not start with a string"); return false; } string proto_name = proto[0]; if (proto_name == string("TCPROS")) { XmlRpcValue tcpros_params; tcpros_params[0] = string("TCPROS"); tcpros_params[1] = network::getHost(); tcpros_params[2] = int(connection_manager_->getTCPPort()); ret[0] = int(1); ret[1] = string(); ret[2] = tcpros_params; return true; } else if (proto_name == string("UDPROS")) { if (proto.size() != 5 || proto[1].getType() != XmlRpcValue::TypeBase64 || proto[2].getType() != XmlRpcValue::TypeString || proto[3].getType() != XmlRpcValue::TypeInt || proto[4].getType() != XmlRpcValue::TypeInt) { ROSCPP_LOG_DEBUG("Invalid protocol parameters for UDPROS"); return false; } std::vector<char> header_bytes = proto[1]; boost::shared_array<uint8_t> buffer(new uint8_t[header_bytes.size()]); memcpy(buffer.get(), &header_bytes[0], header_bytes.size()); Header h; string err; if (!h.parse(buffer, header_bytes.size(), err)) { ROSCPP_LOG_DEBUG("Unable to parse UDPROS connection header: %s", err.c_str()); return false; } PublicationPtr pub_ptr = lookupPublication(topic); if(!pub_ptr) { ROSCPP_LOG_DEBUG("Unable to find advertised topic %s for UDPROS connection", topic.c_str()); return false; } std::string host = proto[2]; int port = proto[3]; M_string m; std::string error_msg; if (!pub_ptr->validateHeader(h, error_msg)) { ROSCPP_LOG_DEBUG("Error validating header from [%s:%d] for topic [%s]: %s", host.c_str(), port, topic.c_str(), error_msg.c_str()); return false; } int max_datagram_size = proto[4]; int conn_id = connection_manager_->getNewConnectionID(); TransportUDPPtr transport = connection_manager_->getUDPServerTransport()->createOutgoing(host, port, conn_id, max_datagram_size); if (!transport) { ROSCPP_LOG_DEBUG("Error creating outgoing transport for [%s:%d]", host.c_str(), port); return false; } connection_manager_->udprosIncomingConnection(transport, h); XmlRpcValue udpros_params; udpros_params[0] = string("UDPROS"); udpros_params[1] = network::getHost(); udpros_params[2] = connection_manager_->getUDPServerTransport()->getServerPort(); udpros_params[3] = conn_id; udpros_params[4] = max_datagram_size; m["topic"] = topic; m["md5sum"] = pub_ptr->getMD5Sum(); m["type"] = pub_ptr->getDataType(); m["callerid"] = this_node::getName(); m["message_definition"] = pub_ptr->getMessageDefinition(); boost::shared_array<uint8_t> msg_def_buffer; uint32_t len; Header::write(m, msg_def_buffer, len); XmlRpcValue v(msg_def_buffer.get(), len); udpros_params[5] = v; ret[0] = int(1); ret[1] = string(); ret[2] = udpros_params; return true; } else { ROSCPP_LOG_DEBUG( "an unsupported protocol was offered: [%s]", proto_name.c_str()); } } ROSCPP_LOG_DEBUG( "Currently, roscpp only supports TCPROS. The caller to " \ "requestTopic did not support TCPROS, so there are no " \ "protocols in common."); return false; } void TopicManager::publish(const std::string& topic, const boost::function<SerializedMessage(void)>& serfunc, SerializedMessage& m) { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); if (isShuttingDown()) { return; } PublicationPtr p = lookupPublicationWithoutLock(topic); if (p->hasSubscribers() || p->isLatching()) { ROS_DEBUG_NAMED("superdebug", "Publishing message on topic [%s] with sequence number [%d]", p->getName().c_str(), p->getSequence()); // Determine what kinds of subscribers we're publishing to. If they're intraprocess with the same C++ type we can // do a no-copy publish. bool nocopy = false; bool serialize = false; // We can only do a no-copy publish if a shared_ptr to the message is provided, and we have type information for it if (m.type_info && m.message) { p->getPublishTypes(serialize, nocopy, *m.type_info); } else { serialize = true; } if (!nocopy) { m.message.reset(); m.type_info = 0; } if (serialize || p->isLatching()) { SerializedMessage m2 = serfunc(); m.buf = m2.buf; m.num_bytes = m2.num_bytes; m.message_start = m2.message_start; } p->publish(m); // If we're not doing a serialized publish we don't need to signal the pollset. The write() // call inside signal() is actually relatively expensive when doing a nocopy publish. if (serialize) { poll_manager_->getPollSet().signal(); } } else { p->incrementSequence(); } } void TopicManager::incrementSequence(const std::string& topic) { PublicationPtr pub = lookupPublication(topic); if (pub) { pub->incrementSequence(); } } bool TopicManager::isLatched(const std::string& topic) { PublicationPtr pub = lookupPublication(topic); if (pub) { return pub->isLatched(); } return false; } PublicationPtr TopicManager::lookupPublicationWithoutLock(const string &topic) { PublicationPtr t; for (V_Publication::iterator i = advertised_topics_.begin(); !t && i != advertised_topics_.end(); ++i) { if (((*i)->getName() == topic) && (!(*i)->isDropped())) { t = *i; break; } } return t; } SubscriptionPtr TopicManager::lookupSubscriptionWithoutLock(const string &topic) { SubscriptionPtr t; for (L_Subscription::iterator i = subscriptions_.begin(); i != subscriptions_.end(); ++i) { if ((!(*i)->isDropped()) && ((*i)->getName() == topic)) { t = *i; break; } } return t; } bool TopicManager::unsubscribe(const std::string &topic, const SubscriptionCallbackHelperPtr& helper) { SubscriptionPtr sub; { boost::mutex::scoped_lock lock(subs_mutex_); if (isShuttingDown()) { return false; } L_Subscription::iterator it; for (it = subscriptions_.begin(); it != subscriptions_.end(); ++it) { if ((*it)->getName() == topic) { sub = *it; break; } } } if (!sub) { return false; } sub->removeCallback(helper); if (sub->getNumCallbacks() == 0) { // nobody is left. blow away the subscription. { boost::mutex::scoped_lock lock(subs_mutex_); L_Subscription::iterator it; for (it = subscriptions_.begin(); it != subscriptions_.end(); ++it) { if ((*it)->getName() == topic) { subscriptions_.erase(it); break; } } if (!unregisterSubscriber(topic)) { ROSCPP_LOG_DEBUG("Couldn't unregister subscriber for topic [%s]", topic.c_str()); } } sub->shutdown(); return true; } return true; } size_t TopicManager::getNumSubscribers(const std::string &topic) { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); if (isShuttingDown()) { return 0; } PublicationPtr p = lookupPublicationWithoutLock(topic); if (p) { return p->getNumSubscribers(); } return 0; } size_t TopicManager::getNumSubscriptions() { boost::mutex::scoped_lock lock(subs_mutex_); return subscriptions_.size(); } size_t TopicManager::getNumPublishers(const std::string &topic) { boost::mutex::scoped_lock lock(subs_mutex_); if (isShuttingDown()) { return 0; } for (L_Subscription::const_iterator t = subscriptions_.begin(); t != subscriptions_.end(); ++t) { if (!(*t)->isDropped() && (*t)->getName() == topic) { return (*t)->getNumPublishers(); } } return 0; } void TopicManager::getBusStats(XmlRpcValue &stats) { XmlRpcValue publish_stats, subscribe_stats, service_stats; // force these guys to be arrays, even if we don't populate them publish_stats.setSize(0); subscribe_stats.setSize(0); service_stats.setSize(0); uint32_t pidx = 0; { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); for (V_Publication::iterator t = advertised_topics_.begin(); t != advertised_topics_.end(); ++t) { publish_stats[pidx++] = (*t)->getStats(); } } { uint32_t sidx = 0; boost::mutex::scoped_lock lock(subs_mutex_); for (L_Subscription::iterator t = subscriptions_.begin(); t != subscriptions_.end(); ++t) { subscribe_stats[sidx++] = (*t)->getStats(); } } stats[0] = publish_stats; stats[1] = subscribe_stats; stats[2] = service_stats; } void TopicManager::getBusInfo(XmlRpcValue &info) { // force these guys to be arrays, even if we don't populate them info.setSize(0); { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); for (V_Publication::iterator t = advertised_topics_.begin(); t != advertised_topics_.end(); ++t) { (*t)->getInfo(info); } } { boost::mutex::scoped_lock lock(subs_mutex_); for (L_Subscription::iterator t = subscriptions_.begin(); t != subscriptions_.end(); ++t) { (*t)->getInfo(info); } } } void TopicManager::getSubscriptions(XmlRpcValue &subs) { // force these guys to be arrays, even if we don't populate them subs.setSize(0); { boost::mutex::scoped_lock lock(subs_mutex_); uint32_t sidx = 0; for (L_Subscription::iterator t = subscriptions_.begin(); t != subscriptions_.end(); ++t) { XmlRpcValue sub; sub[0] = (*t)->getName(); sub[1] = (*t)->datatype(); subs[sidx++] = sub; } } } void TopicManager::getPublications(XmlRpcValue &pubs) { // force these guys to be arrays, even if we don't populate them pubs.setSize(0); { boost::recursive_mutex::scoped_lock lock(advertised_topics_mutex_); uint32_t sidx = 0; for (V_Publication::iterator t = advertised_topics_.begin(); t != advertised_topics_.end(); ++t) { XmlRpcValue pub; pub[0] = (*t)->getName(); pub[1] = (*t)->getDataType(); pubs[sidx++] = pub; } } } extern std::string console::g_last_error_message; void TopicManager::pubUpdateCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { std::vector<std::string> pubs; for (int idx = 0; idx < params[2].size(); idx++) { pubs.push_back(params[2][idx]); } if (pubUpdate(params[1], pubs)) { result = xmlrpc::responseInt(1, "", 0); } else { result = xmlrpc::responseInt(0, console::g_last_error_message, 0); } } void TopicManager::requestTopicCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { if (!requestTopic(params[1], params[2], result)) { result = xmlrpc::responseInt(0, console::g_last_error_message, 0); } } void TopicManager::getBusStatsCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { (void)params; result[0] = 1; result[1] = std::string(""); XmlRpcValue response; getBusStats(result); result[2] = response; } void TopicManager::getBusInfoCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { (void)params; result[0] = 1; result[1] = std::string(""); XmlRpcValue response; getBusInfo(response); result[2] = response; } void TopicManager::getSubscriptionsCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { (void)params; result[0] = 1; result[1] = std::string("subscriptions"); XmlRpcValue response; getSubscriptions(response); result[2] = response; } void TopicManager::getPublicationsCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { (void)params; result[0] = 1; result[1] = std::string("publications"); XmlRpcValue response; getPublications(response); result[2] = response; } void TopicManager::registerPublisher(const std::string& topic) { for (auto t: advertised_topics_) { if ((t->getName() == topic) && (!t->isDropped())) { registerPublisher(t->getName(), t->getDataType()); } } } void TopicManager::registerPublisher(const std::string& topic, const std::string& datatype) { BroadcastManager::instance()->registerPublisher(topic, datatype, xmlrpc_manager_->getServerURI()); } void TopicManager::registerAllPublisher() { for (auto t: advertised_topics_) { if (!t->isDropped()) { registerPublisher(t->getName(), t->getDataType()); } } } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/service.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/service.h" #include "ros/connection.h" #include "ros/service_server_link.h" #include "ros/service_manager.h" #include "ros/transport/transport_tcp.h" #include "ros/poll_manager.h" #include "ros/init.h" #include "ros/names.h" #include "ros/this_node.h" #include "ros/header.h" using namespace ros; bool service::exists(const std::string& service_name, bool print_failure_reason) { std::string mapped_name = names::resolve(service_name); std::string host; uint32_t port; if (ServiceManager::instance()->lookupService(mapped_name, host, port)) { TransportTCPPtr transport(boost::make_shared<TransportTCP>(static_cast<ros::PollSet*>(NULL), TransportTCP::SYNCHRONOUS)); if (transport->connect(host, port)) { M_string m; m["probe"] = "1"; m["md5sum"] = "*"; m["callerid"] = this_node::getName(); m["service"] = mapped_name; boost::shared_array<uint8_t> buffer; uint32_t size = 0;; Header::write(m, buffer, size); transport->write((uint8_t*)&size, sizeof(size)); transport->write(buffer.get(), size); transport->close(); return true; } else { if (print_failure_reason) { ROS_INFO("waitForService: Service [%s] could not connect to host [%s:%d], waiting...", mapped_name.c_str(), host.c_str(), port); } } } else { if (print_failure_reason) { ROS_INFO("waitForService: Service [%s] has not been advertised, waiting...", mapped_name.c_str()); } } return false; } bool service::waitForService(const std::string& service_name, ros::Duration timeout) { std::string mapped_name = names::resolve(service_name); Time start_time = Time::now(); bool printed = false; bool result = false; while (ros::ok()) { if (exists(service_name, !printed)) { result = true; break; } else { printed = true; if (timeout >= Duration(0)) { Time current_time = Time::now(); if ((current_time - start_time) >= timeout) { return false; } } Duration(0.02).sleep(); } } if (printed && ros::ok()) { ROS_INFO("waitForService: Service [%s] is now available.", mapped_name.c_str()); } return result; } bool service::waitForService(const std::string& service_name, int32_t timeout) { return waitForService(service_name, ros::Duration(timeout / 1000.0)); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/xmlrpc_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/xmlrpc_manager.h" #include "ros/network.h" #include "ros/param.h" #include "ros/assert.h" #include "ros/common.h" #include "ros/file_log.h" #include "ros/io.h" using namespace XmlRpc; namespace ros { namespace xmlrpc { XmlRpc::XmlRpcValue responseStr(int code, const std::string& msg, const std::string& response) { XmlRpc::XmlRpcValue v; v[0] = code; v[1] = msg; v[2] = response; return v; } XmlRpc::XmlRpcValue responseInt(int code, const std::string& msg, int response) { XmlRpc::XmlRpcValue v; v[0] = int(code); v[1] = msg; v[2] = response; return v; } XmlRpc::XmlRpcValue responseBool(int code, const std::string& msg, bool response) { XmlRpc::XmlRpcValue v; v[0] = int(code); v[1] = msg; v[2] = XmlRpc::XmlRpcValue(response); return v; } } class XMLRPCCallWrapper : public XmlRpcServerMethod { public: XMLRPCCallWrapper(const std::string& function_name, const XMLRPCFunc& cb, XmlRpcServer *s) : XmlRpcServerMethod(function_name, s) , name_(function_name) , func_(cb) { } void execute(XmlRpcValue &params, XmlRpcValue &result) { func_(params, result); } private: std::string name_; XMLRPCFunc func_; }; void getPid(const XmlRpcValue& params, XmlRpcValue& result) { (void)params; result = xmlrpc::responseInt(1, "", (int)getpid()); } const ros::WallDuration CachedXmlRpcClient::s_zombie_time_(30.0); // reap after 30 seconds XMLRPCManagerPtr g_xmlrpc_manager; boost::mutex g_xmlrpc_manager_mutex; const XMLRPCManagerPtr& XMLRPCManager::instance() { if (!g_xmlrpc_manager) { boost::mutex::scoped_lock lock(g_xmlrpc_manager_mutex); if (!g_xmlrpc_manager) { g_xmlrpc_manager.reset(new XMLRPCManager); } } return g_xmlrpc_manager; } XMLRPCManager::XMLRPCManager() : port_(0) , shutting_down_(false) , unbind_requested_(false) { } XMLRPCManager::~XMLRPCManager() { shutdown(); } void XMLRPCManager::start(int port_def) { shutting_down_ = false; port_ = 0; bind("getPid", getPid); bool bound = server_.bindAndListen(port_def); (void) bound; ROS_ASSERT(bound); port_ = server_.get_port(); ROS_ASSERT(port_ != 0); std::stringstream ss; ss << "http://" << network::getHost() << ":" << port_ << "/"; uri_ = ss.str(); server_thread_ = boost::thread(boost::bind(&XMLRPCManager::serverThreadFunc, this)); } void XMLRPCManager::shutdown() { if (shutting_down_) { return; } shutting_down_ = true; server_thread_.join(); server_.close(); // kill the last few clients that were started in the shutdown process for (V_CachedXmlRpcClient::iterator i = clients_.begin(); i != clients_.end(); ++i) { for (int wait_count = 0; i->in_use_ && wait_count < 10; wait_count++) { ROSCPP_LOG_DEBUG("waiting for xmlrpc connection to finish..."); ros::WallDuration(0.01).sleep(); } i->client_->close(); delete i->client_; } clients_.clear(); boost::mutex::scoped_lock lock(functions_mutex_); functions_.clear(); { S_ASyncXMLRPCConnection::iterator it = connections_.begin(); S_ASyncXMLRPCConnection::iterator end = connections_.end(); for (; it != end; ++it) { (*it)->removeFromDispatch(server_.get_dispatch()); } } connections_.clear(); { boost::mutex::scoped_lock lock(added_connections_mutex_); added_connections_.clear(); } { boost::mutex::scoped_lock lock(removed_connections_mutex_); removed_connections_.clear(); } } bool XMLRPCManager::validateXmlrpcResponse(const std::string& method, XmlRpcValue &response, XmlRpcValue &payload) { if (response.getType() != XmlRpcValue::TypeArray) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return an array", method.c_str()); return false; } if (response.size() != 2 && response.size() != 3) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a 2 or 3-element array", method.c_str()); return false; } if (response[0].getType() != XmlRpcValue::TypeInt) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a int as the 1st element", method.c_str()); return false; } int status_code = response[0]; if (response[1].getType() != XmlRpcValue::TypeString) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a string as the 2nd element", method.c_str()); return false; } std::string status_string = response[1]; if (status_code != 1) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] returned an error (%d): [%s]", method.c_str(), status_code, status_string.c_str()); return false; } if (response.size() > 2) { payload = response[2]; } else { std::string empty_array = "<value><array><data></data></array></value>"; int offset = 0; payload = XmlRpcValue(empty_array, &offset); } return true; } void XMLRPCManager::serverThreadFunc() { disableAllSignalsInThisThread(); while(!shutting_down_) { { boost::mutex::scoped_lock lock(added_connections_mutex_); S_ASyncXMLRPCConnection::iterator it = added_connections_.begin(); S_ASyncXMLRPCConnection::iterator end = added_connections_.end(); for (; it != end; ++it) { (*it)->addToDispatch(server_.get_dispatch()); connections_.insert(*it); } added_connections_.clear(); } // Update the XMLRPC server, blocking for at most 100ms in select() { boost::mutex::scoped_lock lock(functions_mutex_); server_.work(0.1); } while (unbind_requested_) { WallDuration(0.01).sleep(); } if (shutting_down_) { return; } { S_ASyncXMLRPCConnection::iterator it = connections_.begin(); S_ASyncXMLRPCConnection::iterator end = connections_.end(); for (; it != end; ++it) { if ((*it)->check()) { removeASyncConnection(*it); } } } { boost::mutex::scoped_lock lock(removed_connections_mutex_); S_ASyncXMLRPCConnection::iterator it = removed_connections_.begin(); S_ASyncXMLRPCConnection::iterator end = removed_connections_.end(); for (; it != end; ++it) { (*it)->removeFromDispatch(server_.get_dispatch()); connections_.erase(*it); } removed_connections_.clear(); } } } XmlRpcClient* XMLRPCManager::getXMLRPCClient(const std::string &host, const int port, const std::string &uri) { // go through our vector of clients and grab the first available one XmlRpcClient *c = NULL; boost::mutex::scoped_lock lock(clients_mutex_); for (V_CachedXmlRpcClient::iterator i = clients_.begin(); !c && i != clients_.end(); ) { if (!i->in_use_) { // see where it's pointing if (i->client_->getHost() == host && i->client_->getPort() == port && i->client_->getUri() == uri) { // hooray, it's pointing at our destination. re-use it. c = i->client_; i->in_use_ = true; i->last_use_time_ = WallTime::now(); break; } else if (i->last_use_time_ + CachedXmlRpcClient::s_zombie_time_ < WallTime::now()) { // toast this guy. he's dead and nobody is reusing him. delete i->client_; i = clients_.erase(i); } else { ++i; // move along. this guy isn't dead yet. } } else { ++i; } } if (!c) { // allocate a new one c = new XmlRpcClient(host.c_str(), port, uri.c_str()); CachedXmlRpcClient mc(c); mc.in_use_ = true; mc.last_use_time_ = WallTime::now(); clients_.push_back(mc); //ROS_INFO("%d xmlrpc clients allocated\n", xmlrpc_clients.size()); } // ONUS IS ON THE RECEIVER TO UNSET THE IN_USE FLAG // by calling releaseXMLRPCClient return c; } void XMLRPCManager::releaseXMLRPCClient(XmlRpcClient *c) { boost::mutex::scoped_lock lock(clients_mutex_); for (V_CachedXmlRpcClient::iterator i = clients_.begin(); i != clients_.end(); ++i) { if (c == i->client_) { i->in_use_ = false; break; } } } void XMLRPCManager::addASyncConnection(const ASyncXMLRPCConnectionPtr& conn) { boost::mutex::scoped_lock lock(added_connections_mutex_); added_connections_.insert(conn); } void XMLRPCManager::removeASyncConnection(const ASyncXMLRPCConnectionPtr& conn) { boost::mutex::scoped_lock lock(removed_connections_mutex_); removed_connections_.insert(conn); } bool XMLRPCManager::bind(const std::string& function_name, const XMLRPCFunc& cb) { boost::mutex::scoped_lock lock(functions_mutex_); if (functions_.find(function_name) != functions_.end()) { return false; } FunctionInfo info; info.name = function_name; info.function = cb; info.wrapper.reset(new XMLRPCCallWrapper(function_name, cb, &server_)); functions_[function_name] = info; return true; } void XMLRPCManager::unbind(const std::string& function_name) { unbind_requested_ = true; boost::mutex::scoped_lock lock(functions_mutex_); functions_.erase(function_name); unbind_requested_ = false; } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/param.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/param.h" #include "ros/master.h" #include "ros/xmlrpc_manager.h" #include "ros/this_node.h" #include "ros/names.h" #include <ros/console.h> #include <boost/thread/mutex.hpp> #include <boost/lexical_cast.hpp> #include <vector> #include <map> namespace ros { namespace param { typedef std::map<std::string, XmlRpc::XmlRpcValue> M_Param; M_Param g_params; boost::mutex g_params_mutex; S_string g_subscribed_params; void invalidateParentParams(const std::string& key) { std::string ns_key = names::parentNamespace(key); while (ns_key != "" && ns_key != "/") { if (g_subscribed_params.find(ns_key) != g_subscribed_params.end()) { // by erasing the key the parameter will be re-queried g_params.erase(ns_key); } ns_key = names::parentNamespace(ns_key); } } void set(const std::string& key, const XmlRpc::XmlRpcValue& v) { std::string mapped_key = ros::names::resolve(key); XmlRpc::XmlRpcValue params, result, payload; params[0] = this_node::getName(); params[1] = mapped_key; params[2] = v; { // Lock around the execute to the master in case we get a parameter update on this value between // executing on the master and setting the parameter in the g_params list. boost::mutex::scoped_lock lock(g_params_mutex); if (master::execute("setParam", params, result, payload, true)) { // Update our cached params list now so that if get() is called immediately after param::set() // we already have the cached state and our value will be correct if (g_subscribed_params.find(mapped_key) != g_subscribed_params.end()) { g_params[mapped_key] = v; } invalidateParentParams(mapped_key); } } } void set(const std::string& key, const std::string& s) { // construct xmlrpc_c::value object of the std::string and // call param::set(key, xmlvalue); XmlRpc::XmlRpcValue v(s); ros::param::set(key, v); } void set(const std::string& key, const char* s) { // construct xmlrpc_c::value object of the std::string and // call param::set(key, xmlvalue); std::string sxx = std::string(s); XmlRpc::XmlRpcValue v(sxx); ros::param::set(key, v); } void set(const std::string& key, double d) { XmlRpc::XmlRpcValue v(d); ros::param::set(key, v); } void set(const std::string& key, int i) { XmlRpc::XmlRpcValue v(i); ros::param::set(key, v); } void set(const std::string& key, bool b) { XmlRpc::XmlRpcValue v(b); ros::param::set(key, v); } template <class T> void setImpl(const std::string& key, const std::vector<T>& vec) { // Note: the XmlRpcValue starts off as "invalid" and assertArray turns it // into an array type with the given size XmlRpc::XmlRpcValue xml_vec; xml_vec.setSize(vec.size()); // Copy the contents into the XmlRpcValue for(size_t i=0; i < vec.size(); i++) { xml_vec[i] = vec.at(i); } ros::param::set(key, xml_vec); } void set(const std::string& key, const std::vector<std::string>& vec) { setImpl(key, vec); } void set(const std::string& key, const std::vector<double>& vec) { setImpl(key, vec); } void set(const std::string& key, const std::vector<float>& vec) { setImpl(key, vec); } void set(const std::string& key, const std::vector<int>& vec) { setImpl(key, vec); } void set(const std::string& key, const std::vector<bool>& vec) { setImpl(key, vec); } template <class T> void setImpl(const std::string& key, const std::map<std::string, T>& map) { // Note: the XmlRpcValue starts off as "invalid" and assertArray turns it // into an array type with the given size XmlRpc::XmlRpcValue xml_value; const XmlRpc::XmlRpcValue::ValueStruct& xml_map = (const XmlRpc::XmlRpcValue::ValueStruct &)(xml_value); (void)xml_map; // Copy the contents into the XmlRpcValue for(typename std::map<std::string, T>::const_iterator it = map.begin(); it != map.end(); ++it) { xml_value[it->first] = it->second; } ros::param::set(key, xml_value); } void set(const std::string& key, const std::map<std::string, std::string>& map) { setImpl(key, map); } void set(const std::string& key, const std::map<std::string, double>& map) { setImpl(key, map); } void set(const std::string& key, const std::map<std::string, float>& map) { setImpl(key, map); } void set(const std::string& key, const std::map<std::string, int>& map) { setImpl(key, map); } void set(const std::string& key, const std::map<std::string, bool>& map) { setImpl(key, map); } bool has(const std::string& key) { XmlRpc::XmlRpcValue params, result, payload; params[0] = this_node::getName(); params[1] = ros::names::resolve(key); //params[1] = key; // We don't loop here, because validateXmlrpcResponse() returns false // both when we can't contact the master and when the master says, "I // don't have that param." if (!master::execute("hasParam", params, result, payload, false)) { return false; } return payload; } bool del(const std::string& key) { std::string mapped_key = ros::names::resolve(key); { boost::mutex::scoped_lock lock(g_params_mutex); g_subscribed_params.erase(mapped_key); g_params.erase(mapped_key); } XmlRpc::XmlRpcValue params, result, payload; params[0] = this_node::getName(); params[1] = mapped_key; // We don't loop here, because validateXmlrpcResponse() returns false // both when we can't contact the master and when the master says, "I // don't have that param." if (!master::execute("deleteParam", params, result, payload, false)) { return false; } return true; } bool getImpl(const std::string& key, XmlRpc::XmlRpcValue& v, bool use_cache) { std::string mapped_key = ros::names::resolve(key); if (mapped_key.empty()) mapped_key = "/"; if (use_cache) { boost::mutex::scoped_lock lock(g_params_mutex); if (g_subscribed_params.find(mapped_key) != g_subscribed_params.end()) { M_Param::iterator it = g_params.find(mapped_key); if (it != g_params.end()) { if (it->second.valid()) { ROS_DEBUG_NAMED("cached_parameters", "Using cached parameter value for key [%s]", mapped_key.c_str()); v = it->second; return true; } else { ROS_DEBUG_NAMED("cached_parameters", "Cached parameter is invalid for key [%s]", mapped_key.c_str()); return false; } } } else { // parameter we've never seen before, register for update from the master if (g_subscribed_params.insert(mapped_key).second) { XmlRpc::XmlRpcValue params, result, payload; params[0] = this_node::getName(); params[1] = XMLRPCManager::instance()->getServerURI(); params[2] = mapped_key; if (!master::execute("subscribeParam", params, result, payload, false)) { ROS_DEBUG_NAMED("cached_parameters", "Subscribe to parameter [%s]: call to the master failed", mapped_key.c_str()); g_subscribed_params.erase(mapped_key); use_cache = false; } else { ROS_DEBUG_NAMED("cached_parameters", "Subscribed to parameter [%s]", mapped_key.c_str()); } } } } XmlRpc::XmlRpcValue params, result; params[0] = this_node::getName(); params[1] = mapped_key; // We don't loop here, because validateXmlrpcResponse() returns false // both when we can't contact the master and when the master says, "I // don't have that param." bool ret = master::execute("getParam", params, result, v, false); if (use_cache) { boost::mutex::scoped_lock lock(g_params_mutex); ROS_DEBUG_NAMED("cached_parameters", "Caching parameter [%s] with value type [%d]", mapped_key.c_str(), v.getType()); g_params[mapped_key] = v; } return ret; } bool getImpl(const std::string& key, std::string& s, bool use_cache) { XmlRpc::XmlRpcValue v; if (!getImpl(key, v, use_cache)) return false; if (v.getType() != XmlRpc::XmlRpcValue::TypeString) return false; s = std::string(v); return true; } bool getImpl(const std::string& key, double& d, bool use_cache) { XmlRpc::XmlRpcValue v; if (!getImpl(key, v, use_cache)) { return false; } if (v.getType() == XmlRpc::XmlRpcValue::TypeInt) { d = (int)v; } else if (v.getType() != XmlRpc::XmlRpcValue::TypeDouble) { return false; } else { d = v; } return true; } bool getImpl(const std::string& key, float& f, bool use_cache) { double d = static_cast<double>(f); bool result = getImpl(key, d, use_cache); if (result) f = static_cast<float>(d); return result; } bool getImpl(const std::string& key, int& i, bool use_cache) { XmlRpc::XmlRpcValue v; if (!getImpl(key, v, use_cache)) { return false; } if (v.getType() == XmlRpc::XmlRpcValue::TypeDouble) { double d = v; if (fmod(d, 1.0) < 0.5) { d = floor(d); } else { d = ceil(d); } i = d; } else if (v.getType() != XmlRpc::XmlRpcValue::TypeInt) { return false; } else { i = v; } return true; } bool getImpl(const std::string& key, bool& b, bool use_cache) { XmlRpc::XmlRpcValue v; if (!getImpl(key, v, use_cache)) return false; if (v.getType() != XmlRpc::XmlRpcValue::TypeBoolean) return false; b = v; return true; } bool get(const std::string& key, std::string& s) { return getImpl(key, s, false); } bool get(const std::string& key, double& d) { return getImpl(key, d, false); } bool get(const std::string& key, float& f) { return getImpl(key, f, false); } bool get(const std::string& key, int& i) { return getImpl(key, i, false); } bool get(const std::string& key, bool& b) { return getImpl(key, b, false); } bool get(const std::string& key, XmlRpc::XmlRpcValue& v) { return getImpl(key, v, false); } bool getCached(const std::string& key, std::string& s) { return getImpl(key, s, true); } bool getCached(const std::string& key, double& d) { return getImpl(key, d, true); } bool getCached(const std::string& key, float& f) { return getImpl(key, f, true); } bool getCached(const std::string& key, int& i) { return getImpl(key, i, true); } bool getCached(const std::string& key, bool& b) { return getImpl(key, b, true); } bool getCached(const std::string& key, XmlRpc::XmlRpcValue& v) { return getImpl(key, v, true); } template <class T> T xml_cast(XmlRpc::XmlRpcValue xml_value) { return static_cast<T>(xml_value); } template <class T> bool xml_castable(int XmlType) { return false; } template<> bool xml_castable<std::string>(int XmlType) { return XmlType == XmlRpc::XmlRpcValue::TypeString; } template<> bool xml_castable<double>(int XmlType) { return ( XmlType == XmlRpc::XmlRpcValue::TypeDouble || XmlType == XmlRpc::XmlRpcValue::TypeInt || XmlType == XmlRpc::XmlRpcValue::TypeBoolean ); } template<> bool xml_castable<float>(int XmlType) { return ( XmlType == XmlRpc::XmlRpcValue::TypeDouble || XmlType == XmlRpc::XmlRpcValue::TypeInt || XmlType == XmlRpc::XmlRpcValue::TypeBoolean ); } template<> bool xml_castable<int>(int XmlType) { return ( XmlType == XmlRpc::XmlRpcValue::TypeDouble || XmlType == XmlRpc::XmlRpcValue::TypeInt || XmlType == XmlRpc::XmlRpcValue::TypeBoolean ); } template<> bool xml_castable<bool>(int XmlType) { return ( XmlType == XmlRpc::XmlRpcValue::TypeDouble || XmlType == XmlRpc::XmlRpcValue::TypeInt || XmlType == XmlRpc::XmlRpcValue::TypeBoolean ); } template<> double xml_cast(XmlRpc::XmlRpcValue xml_value) { using namespace XmlRpc; switch(xml_value.getType()) { case XmlRpcValue::TypeDouble: return static_cast<double>(xml_value); case XmlRpcValue::TypeInt: return static_cast<double>(static_cast<int>(xml_value)); case XmlRpcValue::TypeBoolean: return static_cast<double>(static_cast<bool>(xml_value)); default: return 0.0; }; } template<> float xml_cast(XmlRpc::XmlRpcValue xml_value) { using namespace XmlRpc; switch(xml_value.getType()) { case XmlRpcValue::TypeDouble: return static_cast<float>(static_cast<double>(xml_value)); case XmlRpcValue::TypeInt: return static_cast<float>(static_cast<int>(xml_value)); case XmlRpcValue::TypeBoolean: return static_cast<float>(static_cast<bool>(xml_value)); default: return 0.0f; }; } template<> int xml_cast(XmlRpc::XmlRpcValue xml_value) { using namespace XmlRpc; switch(xml_value.getType()) { case XmlRpcValue::TypeDouble: return static_cast<int>(static_cast<double>(xml_value)); case XmlRpcValue::TypeInt: return static_cast<int>(xml_value); case XmlRpcValue::TypeBoolean: return static_cast<int>(static_cast<bool>(xml_value)); default: return 0; }; } template<> bool xml_cast(XmlRpc::XmlRpcValue xml_value) { using namespace XmlRpc; switch(xml_value.getType()) { case XmlRpcValue::TypeDouble: return static_cast<bool>(static_cast<double>(xml_value)); case XmlRpcValue::TypeInt: return static_cast<bool>(static_cast<int>(xml_value)); case XmlRpcValue::TypeBoolean: return static_cast<bool>(xml_value); default: return false; }; } template <class T> bool getImpl(const std::string& key, std::vector<T>& vec, bool cached) { XmlRpc::XmlRpcValue xml_array; if(!getImpl(key, xml_array, cached)) { return false; } // Make sure it's an array type if(xml_array.getType() != XmlRpc::XmlRpcValue::TypeArray) { return false; } // Resize the target vector (destructive) vec.resize(xml_array.size()); // Fill the vector with stuff for (int i = 0; i < xml_array.size(); i++) { if(!xml_castable<T>(xml_array[i].getType())) { return false; } vec[i] = xml_cast<T>(xml_array[i]); } return true; } bool get(const std::string& key, std::vector<std::string>& vec) { return getImpl(key, vec, false); } bool get(const std::string& key, std::vector<double>& vec) { return getImpl(key, vec, false); } bool get(const std::string& key, std::vector<float>& vec) { return getImpl(key, vec, false); } bool get(const std::string& key, std::vector<int>& vec) { return getImpl(key, vec, false); } bool get(const std::string& key, std::vector<bool>& vec) { return getImpl(key, vec, false); } bool getCached(const std::string& key, std::vector<std::string>& vec) { return getImpl(key, vec, true); } bool getCached(const std::string& key, std::vector<double>& vec) { return getImpl(key, vec, true); } bool getCached(const std::string& key, std::vector<float>& vec) { return getImpl(key, vec, true); } bool getCached(const std::string& key, std::vector<int>& vec) { return getImpl(key, vec, true); } bool getCached(const std::string& key, std::vector<bool>& vec) { return getImpl(key, vec, true); } template <class T> bool getImpl(const std::string& key, std::map<std::string, T>& map, bool cached) { XmlRpc::XmlRpcValue xml_value; if(!getImpl(key, xml_value, cached)) { return false; } // Make sure it's a struct type if(xml_value.getType() != XmlRpc::XmlRpcValue::TypeStruct) { return false; } // Fill the map with stuff for (XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = xml_value.begin(); it != xml_value.end(); ++it) { // Make sure this element is the right type if(!xml_castable<T>(it->second.getType())) { return false; } // Store the element map[it->first] = xml_cast<T>(it->second); } return true; } bool get(const std::string& key, std::map<std::string, std::string>& map) { return getImpl(key, map, false); } bool get(const std::string& key, std::map<std::string, double>& map) { return getImpl(key, map, false); } bool get(const std::string& key, std::map<std::string, float>& map) { return getImpl(key, map, false); } bool get(const std::string& key, std::map<std::string, int>& map) { return getImpl(key, map, false); } bool get(const std::string& key, std::map<std::string, bool>& map) { return getImpl(key, map, false); } bool getCached(const std::string& key, std::map<std::string, std::string>& map) { return getImpl(key, map, true); } bool getCached(const std::string& key, std::map<std::string, double>& map) { return getImpl(key, map, true); } bool getCached(const std::string& key, std::map<std::string, float>& map) { return getImpl(key, map, true); } bool getCached(const std::string& key, std::map<std::string, int>& map) { return getImpl(key, map, true); } bool getCached(const std::string& key, std::map<std::string, bool>& map) { return getImpl(key, map, true); } bool getParamNames(std::vector<std::string>& keys) { XmlRpc::XmlRpcValue params, result, payload; params[0] = this_node::getName(); if (!master::execute("getParamNames", params, result, payload, false)) { return false; } // Make sure it's an array type if (result.getType() != XmlRpc::XmlRpcValue::TypeArray) { return false; } // Make sure it returned 3 elements if (result.size() != 3) { return false; } // Get the actual parameter keys XmlRpc::XmlRpcValue parameters = result[2]; // Resize the output keys.resize(parameters.size()); // Fill the output vector with the answer for (int i = 0; i < parameters.size(); ++i) { if (parameters[i].getType() != XmlRpc::XmlRpcValue::TypeString) { return false; } keys[i] = std::string(parameters[i]); } return true; } bool search(const std::string& key, std::string& result_out) { return search(this_node::getName(), key, result_out); } bool search(const std::string& ns, const std::string& key, std::string& result_out) { XmlRpc::XmlRpcValue params, result, payload; params[0] = ns; // 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 = names::getUnresolvedRemappings().find(key); if (it != names::getUnresolvedRemappings().end()) { remapped = it->second; } params[1] = remapped; // We don't loop here, because validateXmlrpcResponse() returns false // both when we can't contact the master and when the master says, "I // don't have that param." if (!master::execute("searchParam", params, result, payload, false)) { return false; } result_out = (std::string)payload; return true; } void update(const std::string& key, const XmlRpc::XmlRpcValue& v) { std::string clean_key = names::clean(key); ROS_DEBUG_NAMED("cached_parameters", "Received parameter update for key [%s]", clean_key.c_str()); boost::mutex::scoped_lock lock(g_params_mutex); if (g_subscribed_params.find(clean_key) != g_subscribed_params.end()) { g_params[clean_key] = v; } invalidateParentParams(clean_key); } void paramUpdateCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { result[0] = 1; result[1] = std::string(""); result[2] = 0; ros::param::update((std::string)params[1], params[2]); } void init(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& name = it->first; const std::string& param = it->second; if (name.size() < 2) { continue; } if (name[0] == '_' && name[1] != '_') { std::string local_name = "~" + name.substr(1); bool success = false; try { int32_t i = boost::lexical_cast<int32_t>(param); ros::param::set(names::resolve(local_name), i); success = true; } catch (boost::bad_lexical_cast&) { } if (success) { continue; } try { double d = boost::lexical_cast<double>(param); ros::param::set(names::resolve(local_name), d); success = true; } catch (boost::bad_lexical_cast&) { } if (success) { continue; } if (param == "true" || param == "True" || param == "TRUE") { ros::param::set(names::resolve(local_name), true); } else if (param == "false" || param == "False" || param == "FALSE") { ros::param::set(names::resolve(local_name), false); } else { ros::param::set(names::resolve(local_name), param); } } } XMLRPCManager::instance()->bind("paramUpdate", paramUpdateCallback); } } // namespace param } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/transport_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/platform.h> // platform dependendant requirements #include "ros/transport_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 "ros/poll_manager.h" #include "ros/transport/transport_tcp.h" #include "ros/timer_manager.h" #include "ros/callback_queue.h" #include "ros/internal_timer_manager.h" #include <boost/bind.hpp> #include <sstream> namespace ros { TransportPublisherLink::TransportPublisherLink(const SubscriptionPtr& parent, const std::string& xmlrpc_uri, const TransportHints& transport_hints) : PublisherLink(parent, xmlrpc_uri, transport_hints) , retry_timer_handle_(-1) , needs_retry_(false) , dropping_(false) { } TransportPublisherLink::~TransportPublisherLink() { dropping_ = true; if (retry_timer_handle_ != -1) { getInternalTimerManager()->remove(retry_timer_handle_); } connection_->drop(Connection::Destructing); } bool TransportPublisherLink::initialize(const ConnectionPtr& connection) { connection_ = connection; // slot_type is used to automatically track the TransporPublisherLink class' existence // and disconnect when this class' reference count is decremented to 0. It increments // then decrements the shared_from_this reference count around calls to the // onConnectionDropped function, preventing a coredump in the middle of execution. connection_->addDropListener(Connection::DropSignal::slot_type(&TransportPublisherLink::onConnectionDropped, this, _1, _2).track(shared_from_this())); if (connection_->getTransport()->requiresHeader()) { connection_->setHeaderReceivedCallback(boost::bind(&TransportPublisherLink::onHeaderReceived, this, _1, _2)); SubscriptionPtr parent = parent_.lock(); M_string header; header["topic"] = parent->getName(); header["md5sum"] = parent->md5sum(); header["callerid"] = this_node::getName(); header["type"] = parent->datatype(); header["tcp_nodelay"] = transport_hints_.getTCPNoDelay() ? "1" : "0"; connection_->writeHeader(header, boost::bind(&TransportPublisherLink::onHeaderWritten, this, _1)); } else { connection_->read(4, boost::bind(&TransportPublisherLink::onMessageLength, this, _1, _2, _3, _4)); } return true; } void TransportPublisherLink::drop() { dropping_ = true; connection_->drop(Connection::Destructing); if (SubscriptionPtr parent = parent_.lock()) { parent->removePublisherLink(shared_from_this()); } } void TransportPublisherLink::onHeaderWritten(const ConnectionPtr& conn) { (void)conn; // Do nothing } bool TransportPublisherLink::onHeaderReceived(const ConnectionPtr& conn, const Header& header) { ROS_ASSERT(conn == connection_); if (!setHeader(header)) { drop(); return false; } if (retry_timer_handle_ != -1) { getInternalTimerManager()->remove(retry_timer_handle_); retry_timer_handle_ = -1; } connection_->read(4, boost::bind(&TransportPublisherLink::onMessageLength, this, _1, _2, _3, _4)); return true; } void TransportPublisherLink::onMessageLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success) { if (retry_timer_handle_ != -1) { getInternalTimerManager()->remove(retry_timer_handle_); retry_timer_handle_ = -1; } if (!success) { if (connection_) connection_->read(4, boost::bind(&TransportPublisherLink::onMessageLength, this, _1, _2, _3, _4)); 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."); drop(); return; } connection_->read(len, boost::bind(&TransportPublisherLink::onMessage, this, _1, _2, _3, _4)); } void TransportPublisherLink::onMessage(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success) { if (!success && !conn) return; ROS_ASSERT(conn == connection_); if (success) { handleMessage(SerializedMessage(buffer, size), true, false); } if (success || !connection_->getTransport()->requiresHeader()) { connection_->read(4, boost::bind(&TransportPublisherLink::onMessageLength, this, _1, _2, _3, _4)); } } void TransportPublisherLink::onRetryTimer(const ros::WallTimerEvent&) { if (dropping_) { return; } if (needs_retry_ && WallTime::now() > next_retry_) { retry_period_ = std::min(retry_period_ * 2, WallDuration(20)); needs_retry_ = false; SubscriptionPtr parent = parent_.lock(); // TODO: support retry on more than just TCP // For now, since UDP does not have a heartbeat, we do not attempt to retry // UDP connections since an error there likely means some invalid operation has // happened. if (connection_->getTransport()->getType() == std::string("TCPROS")) { std::string topic = parent ? parent->getName() : "unknown"; TransportTCPPtr old_transport = boost::dynamic_pointer_cast<TransportTCP>(connection_->getTransport()); ROS_ASSERT(old_transport); const std::string& host = old_transport->getConnectedHost(); int port = old_transport->getConnectedPort(); ROSCPP_LOG_DEBUG("Retrying connection to [%s:%d] for topic [%s]", host.c_str(), port, topic.c_str()); TransportTCPPtr transport(boost::make_shared<TransportTCP>(&PollManager::instance()->getPollSet())); if (transport->connect(host, port)) { ConnectionPtr connection(boost::make_shared<Connection>()); connection->initialize(transport, false, HeaderReceivedFunc()); initialize(connection); ConnectionManager::instance()->addConnection(connection); } else { ROSCPP_LOG_DEBUG("connect() failed when retrying connection to [%s:%d] for topic [%s]", host.c_str(), port, topic.c_str()); } } else if (parent) { parent->removePublisherLink(shared_from_this()); } } } CallbackQueuePtr getInternalCallbackQueue(); void TransportPublisherLink::onConnectionDropped(const ConnectionPtr& conn, Connection::DropReason reason) { if (dropping_) { return; } ROS_ASSERT(conn == connection_); SubscriptionPtr parent = parent_.lock(); if (reason == Connection::TransportDisconnect) { std::string topic = parent ? parent->getName() : "unknown"; ROSCPP_LOG_DEBUG("Connection to publisher [%s] to topic [%s] dropped", connection_->getTransport()->getTransportInfo().c_str(), topic.c_str()); ROS_ASSERT(!needs_retry_); needs_retry_ = true; next_retry_ = WallTime::now() + retry_period_; if (retry_timer_handle_ == -1) { retry_period_ = WallDuration(0.1); next_retry_ = WallTime::now() + retry_period_; // shared_from_this() shared_ptr is used to ensure TransportPublisherLink is not // destroyed in the middle of onRetryTimer execution retry_timer_handle_ = getInternalTimerManager()->add(WallDuration(retry_period_), boost::bind(&TransportPublisherLink::onRetryTimer, this, _1), getInternalCallbackQueue().get(), shared_from_this(), false); } else { getInternalTimerManager()->setPeriod(retry_timer_handle_, retry_period_); } } else { drop(); } } void TransportPublisherLink::handleMessage(const SerializedMessage& m, bool ser, bool nocopy) { stats_.bytes_received_ += m.num_bytes; stats_.messages_received_++; SubscriptionPtr parent = parent_.lock(); if (parent) { stats_.drops_ += parent->handleMessage(m, ser, nocopy, getConnection()->getHeader().getValues(), shared_from_this()); } } std::string TransportPublisherLink::getTransportType() { return connection_->getTransport()->getType(); } std::string TransportPublisherLink::getTransportInfo() { return connection_->getTransport()->getTransportInfo(); } } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src
apollo_public_repos/apollo-platform/ros/ros_comm/roscpp/src/libros/publication.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/publication.h" #include "ros/subscriber_link.h" #include "ros/connection.h" #include "ros/callback_queue_interface.h" #include "ros/single_subscriber_publisher.h" #include "ros/serialization.h" #include <std_msgs/Header.h> #include "ros/names.h" #include "ros/config_comm.h" #include "ros/param.h" namespace ros { class PeerConnDisconnCallback : public CallbackInterface { public: PeerConnDisconnCallback(const SubscriberStatusCallback& callback, const SubscriberLinkPtr& sub_link, bool use_tracked_object, const VoidConstWPtr& tracked_object) : callback_(callback) , sub_link_(sub_link) , use_tracked_object_(use_tracked_object) , tracked_object_(tracked_object) { } virtual CallResult call() { VoidConstPtr tracker; if (use_tracked_object_) { tracker = tracked_object_.lock(); if (!tracker) { return Invalid; } } SingleSubscriberPublisher pub(sub_link_); callback_(pub); return Success; } private: SubscriberStatusCallback callback_; SubscriberLinkPtr sub_link_; bool use_tracked_object_; VoidConstWPtr tracked_object_; }; Publication::Publication(const std::string &name, const std::string &datatype, const std::string &_md5sum, const std::string& message_definition, size_t max_queue, bool latch, bool has_header) : name_(name), datatype_(datatype), md5sum_(_md5sum), message_definition_(message_definition), max_queue_(max_queue), seq_(0), dropped_(false), latch_(latch), has_header_(has_header), self_published_(false), intraprocess_subscriber_count_(0) { } Publication::~Publication() { drop(); } void Publication::addCallbacks(const SubscriberCallbacksPtr& callbacks) { boost::mutex::scoped_lock lock(callbacks_mutex_); callbacks_.push_back(callbacks); // Add connect callbacks for all current subscriptions if this publisher wants them if (callbacks->connect_ && callbacks->callback_queue_) { boost::mutex::scoped_lock lock(subscriber_links_mutex_); V_SubscriberLink::iterator it = subscriber_links_.begin(); V_SubscriberLink::iterator end = subscriber_links_.end(); for (; it != end; ++it) { const SubscriberLinkPtr& sub_link = *it; CallbackInterfacePtr cb(boost::make_shared<PeerConnDisconnCallback>(callbacks->connect_, sub_link, callbacks->has_tracked_object_, callbacks->tracked_object_)); callbacks->callback_queue_->addCallback(cb, (uint64_t)callbacks.get()); } } } void Publication::removeCallbacks(const SubscriberCallbacksPtr& callbacks) { boost::mutex::scoped_lock lock(callbacks_mutex_); V_Callback::iterator it = std::find(callbacks_.begin(), callbacks_.end(), callbacks); if (it != callbacks_.end()) { const SubscriberCallbacksPtr& cb = *it; if (cb->callback_queue_) { cb->callback_queue_->removeByID((uint64_t)cb.get()); } callbacks_.erase(it); } } void Publication::drop() { // grab a lock here, to ensure that no subscription callback will // be invoked after we return { boost::mutex::scoped_lock lock(publish_queue_mutex_); boost::mutex::scoped_lock lock2(subscriber_links_mutex_); if (dropped_) { return; } dropped_ = true; } dropAllConnections(); } bool Publication::enqueueMessage(const SerializedMessage& m) { boost::mutex::scoped_lock lock(subscriber_links_mutex_); if (dropped_) { return false; } ROS_ASSERT(m.buf); uint32_t seq = incrementSequence(); if (has_header_) { // If we have a header, we know it's immediately after the message length // Deserialize it, write the sequence, and then serialize it again. namespace ser = ros::serialization; std_msgs::Header header; ser::IStream istream(m.buf.get() + 4, m.num_bytes - 4); ser::deserialize(istream, header); header.seq = seq; ser::OStream ostream(m.buf.get() + 4, m.num_bytes - 4); ser::serialize(ostream, header); } for(V_SubscriberLink::iterator i = subscriber_links_.begin(); i != subscriber_links_.end(); ++i) { const SubscriberLinkPtr& sub_link = (*i); if(sub_link->getDefaultTransport()) { sub_link->enqueueMessage(m, true, false); } } if (latch_) { last_message_ = m; } return true; } void Publication::setSelfPublished(bool self_published) { self_published_ = self_published; } bool Publication::getSelfPublished() { return self_published_; } TransportType Publication::getSubscriberlinksTransport() { boost::mutex::scoped_lock lock(subscriber_links_mutex_); uint32_t count = 0 ; bool intraprocess = false; TransportType ret = SHARED_MEMORY ; for (uint32_t i = 0; i< (uint32_t)subscriber_links_.size(); i++ ) { if (subscriber_links_[i]->getDefaultTransport()) { count ++ ; } if (subscriber_links_[i]->isIntraprocess()) { intraprocess = true; } } if (intraprocess || latch_) { for (uint32_t i = 0; i < (uint32_t)subscriber_links_.size(); i++) { subscriber_links_[i]->setDefaultTransport(true); } ret = SOCKET; return ret; } if (count == ((uint32_t)subscriber_links_.size()) && count != 0) { ret = SOCKET; } else if (count < ((uint32_t)subscriber_links_.size()) && count != 0) { ret = BOTH; } else { ret = SHARED_MEMORY; } return ret ; } extern struct ConfigComm g_config_comm; void Publication::addSubscriberLink(const SubscriberLinkPtr& sub_link) { { boost::mutex::scoped_lock lock(subscriber_links_mutex_); if (dropped_) { return; } subscriber_links_.push_back(sub_link); if (sub_link->isIntraprocess()) { ++intraprocess_subscriber_count_; } } if (sub_link->getRospy()) { ROS_DEBUG_STREAM("has rospy sub_link."); sub_link->setDefaultTransport(true); } else if (sub_link->isIntraprocess()) { sub_link->setDefaultTransport(true); ROS_DEBUG_STREAM("Publication self_published:" << getName()); } else if (latch_) { sub_link->setDefaultTransport(true); ROS_DEBUG_STREAM("Publication topic latched:" << getName()); } else if (!g_config_comm.transport_mode && g_config_comm.topic_white_list.find(getName()) == g_config_comm.topic_white_list.end() ) { std::string ip_env; if (get_environment_variable(ip_env, "ROS_IP")) { ROS_DEBUG( "ROS_IP:%s", ip_env.c_str()); if (ip_env.size() == 0) { sub_link->setDefaultTransport(false); ROS_WARN("invalid ROS_IP (an empty string)"); } else { std::string remote_host = sub_link->getConnection()->getRemoteIp(); std::string::size_type remote_colon_pos = remote_host.find_first_of(":"); std::string remote_ip = remote_host.substr(0,remote_colon_pos); std::string local_host = sub_link->getConnection()->getLocalIp(); std::string::size_type local_colon_pos = local_host.find_first_of(":"); std::string local_ip = local_host.substr(0,local_colon_pos); if (remote_ip == local_ip) { ROS_DEBUG_STREAM("Local IP == Remote IP , share memory transport : " << getName()); sub_link->setDefaultTransport(false); } else { ROS_WARN_STREAM("Local IP != Remote IP , socket transport : " << getName() ); sub_link->setDefaultTransport(true); } } } else { sub_link->setDefaultTransport(false); } } else { sub_link->setDefaultTransport(true); } if (latch_ && last_message_.buf) { if (sub_link->getDefaultTransport()) { sub_link->enqueueMessage(last_message_, true, true); } } // This call invokes the subscribe callback if there is one. // This must happen *after* the push_back above, in case the // callback uses publish(). peerConnect(sub_link); } void Publication::removeSubscriberLink(const SubscriberLinkPtr& sub_link) { SubscriberLinkPtr link; { boost::mutex::scoped_lock lock(subscriber_links_mutex_); if (dropped_) { return; } if (sub_link->isIntraprocess()) { --intraprocess_subscriber_count_; } V_SubscriberLink::iterator it = std::find(subscriber_links_.begin(), subscriber_links_.end(), sub_link); if (it != subscriber_links_.end()) { link = *it; subscriber_links_.erase(it); } } if (link) { peerDisconnect(link); } } XmlRpc::XmlRpcValue Publication::getStats() { XmlRpc::XmlRpcValue stats; stats[0] = name_; XmlRpc::XmlRpcValue conn_data; conn_data.setSize(0); // force to be an array, even if it's empty boost::mutex::scoped_lock lock(subscriber_links_mutex_); uint32_t cidx = 0; for (V_SubscriberLink::iterator c = subscriber_links_.begin(); c != subscriber_links_.end(); ++c, cidx++) { const SubscriberLink::Stats& s = (*c)->getStats(); conn_data[cidx][0] = (*c)->getConnectionID(); // todo: figure out what to do here... the bytes_sent will wrap around // on some flows within a reasonable amount of time. xmlrpc++ doesn't // seem to give me a nice way to do 64-bit ints, perhaps that's a // limitation of xml-rpc, not sure. alternatively we could send the number // of KB transmitted to gain a few order of magnitude. conn_data[cidx][1] = (int)s.bytes_sent_; conn_data[cidx][2] = (int)s.message_data_sent_; conn_data[cidx][3] = (int)s.messages_sent_; conn_data[cidx][4] = 0; // not sure what is meant by connected } stats[1] = conn_data; return stats; } // Publisher : [(connection_id, destination_caller_id, direction, transport, topic_name, connected, connection_info_string)*] // e.g. [(2, '/listener', 'o', 'TCPROS', '/chatter', 1, 'TCPROS connection on port 55878 to [127.0.0.1:44273 on socket 7]')] void Publication::getInfo(XmlRpc::XmlRpcValue& info) { boost::mutex::scoped_lock lock(subscriber_links_mutex_); for (V_SubscriberLink::iterator c = subscriber_links_.begin(); c != subscriber_links_.end(); ++c) { XmlRpc::XmlRpcValue curr_info; curr_info[0] = (int)(*c)->getConnectionID(); curr_info[1] = (*c)->getDestinationCallerID(); curr_info[2] = "o"; 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; } } void Publication::dropAllConnections() { // Swap our publishers 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 publishers mutex V_SubscriberLink local_publishers; { boost::mutex::scoped_lock lock(subscriber_links_mutex_); local_publishers.swap(subscriber_links_); } for (V_SubscriberLink::iterator i = local_publishers.begin(); i != local_publishers.end(); ++i) { (*i)->drop(); } } void Publication::peerConnect(const SubscriberLinkPtr& sub_link) { V_Callback::iterator it = callbacks_.begin(); V_Callback::iterator end = callbacks_.end(); for (; it != end; ++it) { const SubscriberCallbacksPtr& cbs = *it; if (cbs->connect_ && cbs->callback_queue_) { CallbackInterfacePtr cb(boost::make_shared<PeerConnDisconnCallback>(cbs->connect_, sub_link, cbs->has_tracked_object_, cbs->tracked_object_)); cbs->callback_queue_->addCallback(cb, (uint64_t)cbs.get()); } } } void Publication::peerDisconnect(const SubscriberLinkPtr& sub_link) { V_Callback::iterator it = callbacks_.begin(); V_Callback::iterator end = callbacks_.end(); for (; it != end; ++it) { const SubscriberCallbacksPtr& cbs = *it; if (cbs->disconnect_ && cbs->callback_queue_) { CallbackInterfacePtr cb(boost::make_shared<PeerConnDisconnCallback>(cbs->disconnect_, sub_link, cbs->has_tracked_object_, cbs->tracked_object_)); cbs->callback_queue_->addCallback(cb, (uint64_t)cbs.get()); } } } size_t Publication::getNumCallbacks() { boost::mutex::scoped_lock lock(callbacks_mutex_); return callbacks_.size(); } uint32_t Publication::incrementSequence() { boost::mutex::scoped_lock lock(seq_mutex_); uint32_t old_seq = seq_; ++seq_; return old_seq; } uint32_t Publication::getNumSubscribers() { boost::mutex::scoped_lock lock(subscriber_links_mutex_); return (uint32_t)subscriber_links_.size(); } void Publication::getPublishTypes(bool& serialize, bool& nocopy, const std::type_info& ti) { boost::mutex::scoped_lock lock(subscriber_links_mutex_); V_SubscriberLink::const_iterator it = subscriber_links_.begin(); V_SubscriberLink::const_iterator end = subscriber_links_.end(); for (; it != end; ++it) { const SubscriberLinkPtr& sub = *it; bool s = false; bool n = false; sub->getPublishTypes(s, n, ti); serialize = serialize || s; nocopy = nocopy || n; if (serialize && nocopy) { break; } } } bool Publication::hasSubscribers() { boost::mutex::scoped_lock lock(subscriber_links_mutex_); return !subscriber_links_.empty(); } void Publication::publish(SerializedMessage& m) { if (m.message) { boost::mutex::scoped_lock lock(subscriber_links_mutex_); V_SubscriberLink::const_iterator it = subscriber_links_.begin(); V_SubscriberLink::const_iterator end = subscriber_links_.end(); for (; it != end; ++it) { const SubscriberLinkPtr& sub = *it; if (sub->isIntraprocess()) { sub->enqueueMessage(m, false, true); } } m.message.reset(); } if (m.buf) { boost::mutex::scoped_lock lock(publish_queue_mutex_); publish_queue_.push_back(m); } } void Publication::processPublishQueue() { V_SerializedMessage queue; { boost::mutex::scoped_lock lock(publish_queue_mutex_); if (dropped_) { return; } queue.insert(queue.end(), publish_queue_.begin(), publish_queue_.end()); publish_queue_.clear(); } if (queue.empty()) { return; } V_SerializedMessage::iterator it = queue.begin(); V_SerializedMessage::iterator end = queue.end(); for (; it != end; ++it) { enqueueMessage(*it); } } bool Publication::validateHeader(const Header& header, std::string& error_msg) { std::string md5sum, topic, client_callerid; if (!header.getValue("md5sum", md5sum) || !header.getValue("topic", topic) || !header.getValue("callerid", client_callerid)) { std::string msg("Header from subscriber did not have the required elements: md5sum, topic, callerid"); ROS_ERROR("%s", msg.c_str()); error_msg = msg; return false; } // Check whether the topic 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 (isDropped()) { std::string msg = std::string("received a tcpros connection for a nonexistent topic [") + topic + std::string("] from [" + client_callerid +"]."); ROS_ERROR("%s", msg.c_str()); error_msg = msg; return false; } if (getMD5Sum() != md5sum && (md5sum != std::string("*") && getMD5Sum() != std::string("*"))) { std::string datatype; header.getValue("type", datatype); std::string msg = std::string("Client [") + client_callerid + std::string("] wants topic ") + topic + std::string(" to have datatype/md5sum [") + datatype + "/" + md5sum + std::string("], but our version has [") + getDataType() + "/" + getMD5Sum() + std::string("]. Dropping connection."); ROS_ERROR("%s", msg.c_str()); error_msg = msg; return false; } return true; } } // namespace ros
0