Go to the documentation of this file.00001 import rospy
00002 import rosgraph
00003 from urlparse import urlparse
00004 from .dbm_param import DBMParam
00005
00006 class DBMOptimizer:
00007 def __init__(self, get_new_frequencies_method):
00008 self.__get_new_frequencies_method = get_new_frequencies_method
00009 self.__optimization_rate = rospy.get_param('dbm/optimization_rate', 1)
00010 self.__loop_rate = rospy.Rate(self.__optimization_rate)
00011
00012 def start(self):
00013 while not rospy.is_shutdown():
00014 managed_topics = rospy.get_param('dbm/topics', {})
00015 self.__verify_if_topics_should_be_managed(managed_topics)
00016 managed_topics = [topic for topic, isManaged in managed_topics.iteritems() if isManaged == 1]
00017 frequencies = self.__get_new_frequencies_method(managed_topics)
00018 for key in frequencies:
00019 DBMParam.set_current_frequency(key, frequencies[key])
00020 self.__loop_rate.sleep()
00021
00022 def __verify_if_topics_should_be_managed(self, topics):
00023 for topic in topics.keys():
00024 if self.__there_are_external_subscribers(topic):
00025 topics[topic] = 1
00026 else:
00027 topics[topic] = 0
00028 rospy.set_param("/dbm/topics", topics)
00029 return topics
00030
00031 def __there_are_external_subscribers(self, topic):
00032 pubs = self.__get_publishers(topic)
00033 subs = self.__get_subscribers(topic)
00034 if len(subs) == 0:
00035 return False
00036 elif rospy.get_param('dbm/manage_local_subscribers', False):
00037 return True
00038 elif self.__publishers_and_subscribers_are_in_the_same_host(pubs, subs):
00039 return False
00040 else:
00041 return True
00042
00043 def __get_subscribers(self, topic):
00044 topic = rosgraph.names.script_resolve_name('rostopic', topic)
00045 master = rosgraph.Master('/rostopic')
00046 state = master.getSystemState()
00047 subs = [x[1] for x in state[1] if x[0] == topic]
00048 if len(subs) > 0:
00049 return subs[0]
00050 else:
00051 return []
00052
00053 def __get_publishers(self, topic):
00054 topic = rosgraph.names.script_resolve_name('rostopic', topic)
00055 master = rosgraph.Master('/rostopic')
00056 state = master.getSystemState()
00057 pubs = [x[1] for x in state[0] if x[0] == topic]
00058 if len(pubs) > 0:
00059 return pubs[0]
00060 else:
00061 return []
00062
00063 def __get_node_location(self, node_name):
00064 master = rosgraph.Master('/rosnode')
00065 node_uri = urlparse(master.lookupNode(node_name))
00066 return node_uri.hostname
00067
00068 def __publishers_and_subscribers_are_in_the_same_host(self, pubs, subs):
00069 for publisher in pubs:
00070 for subscriber in subs:
00071 if self.__get_node_location(publisher) != self.__get_node_location(subscriber):
00072 return False
00073 return True