Pass arguments to subscriber callback #42
-
Hello, I wonder if it it is possible to pass an extra parameter to the subscriber callback. Does goroslib allow this somehow? What is the appropriate way of doing this? I checked the SubscriberConf struct definition, https://github.com/aler9/goroslib/blob/978eeb6e825ee627aa2b33a765024ae9991139b2/subscriber.go#L24 and it does not seem have any field dedicated to this possibility. Is it possible to achieve this through the interface destined for the callback? The NewSubscriber function seems to limit this a bit https://github.com/aler9/goroslib/blob/978eeb6e825ee627aa2b33a765024ae9991139b2/subscriber.go#L78 Context: my use case requires multiple topic subscriptions of the same type. For that I need to know to which topic, each message received belongs to. With rospy I would simply do something similar to what is suggested in the answer of this post https://answers.ros.org/question/231492/passing-arguments-to-callback-in-python/. Apologies in advance if this is a golang specific question. Best regards, |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Hello, one of the advantages of Golang with respect to Python is that it supports anonymous functions, therefore, you can add as many arguments as you want to the callback function, in this way package main
import (
"fmt"
"github.com/aler9/goroslib"
"github.com/aler9/goroslib/pkg/msgs/sensor_msgs"
)
func onMessage(msg *sensor_msgs.Imu, topicName string) {
fmt.Printf("Incoming: %+v\n", msg)
fmt.Println("topic name:", topicName)
}
func main() {
// create a node and connect to the master
n, err := goroslib.NewNode(goroslib.NodeConf{
Name: "goroslib_sub",
MasterAddress: "127.0.0.1:11311",
})
if err != nil {
panic(err)
}
defer n.Close()
// create a subscriber
sub, err := goroslib.NewSubscriber(goroslib.SubscriberConf{
Node: n,
Topic: "test_topic",
Callback: func (msg *sensor_msgs.Imu) {
onMessage(msg, "test_topic")
},
})
if err != nil {
panic(err)
}
defer sub.Close()
// freeze main loop
select {}
} |
Beta Was this translation helpful? Give feedback.
-
Ahh perfect! That answered my question 👍 . |
Beta Was this translation helpful? Give feedback.
-
For anyone else that lands here, believe this should be: sub, err := goroslib.NewSubscriber(goroslib.SubscriberConf{
Node: n,
Topic: "test_topic",
Callback: func (msg *sensor_msgs.Imu) {
onMessage(msg, "test_topic")
},
}) |
Beta Was this translation helpful? Give feedback.
Hello, one of the advantages of Golang with respect to Python is that it supports anonymous functions, therefore, you can add as many arguments as you want to the callback function, in this way