Create publisher each time a service is called
I have a node that offers some services for sending commands to different devices.
Each one of these devices have an identifier, so when a service is called, you have to send the identifier and then, this node will send an String message to the topic json_cmd/ + identifier.
I'm doing this right now inside the callback of each service:
def command(self, req):
template_copy = copy.deepcopy(self.command_template)
template_copy["timeStamp"] = self.__get_timestamp()
template_copy["commandUUID"] = str(uuid.uuid1())
template_copy["commandType"] = CommandList.PAUSE
publisher = rospy.Publisher("json_cmd/" + req.id, String, queue_size=10)
publisher.publish(json.dumps(template_copy))
return True
But I'm not sure if it's a good practice to create the publisher each time or if there's a way to publish once without creating an object.
Also it's important to say that I don't know all the identifiers at the beginning, so I can't create the publishers on start.