Suppose I have defined two custom dynamic parameters, gain1 and gain2, in a cfg file. I would like to use these in a node that subscribes and publishes to two topics. Here's what i tried:
import rospy
from std_msgs.msg import Float64
from dynamic_reconfigure.server import Server
from myPack.cfg import paramConfig
def param_callback(config, level):
gain1 = config.gain1
gain2 = config.gain2
return config
def callback1(msg):
in1 = msg.data
def callback2(msg):
in2 = msg.data
rospy.init_node('mixer')
srv = Server(paramConfig, param_callback)
sub1 = rospy.Subscriber('in1', Float64, callback1)
sub2 = rospy.Subscriber('in2', Float64, callback2)
pub1 = rospy.Subscriber('out1', Float64)
pub2 = rospy.Subscriber('out2', Float64)
out1 = Float64()
out2 = Float64()
while not rospy.is_shutdown():
out1.data = in1*gain1
out2.data = in2*gain2
pub1.publish(out1)
pub2.publish(out2)
But it seems the subscribers callbacks don't work. This error is given for the first line of the while loop.
NameError: name 'in1' is not defined
Note that the subscription and parameter server code work fine individually.
Am I using the right method?
**Update:**
As suggested by gvdhoorn, I had to define `in1`, `in2`, `gain1` and `gain2` as global variables **and** initialize `in1` and `in2` before the while loop. The latter because the program could reach the while loop before a callback. In this case, `in1` is still undefined and I would receive the same error .
I feel this method is a bit inelegant and as gvdhoorn pointed out, using a class instead of global variables is better programming.
↧