Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #include <ros/ros.h>
00020
00021 #include <variant_topic_tools/Publisher.h>
00022
00023 ros::NodeHandlePtr nodeHandle;
00024
00025 variant_topic_tools::Publisher publisher;
00026 std::string publisherTopic;
00027 std::string publisherType;
00028 double publisherRate = 0.0;
00029 size_t publisherQueueSize = 100;
00030 ros::Timer publisherTimer;
00031
00032 variant_topic_tools::MessageDefinition messageDefinition;
00033 variant_topic_tools::MessageType messageType;
00034
00035 bool getTopicBase(const std::string& topic, std::string& topicBase) {
00036 std::string tmp = topic;
00037 int i = tmp.rfind('/');
00038
00039 while( (tmp.size() > 0) && (i >= (int)(tmp.size()-1))) {
00040 tmp = tmp.substr(0,tmp.size()-1);
00041 i = tmp.rfind('/');
00042 }
00043
00044 if (tmp.size() == 0)
00045 return false;
00046
00047 if(i < 0)
00048 topicBase = tmp;
00049 else
00050 topicBase = tmp.substr(i+1, tmp.size()-i-1);
00051
00052 return true;
00053 }
00054
00055 void publishOnce() {
00056 if (!messageDefinition.isValid())
00057 messageDefinition.load(publisherType);
00058
00059 if (!messageType.isValid())
00060 messageType = messageDefinition.getMessageDataType();
00061
00062 if (!publisher)
00063 publisher = messageType.advertise(*nodeHandle, publisherTopic,
00064 publisherQueueSize, true);
00065
00066 variant_topic_tools::MessageVariant variant = messageDefinition.
00067 getMessageDataType().createVariant();
00068
00069 publisher.publish(variant);
00070 }
00071
00072 void publish(const ros::TimerEvent& event) {
00073 publishOnce();
00074 }
00075
00076 int main(int argc, char **argv) {
00077 if (argc < 3) {
00078 printf("\nusage: echo TOPIC TYPE [RATE]\n\n");
00079 return 1;
00080 }
00081
00082 if (!getTopicBase((argv[1]), publisherTopic)) {
00083 ROS_ERROR("Failed to extract topic base from [%s]", argv[1]);
00084 return 1;
00085 }
00086
00087 ros::init(argc, argv, publisherTopic+"_publish",
00088 ros::init_options::AnonymousName);
00089
00090 nodeHandle.reset(new ros::NodeHandle("~"));
00091
00092 publisherTopic = argv[1];
00093 publisherType = argv[2];
00094 if (argc > 3)
00095 publisherRate = boost::lexical_cast<double>(argv[3]);
00096
00097 if (publisherRate > 0.0) {
00098 publisherTimer = nodeHandle->createTimer(ros::Rate(publisherRate).
00099 expectedCycleTime(), &publish);
00100 }
00101 else
00102 publishOnce();
00103
00104 ros::AsyncSpinner spinner(1);
00105 spinner.start();
00106 ros::waitForShutdown();
00107
00108 publisherTimer.stop();
00109
00110 return 0;
00111 }