本文整理汇总了Python中rospy.rostime.Time类的典型用法代码示例。如果您正苦于以下问题:Python Time类的具体用法?Python Time怎么用?Python Time使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Time类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_start_end_time
def _get_start_end_time(self, limit):
"""
Returns the start and end time to use (rospy.Time).
also sets self.start_stamp, self.end_stamp
"""
from rospy.rostime import Time # @UnresolvedImport
self.info('limit: %r' % limit)
warnings.warn('Make better code for dealing with unindexed')
if limit is not None and limit != 0:
# try:
chunks = self.bag.__dict__['_chunks']
self.start_stamp = chunks[0].start_time.to_sec()
self.end_stamp = chunks[-1].end_time.to_sec()
start_time = Time.from_sec(self.start_stamp)
end_time = Time.from_sec(self.start_stamp + limit)
return start_time, end_time
# except Exception as e:
# self.error('Perhaps unindexed bag?')
# self.error(traceback.format_exc(e))
# raise
# start_time = None
# end_time = None
#
# self.info('start_stamp: %s' % self.start_stamp)
# self.info('end_stamp: %s' % self.end_stamp)
else:
self.start_stamp = None
self.end_stamp = None
return None, None
示例2: get_short_data
def get_short_data(self):
"""
Returns a shortend version of the item data.
:returns: data of the item
:rtype: str
"""
data_dict = self.get_latest_data()
if data_dict["window_stop"] == Time(0):
return "No data yet"
elif (Time.now() - data_dict["window_stop"]) > Duration(MAXIMUM_OFFLINE_TIME):
# last entry was more than MAXIMUM_OFFLINE_TIME ago, it could be offline!
return "No data since " + prepare_number_for_representation(Time.now() - data_dict["window_stop"]) \
+ " seconds"
content = ""
if data_dict["state"] is "error":
content += self.get_erroneous_entries_for_log()
else:
content += self.tr("frequency") + ": " + prepare_number_for_representation(data_dict["frequency"]) \
+ " " + self.tr("frequency_unit") + " - "
content += self.tr("bandwidth") + ": " + prepare_number_for_representation(
data_dict["bandwidth"]) + " " \
+ self.tr("bandwidth_unit") + " - "
content += self.tr("dropped_msgs") + ": " + prepare_number_for_representation(data_dict["dropped_msgs"]) \
+ " " + self.tr("dropped_msgs_unit")
return content
示例3: get_short_data
def get_short_data(self):
"""
Returns a shortend version of the item data.
:returns: data of the item
:rtype: str
"""
data_dict = self.get_latest_data()
if data_dict["window_stop"] == Time(0):
return "No data yet"
elif (Time.now() - data_dict["window_stop"]) > Duration(MAXIMUM_OFFLINE_TIME):
# last entry was more than MAXIMUM_OFFLINE_TIME ago, it could be offline!
return "No data since " + str(round((Time.now() - data_dict["window_stop"]).to_sec(), ROUND_DIGITS)) \
+ " seconds"
content = ""
if data_dict["state"] is "error":
content += self.get_erroneous_entries_for_log()
else:
content += self.tr("node_cpu_usage_mean") + ": " + prepare_number_for_representation(
data_dict["node_cpu_usage_mean"]) + " " + self.tr("node_cpu_usage_mean_unit") + " - "
content += self.tr("node_ramusage_mean") + ": " + prepare_number_for_representation(
data_dict["node_ramusage_mean"]) \
+ " " + self.tr("node_ramusage_mean_unit") + " - "
content += self.tr("node_message_frequency_mean") + ": " + prepare_number_for_representation(
data_dict["node_message_frequency_mean"]) \
+ " " + self.tr("node_message_frequency_mean_unit") + " - "
content += self.tr("node_bandwidth_mean") + ": " + prepare_number_for_representation(
data_dict["node_bandwidth_mean"]) \
+ " " + self.tr("node_bandwidth_mean_unit")
return content
示例4: update_rated_data
def update_rated_data(self, data):
"""
Appends data to the rated_data of the AbstractItem.
:param data: the data to append in key value form
:type data: RatedStatistics
:raises KeyError: if an entry is in the rated dictionary but not found in the message
"""
self._rated_data_lock.acquire()
self._rated_data["window_start"].append(data.window_start)
self._rated_data["window_stop"].append(data.window_stop)
last_state = self.get_state()
new_state = "unknown"
for element in data.rated_statistics_entity:
self._rated_data[element.statistic_type + ".actual_value"].append(element.actual_value)
self._rated_data[element.statistic_type + ".expected_value"].append(element.expected_value)
for i in range(0, len(element.state)):
state = topic_statistics_state_to_string(element, element.state[i])
self._rated_data[element.statistic_type + ".state"].append(state)
if (state is "low" or state is "high") and state is not "ok" and state is not "unkown":
new_state = "error"
elif state is "ok" and new_state is not "error":
new_state = "ok"
self.add_state(new_state)
self._update_current_state()
if new_state is "error" and last_state is not "error":
self._logger.log("error", Time.now(), self.seuid, self.get_erroneous_entries_for_log())
self._rated_data_lock.release()
示例5: append_data_dict
def append_data_dict(self, data):
"""
Appends data to the data of the AbstractItem.
:param data: the data to append in key value form
:type data: dict
:raises KeyError: if an entry is in the global data dictionary but not found in the given dictionary
"""
self._data_lock.acquire()
self.alive = True
if "window_stop" not in data:
data["window_stop"] = Time.now()
for attribute in self._data:
if attribute in data:
self._data[attribute].append(data[attribute])
else:
self._data[attribute].append(None)
if "state" in data:
self.add_state((data["state"]))
else:
self.add_state("unknown")
self._length_of_data += 1
self._update_current_state()
self._data_lock.release()
示例6: __transform_rated_statistics_item
def __transform_rated_statistics_item(self, item):
"""
Integrates RatedStatistics in the model by moding its item/s by adding a new dict to the corresponding item.
:param item: the RatedStatisics item
:type item: RatedStatistics
"""
# get identifier
seuid = item.seuid
if item.seuid == "t!/image_raw":
tmp = self.__identifier_dict[seuid]
for i in range(0, len(item.rated_statistics_entity)):
if item.rated_statistics_entity[i].statistic_type == "frequency":
print(item.rated_statistics_entity[i].actual_value)
print(tmp.get_latest_data()["frequency"])
# check if avaiable
if seuid not in self.__identifier_dict:
# having a problem, item doesn't exist but should not be created here
self.__logger.log("Warning", Time.now(), "RosModel", "A rating was received for an item the gui does not "
"know about. This typically means a dead node/ host but"
" could also indicate an error. If this happens at "
"startup you can typically ignore it. ")
else:
# update it
current_item = self.__identifier_dict[seuid]
current_item.update_rated_data(item)
示例7: get_short_data
def get_short_data(self):
"""
Returns a shortend version of the item data.
:returns: data of the item
:rtype: str
"""
data_dict = self.get_latest_data()
if data_dict["window_stop"] == Time(0):
return "No data yet"
elif (Time.now() - data_dict["window_stop"]) > Duration(MAXIMUM_OFFLINE_TIME):
# last entry was more than MAXIMUM_OFFLINE_TIME ago, it could be offline!
return (
"No data since " + prepare_number_for_representation(Time.now() - data_dict["window_stop"]) + " seconds"
)
content = ""
if data_dict["state"] is "error":
content += self.get_erroneous_entries_for_log()
else:
content += (
self.tr("cpu_usage_mean")
+ ": "
+ prepare_number_for_representation(data_dict["cpu_usage_mean"])
+ " "
+ self.tr("cpu_usage_mean_unit")
+ " - "
)
content += (
self.tr("ram_usage_mean")
+ ": "
+ prepare_number_for_representation(data_dict["ram_usage_mean"])
+ " "
+ self.tr("ram_usage_mean_unit")
+ " - "
)
content += (
self.tr("cpu_temp_mean")
+ ": "
+ prepare_number_for_representation(data_dict["cpu_temp_mean"])
+ " "
+ self.tr("cpu_temp_mean_unit")
)
return content
示例8: __aggregate_topic_data
def __aggregate_topic_data(self, event):
"""
Aggregates the topic every TOPIC_AGGREGATION_FREQUENCY nsecs and pushes the updated data to
self.__calculated_data.
:param event: containing information when this method was called - not used but needed for the interface
"""
aggregated_data = {}
for key in self._attributes:
aggregated_data[key] = 0
for key in self.__calculated_data.keys():
self.__calculated_data[key].append(0)
child_count = 0
for connection in self.get_childs(): # !assuming all childs are connection items!
values = connection.aggregate_data(self.__aggregation_window) # average over N seconds
if values:
for key in self.add_keys:
aggregated_data[key] += values[key]
for key in self.max_keys:
if values[key] > aggregated_data[key]:
aggregated_data[key] = values[key]
for key in self.avg_keys:
aggregated_data[key] += values[key]
child_count += 1
for key in self.avg_keys:
if child_count == 0:
aggregated_data[key] = 0
else:
aggregated_data[key] /= child_count
self._data_lock.acquire()
for key in self._attributes:
self.__calculated_data[key][-1] = aggregated_data[key]
self.__calculated_data["window_start"][-1] = Time.now()
self.__calculated_data["window_stop"][-1] = Time.now() - (Duration(secs=1) if int(Duration(secs=1).to_sec()) <= int(Time.now().to_sec()) else Time(0))
self._data_lock.release()
示例9: __init__
def __init__(self, parent=None):
"""
Defines the class attributes especially the root_item which later contains the list of headers e.g. for a
TreeView representation.
:param parent: the parent of the model
:type parent: QObject
"""
super(ROSModel, self).__init__(parent)
self.__logger = ModelLogger()
self._translator = QTranslator()
# internationalize everything including the 2 plugins
self.rp = rospkg.RosPack()
directory = os.path.join(self.rp.get_path('arni_gui'), 'translations')
files = find_qm_files(directory)
translator = self.get_translator()
# todo: make this more intelligent (should be done as soon as new languages are needed / implemented)
print("chose translation " + files[0])
translator.load(files[0])
qApp.installTranslator(translator)
self.__root_item = RootItem(self.__logger, "abstract", self)
self.__parent = parent
self.__model_lock = Lock()
self.update_signal.connect(self.update_model)
"""
IMPORTANT: Does not contain the models nodes but the logical nodes. E.g. a ConnectionItem splits up to two
TreeConnectionItems where the identifier_dict only contains the connectionitem. This allows to push
data into one item but to show it at two places in the Qt GUI.
"""
self.__identifier_dict = {"root": self.__root_item}
self.__item_delegate = SizeDelegate()
# CAUTION: Do not change this mapping if not absolutely necessary. If you change it remember to change
# item_filter_proxy (and maybe other classes) as well - sadly not all functions use the access function.
self.__mapping = {
0: 'type',
1: 'name',
2: 'state',
3: 'data'
}
self.__last_time_error_occured = 0
self.__logger.log("info", Time.now(), "ROSModel", "ROSModel initialization finished")
self.__seuid_helper = SEUID()
self.__find_host = HostLookup()
self.__buffer_thread = BufferThread(self)
self.__buffer_thread.start()
示例10: get_short_data
def get_short_data(self):
"""
Returns a shortend version of the item data.
:returns: data of the item
:rtype: str
"""
data_dict = {}
for key in self.__calculated_data:
if self.__calculated_data[key]:
data_dict[key] = self.__calculated_data[key][-1]
else:
data_dict[key] = self.tr("Currently no value available")
data_dict["window_stop"] = Time(0)
data_dict["window_start"] = Time(0)
data_dict["state"] = self.get_state()
try:
if data_dict["window_stop"] == Time(0):
return "No data yet"
elif (Time.now() - data_dict["window_stop"]) > Duration(MAXIMUM_OFFLINE_TIME):
# last entry was more than MAXIMUM_OFFLINE_TIME ago, it could be offline!
return "No data since " + prepare_number_for_representation(Time.now() - data_dict["window_stop"]) \
+ " seconds"
except:
print(data_dict["window_stop"])
raise UserWarning
content = ""
if data_dict["state"] is "error":
content += self.get_erroneous_entries_for_log()
else:
content += self.tr("frequency") + ": " + prepare_number_for_representation(
data_dict["frequency"]) + " " \
+ self.tr("frequency_unit") + " - "
content += self.tr("bandwidth") + ": " + prepare_number_for_representation(data_dict["bandwidth"]) \
+ " " + self.tr("bandwidth_unit") + " - "
content += self.tr("dropped_msgs") + ": " + prepare_number_for_representation(data_dict["dropped_msgs"]) \
+ " " + self.tr("dropped_msgs_unit")
return content
示例11: __init__
def __init__(self, logger, seuid, parent=None):
"""
Initializes the AbstractItem.
:param seuid: the seuid of the AbstractItem
:type seuid: str
:param logger: a logger where to log when special events occur
:type logger: ModelLogger
:param parent: the parent-item
:type parent: AbstractItem
"""
super(AbstractItem, self).__init__(parent)
self._logger = logger
self._data = {}
self.counter = 0
"""
_rated_data is dict containing the rated data. state, window_start and window_end are simply lists
with the corresponding entries. Any other values typically is a list containing lists which however contain the
values. This is equivalent to the representation in the RatedStatistics/Entity.
"""
self._rated_data = {}
self._child_items = []
self.__parent = parent
self.seuid = seuid
self._type = "type"
self.__data_attribute = "data"
self.__state = []
# self.__last_update = Time.now()
self.__creation_time = Time.now()
self.marked = False
# self.markation_date = Time.now()
self._add_data_list("window_start")
self._add_data_list("window_stop")
self._add_rated_data_list("window_start")
self._add_rated_data_list("window_stop")
self._length_of_data = 0
self._length_of_rated_data = 0
self._data_lock = Lock()
self._rated_data_lock = Lock()
self._rated_attributes = []
self._rated_attributes.append("alive.actual_value")
self._rated_attributes.append("alive.expected_value")
self._rated_attributes.append("alive.state")
#self._alive_timer = rospy.Time.now()
#self.alive = True
#rospy.Timer(rospy.Duration(ALIVE_TIMER_CALLBACK), self._updateTimer)
#self._offline_time = rospy.Duration(MAXIMUM_OFFLINE_TIME)
self.is_subscriber = False
示例12: update_graphs
def update_graphs(self, event):
"""
Updates and redraws the graphs.
"""
self.__update_graphs_lock.acquire()
if self.__selected_item is not None:
if self.__draw_graphs or self.__first_update_pending:
#print("items per group: " + str(self.__items_per_group))
#print("combo index: " + str(self.__current_selected_combo_box_index))
#print("len plot " + str(len(self.__plotable_items)))
plotable_items = self.__plotable_items[min(self.__current_selected_combo_box_index *
self.__items_per_group, len(self.__plotable_items)):min((self.__current_selected_combo_box_index + 1)
* self.__items_per_group, len(self.__plotable_items))]
plotable_data = self.__selected_item.get_items_younger_than(
#Time.now() - Duration(secs=self.__combo_box_index_to_seconds(self.__current_range_combo_box_index)),
Time.now() - (Duration(secs=(self.__combo_box_index_to_seconds(self.__current_range_combo_box_index) + 10 )) if int(Duration(secs=self.__combo_box_index_to_seconds(self.__current_range_combo_box_index)).to_sec()) <= int(Time.now().to_sec()) else Time(0) ),
"window_stop", *plotable_items)
if "window_stop" in plotable_data:
if plotable_data["window_stop"]:
temp_time = []
temp_content = []
length = len(plotable_data["window_stop"])
modulo = (length / 200) + 1
for i in range(0, length, modulo):
# now having maximally 100 items to plot :)
temp_time.append(plotable_data["window_stop"][i].to_sec())
x = np.array(temp_time)
list_entries = self.__selected_item.get_list_items()
time_entries = self.__selected_item.get_time_items()
for key in plotable_items:
if key in list_entries:
pass
else:
if key in time_entries:
for i in range(0, length, modulo):
temp_content.append(float(str(plotable_data[key][i]))/1000000000)
else:
for i in range(0, length, modulo):
temp_content.append(plotable_data[key][i])
y = np.array(temp_content)
del temp_content[:]
self.__plotted_curves[key].setData(x=x, y=y)
else:
pass
self.__first_update_pending = False
self.__update_graphs_lock.release()
示例13: create_graphs
def create_graphs(self):
"""
Creates the graphs for the plot.
"""
self.__update_graphs_lock.acquire()
if self.__selected_item is not None:
first_iteration = True
first_view = None
i = 0
self.__expected_items_per_group = 0
self.__graph_layout.clear()
if len(self.__plotable_items) is 0:
raise UserWarning()
for key in self.__plotable_items[min(self.__current_selected_combo_box_index *
self.__items_per_group, len(self.__plotable_items)):
min((self.__current_selected_combo_box_index + 1)
* self.__items_per_group, len(self.__plotable_items))]:
plot_widget = None
if first_iteration:
first_iteration = False
date_axis = DateAxis(orientation="bottom")
first_view = pg.ViewBox()
plot_widget = self.__graph_layout.addPlot(title=self.tr(key), axisItems={'bottom': date_axis}, viewBox=first_view)
else:
date_axis = DateAxis(orientation="bottom")
view_box = pg.ViewBox()
plot_widget = self.__graph_layout.addPlot(title=self.tr(key), viewBox=view_box, axisItems={'bottom': date_axis})
view_box.setXLink(first_view)
#performance enhancements when only a short range of the plot is shown
#plot_widget.setClipToView(clip=True)
plot_widget.setYRange(-1, 1)
self.__graph_dict[key] = plot_widget
self.__graph_layout.nextRow()
plot_widget = self.__graph_dict[key]
plot_widget.showGrid(x=True, y=True)
plot_widget.setMenuEnabled(enableMenu=True)
plot_widget.enableAutoRange('xy', True)
x = np.array([1])
y = np.array([int(str(Time.now()))/1000000000])
self.__plotted_curves[key] = plot_widget.plot(x=x, y=y, fillLevel=0, brush=(50, 50, 200, 100),
pen=(255, 0, 0))
self.__expected_items_per_group += 1
self.__first_update_pending = True
self.__update_graphs_lock.release()
示例14: execute_action
def execute_action(self, action):
"""
Sends a signal to top or restart the node.
:param action: action to be executed
:type action: RemoteAction
"""
host_formatted = helper.underscore_ip(self.__parent.get_seuid()[2:])
service_name = "/execute_node_reaction/%s" % host_formatted
try:
execute = rospy.ServiceProxy(
service_name, NodeReaction)
resp = execute(self.seuid[2:], action, '')
except ServiceException:
self._logger.log("error", Time.now(), self.seuid, "could not stop node %s, service %s not found"
% (self.seuid, service_name))
示例15: decode
def decode(self, _, data):
""" Generate a rospy.rostime.Time instance based on the given data of
the form 'YYYY-MM-DDTHH:MM:SS.mmmmmm' (ISO 8601).
"""
if '+' in data:
data = data[:data.index('+')]
try:
dt = datetime(year=int(data[0:4]), month=int(data[5:7]),
day=int(data[8:10]), hour=int(data[11:13]),
minute=int(data[14:16]), second=int(data[17:19]),
microsecond=int(data[20:]))
except ValueError:
return Time()
return Time.from_sec(time.mktime(dt.timetuple()))