siemens / ros-sharp

ROS# is a set of open source software libraries and tools in C# for communicating with ROS from .NET applications, in particular Unity3D
Apache License 2.0
984 stars 373 forks source link

Subscribe to topic by specifying the Type as a string #447

Open sosborne-control2k opened 1 year ago

sosborne-control2k commented 1 year ago

I have a question!

Here is my question: I am trying to connect to and subscribe to Topics on ROSbridge. It works fine if i specify the Type of message upon subscribing as per the code example in the Test Client:

          rosSocket = new RosSocket(new RosBridgeClient.Protocols.WebSocketNetProtocol(uri), RosSocket.SerializerEnum.Newtonsoft_JSON);
string subscription_id = rosSocket.Subscribe<JointState>("/joint_states", SubscriptionHandler);

however I wish to be able to specify the topic and type by string and find that type and call the subscribe method.

I know I can do it with an exhaustive Switch e.g.:

        public static string Subscribe(string type, string topic) 
        {
            switch (type)
            {
                case "sensor_msgs/JointState":
                    return rosSocket.Subscribe<JointState>(topic, SubscriptionHandler);
                    break;
                case "actionlib_msgs/GoalID":
                    return rosSocket.Subscribe<GoalID>(topic, SubscriptionHandler);
                    break;
            }
            return "";
        }

But this will get pretty long and unmanageable especially if i add new Message types for different robots. I have therefore spent some time trying to use reflection to get the type to invoke the Subscribe call, but I seem to be falling over when trying to pass in the Subscription handler. Has anyone done similar, or provide an example of how to do this - many thanks.