subscriber_state.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 import rostopic
3 from flexbe_core import EventState, Logger
4 
5 from flexbe_core.proxy import ProxySubscriberCached
6 
7 
8 class SubscriberState(EventState):
9  '''
10  Gets the latest message on the given topic and stores it to userdata.
11 
12  -- topic string The topic on which should be listened.
13  -- blocking bool Blocks until a message is received.
14  -- clear bool Drops last message on this topic on enter
15  in order to only handle message received since this state is active.
16 
17  #> message object Latest message on the given topic of the respective type.
18 
19  <= received Message has been received and stored in userdata or state is not blocking.
20  <= unavailable The topic is not available when this state becomes actives.
21  '''
22 
23  def __init__(self, topic, blocking=True, clear=False):
24  super(SubscriberState, self).__init__(outcomes=['received', 'unavailable'],
25  output_keys=['message'])
26  self._topic = topic
27  self._blocking = blocking
28  self._clear = clear
29  self._connected = False
30 
31  if not self._connect():
32  Logger.logwarn('Topic %s for state %s not yet available.\n'
33  'Will try again when entering the state...' % (self._topic, self.name))
34 
35  def execute(self, userdata):
36  if not self._connected:
37  userdata.message = None
38  return 'unavailable'
39 
40  if self._sub.has_msg(self._topic) or not self._blocking:
41  userdata.message = self._sub.get_last_msg(self._topic)
42  self._sub.remove_last_msg(self._topic)
43  return 'received'
44 
45  def on_enter(self, userdata):
46  if not self._connected:
47  if self._connect():
48  Logger.loginfo('Successfully subscribed to previously unavailable topic %s' % self._topic)
49  else:
50  Logger.logwarn('Topic %s still not available, giving up.' % self._topic)
51 
52  if self._connected and self._clear and self._sub.has_msg(self._topic):
53  self._sub.remove_last_msg(self._topic)
54 
55  def _connect(self):
56  msg_type, msg_topic, _ = rostopic.get_topic_class(self._topic)
57  if msg_topic == self._topic:
58  self._sub = ProxySubscriberCached({self._topic: msg_type})
59  self._connected = True
60  return True
61  return False
def __init__(self, topic, blocking=True, clear=False)


flexbe_states
Author(s): Philipp Schillinger
autogenerated on Sun Dec 13 2020 04:01:46