Beispiel #1
0
 def setUp(self):
     states = ['A', 'B', {'name': 'C', 'children': ['1', '2', {'name': '3', 'children': ['a', 'b', 'c']}]},
               'D', 'E', 'F']
     self.stuff = Stuff(states, machine_cls=Machine)
     self.stuff.heavy_processing = heavy_processing
     self.stuff.machine.add_transition('process', '*', 'B', before='heavy_processing')
     self.stuff.informer = rsb.createInformer(self.TEST_SCOPE, dataType=int)
     converter = rsb.converter.ProtocolBufferConverter(messageClass=Value)
     rsb.converter.registerGlobalConverter(converter, True)
     self.stuff.informer_rst = rsb.createInformer(self.TEST_SCOPE, dataType=Value)
Beispiel #2
0
    def __init__(self, rsb_scope, rsb_config, wamp, message_type, mode=BIDIRECTIONAL, wamp_scope=None):
        logger.info("register scopes:")
        self.mode = mode
        self.rsb_scope = rsb_scope
        self.wamp_scope = rsb_scope[1:].replace('/', '.') if wamp_scope is None else wamp_scope
        self.converter = None
        self.skipNext = False
        self.rsb_publisher = None
        self.rsb_listener = None
        logger.info("RSB Scope %s" % self.rsb_scope)
        logger.info("WAMP Scope is %s" % self.wamp_scope)
        self.wamp = wamp

        if message_type in PubSubBridge.basic_types:
            self.wamp_callback = self.send_primitive_data
            self.rsb_callback = self.on_primitive_message
            self.rsb_type = PubSubBridge.basic_types[message_type]
        else:
            self.wamp_callback = self.send_rst
            self.rsb_callback = self.on_bytearray_message
            self.rsb_type = str('.' + message_type)

        # RSB_TO_WAMP
        if mode % 2 > 0:
            logger.info('listening on rsb scope %s' % self.rsb_scope)
            self.rsb_listener = rsb.createListener(self.rsb_scope, config=rsb_config)
            self.rsb_listener.addHandler(self.rsb_callback)

        # WAMP_TO_RSB
        if mode > 1:
            logger.info('listening on wamp scope %s' % self.wamp_scope)
            self.wamp_listener = self.wamp.subscribe(self.on_wamp_message, self.wamp_scope)
            self.rsb_publisher = rsb.createInformer(self.rsb_scope, config=rsb_config)
    def test_rpc_protobuf(self):

        def echo(value):
            value.string = "received"
            return value

        def raw_received(session, event):
            msg = '\0' + base64.b64encode(event.data[1]).decode('ascii')
            res = session.call_rpc('/test/rpc', 'echo',  msg, 'rst.generic.Value', 'rst.generic.Value')
            session.scopes['/test/out'].on_wamp_message(res)

        def protobuf_received(passed, lock, event):
            if hasattr(event.data, 'type') and event.data.string == 'received':
                passed()
            lock.release()

        rsb.converter.registerGlobalConverter(
            rsb.converter.ProtocolBufferConverter(messageClass=Value), True)
        self.session.register_scope('/test/scope', 'rst.generic.Value')
        self.session.register_scope('/test/out', 'rst.generic.Value')
        with rsb.createLocalServer('/test/rpc') as server:
            server.addMethod('echo', echo, Value, Value)
            with rsb.createListener('/test/scope', config=self.session.rsb_conf) as listener:
                listener.addHandler(partial(raw_received, self.session))
                with rsb.createListener('/test/out') as out:
                    out.addHandler(partial(protobuf_received, self.passed, self.lock))
                    with rsb.createInformer('/test/scope', dataType=Value) as informer:
                        v = Value()
                        v.type = Value.STRING
                        v.string = "hello"
                        informer.publishData(v)
                        self.lock.acquire()
        self.assertTrue(self.passed.called)
Beispiel #4
0
	def _get_informer(self, iu_category):
		'''Return (or create, store and return) an informer object for IUs of the specified category.'''
		if iu_category in self._informer_store:
			LOGGER.info("Returning informer on scope "+"/ipaaca/channel/"+str(self._channel)+"/category/"+str(iu_category))
			return self._informer_store[iu_category]
		informer_iu = rsb.createInformer(
				rsb.Scope("/ipaaca/channel/"+str(self._channel)+"/category/"+str(iu_category)),
				config=self._participant_config,
				dataType=object)
		self._informer_store[iu_category] = informer_iu #new_tuple
		LOGGER.info("Returning NEW informer on scope "+"/ipaaca/channel/"+str(self._channel)+"/category/"+str(iu_category))
		return informer_iu #return new_tuple
Beispiel #5
0
 def setUp(self):
     states = [
         'A', 'B', {
             'name': 'C',
             'children':
             ['1', '2', {
                 'name': '3',
                 'children': ['a', 'b', 'c']
             }]
         }, 'D', 'E', 'F'
     ]
     self.stuff = Stuff(states, machine_cls=Machine)
     self.stuff.heavy_processing = heavy_processing
     self.stuff.machine.add_transition('process',
                                       '*',
                                       'B',
                                       before='heavy_processing')
     self.stuff.informer = rsb.createInformer(self.TEST_SCOPE, dataType=int)
     converter = rsb.converter.ProtocolBufferConverter(messageClass=Value)
     rsb.converter.registerGlobalConverter(converter, True)
     self.stuff.informer_rst = rsb.createInformer(self.TEST_SCOPE,
                                                  dataType=Value)
Beispiel #6
0
    def testUserRoundtrip(self):
        scope = Scope("/test/it")
        inConnector = self._getInPushConnector(scope, activate=False)
        outConnector = self._getOutConnector(scope, activate=False)

        outConfigurator = rsb.eventprocessing.OutRouteConfigurator(
            connectors=[outConnector])
        inConfigurator = rsb.eventprocessing.InPushRouteConfigurator(
            connectors=[inConnector])

        publisher = createInformer(scope,
                                   dataType=str,
                                   configurator=outConfigurator)
        listener = createListener(scope, configurator=inConfigurator)

        receiver = SettingReceiver(scope)
        listener.addHandler(receiver)

        data1 = "a string to test"
        sentEvent = Event(EventId(uuid.uuid4(), 0))
        sentEvent.setData(data1)
        sentEvent.setType(str)
        sentEvent.setScope(scope)
        sentEvent.getMetaData().setUserInfo("test", "it")
        sentEvent.getMetaData().setUserInfo("test again", "it works?")
        sentEvent.getMetaData().setUserTime("blubb", 234234)
        sentEvent.getMetaData().setUserTime("bla", 3434343.45)
        sentEvent.addCause(EventId(uuid.uuid4(), 1323))
        sentEvent.addCause(EventId(uuid.uuid4(), 42))

        publisher.publishEvent(sentEvent)

        with receiver.resultCondition:
            while receiver.resultEvent is None:
                receiver.resultCondition.wait(10)
            if receiver.resultEvent is None:
                self.fail("Listener did not receive an event")
            self.assertTrue(
                receiver.resultEvent.metaData.createTime <= receiver.
                resultEvent.metaData.sendTime <= receiver.resultEvent.metaData.
                receiveTime <= receiver.resultEvent.metaData.deliverTime)
            sentEvent.metaData.receiveTime = \
                receiver.resultEvent.metaData.receiveTime
            sentEvent.metaData.deliverTime = \
                receiver.resultEvent.metaData.deliverTime
            self.assertEqual(sentEvent, receiver.resultEvent)

        listener.deactivate()
        publisher.deactivate()
Beispiel #7
0
    def __init__(self):
        self.__logger = getLoggerByClass(self.__class__)

        self.__participants = []

        self.__process = ProcessInfo()
        self.__host = HostInfo()

        self.__informer = rsb.createInformer(PARTICIPANTS_SCOPE)
        self.__listener = rsb.createListener(PARTICIPANTS_SCOPE)

        def handle(event):
            # TODO use filter when we get conjunction filter
            if event.method not in ['REQUEST', 'SURVEY']:
                return

            participantId = None
            participant = None
            if len(event.scope.components) > \
                    len(PARTICIPANTS_SCOPE.components):
                try:
                    participantId = uuid.UUID(event.scope.components[-1])
                    if participantId is not None:
                        participant = next((p for p in self.__participants
                                            if p.id == participantId),
                                           None)
                except Exception, e:
                    self.__logger.warn('Query event %s does not '
                                       'properly address a participant: %s',
                                       event, e)

            def process(thunk):
                if participant is not None and event.method == 'REQUEST':
                    thunk(query=event, participant=participant)
                elif participant is None and event.method == 'SURVEY':
                    for p in self.__participants:
                        thunk(query=event, participant=p)
                else:
                    self.__logger.warn('Query event %s not understood', event)

            if event.data is None:
                process(self.sendHello)
            elif event.data == 'ping':
                process(self.sendPong)
            else:
                self.__logger.warn('Query event %s not understood', event)
Beispiel #8
0
    def testHierarchySending(self):

        sendScope = Scope("/this/is/a/test")
        superScopes = sendScope.superScopes(True)

        outConnector = self._getOutConnector(sendScope, activate=False)
        outConfigurator = rsb.eventprocessing.OutRouteConfigurator(
            connectors=[outConnector])
        informer = createInformer(sendScope,
                                  dataType=str,
                                  configurator=outConfigurator)

        # set up listeners on the complete hierarchy
        listeners = []
        receivers = []
        for scope in superScopes:

            inConnector = self._getInPushConnector(scope, activate=False)
            inConfigurator = rsb.eventprocessing.InPushRouteConfigurator(
                connectors=[inConnector])

            listener = createListener(scope, configurator=inConfigurator)
            listeners.append(listener)

            receiver = SettingReceiver(scope)

            listener.addHandler(receiver)

            receivers.append(receiver)

        data = "a string to test"
        informer.publishData(data)

        for receiver in receivers:
            with receiver.resultCondition:
                while receiver.resultEvent is None:
                    receiver.resultCondition.wait(10)
                if receiver.resultEvent is None:
                    self.fail("Listener on scope %s did not receive an event" %
                              receiver.scope)
                self.assertEqual(receiver.resultEvent.data, data)

        for listener in listeners:
            listener.deactivate()
        informer.deactivate()
def main():
	converter = ProtocolBufferConverter(messageClass=JointAngles)
	rsb.converter.registerGlobalConverter(converter)

	rsb.setDefaultParticipantConfig(rsb.ParticipantConfig.fromDefaultSources())

	# print("Registered converter %s" % converter)
	# print("Registered converters:\n%s "
	#      % rsb.converter.getGlobalConverterMap(bytearray))

	with rsb.createInformer("/my/input", dataType=JointAngles) as informer:
		# Send and event using a method that directly accepts data.
		message = JointAngles()
		message.angles.extend([0.707]*29)

		informer.publishData(message)

		print "Message sent: " + str(message)
def main():
    converter = ProtocolBufferConverter(messageClass=JointAngles)
    rsb.converter.registerGlobalConverter(converter)

    rsb.setDefaultParticipantConfig(rsb.ParticipantConfig.fromDefaultSources())

    # print("Registered converter %s" % converter)
    # print("Registered converters:\n%s "
    #      % rsb.converter.getGlobalConverterMap(bytearray))

    with rsb.createInformer("/my/input", dataType=JointAngles) as informer:
        # Send and event using a method that directly accepts data.
        message = JointAngles()
        message.angles.extend([0.707] * 29)

        informer.publishData(message)

        print "Message sent: " + str(message)
    def test_send_protobuf(self):
        def protobuf_received(passed, lock, event):
            if hasattr(event.data, 'type'):
                passed()
            lock.release()

        rsb.converter.registerGlobalConverter(
            rsb.converter.ProtocolBufferConverter(messageClass=Value), True)
        self.session.register_scope('/test/scope', 'rst.generic.Value')
        with rsb.createListener('/test/scope') as listener:
            listener.addHandler(partial(protobuf_received, self.passed, self.lock))
            with rsb.createInformer('/test/scope', dataType=Value) as informer:
                v = Value()
                v.type = Value.STRING
                v.string = "hello"
                informer.publishData(v)
            self.lock.acquire()
        self.assertTrue(self.passed.called)
Beispiel #12
0
    def testUserPullRoundtrip(self):
        scope = Scope("/test/it/pull")
        try:
            inConnector = self._getInPullConnector(scope, activate=False)
        except NotImplementedError:
            return
        outConnector = self._getOutConnector(scope, activate=False)

        outConfigurator = rsb.eventprocessing.OutRouteConfigurator(
            connectors=[outConnector])
        inConfigurator = rsb.eventprocessing.InPullRouteConfigurator(
            connectors=[inConnector])

        publisher = createInformer(scope,
                                   dataType=str,
                                   configurator=outConfigurator)
        reader = createReader(scope, configurator=inConfigurator)

        data1 = "a string to test"
        sentEvent = Event(EventId(uuid.uuid4(), 0))
        sentEvent.setData(data1)
        sentEvent.setType(str)
        sentEvent.setScope(scope)
        sentEvent.getMetaData().setUserInfo("test", "it")
        sentEvent.getMetaData().setUserInfo("test again", "it works?")
        sentEvent.getMetaData().setUserTime("blubb", 234234)
        sentEvent.getMetaData().setUserTime("bla", 3434343.45)
        sentEvent.addCause(EventId(uuid.uuid4(), 1323))
        sentEvent.addCause(EventId(uuid.uuid4(), 42))

        publisher.publishEvent(sentEvent)

        resultEvent = reader.read(True)
        self.assertTrue(resultEvent.metaData.createTime <= resultEvent.
                        metaData.sendTime <= resultEvent.metaData.receiveTime
                        <= resultEvent.metaData.deliverTime)
        sentEvent.metaData.receiveTime = resultEvent.metaData.receiveTime
        sentEvent.metaData.deliverTime = resultEvent.metaData.deliverTime
        self.assertEqual(sentEvent, resultEvent)

        reader.deactivate()
        publisher.deactivate()
Beispiel #13
0
    def testInformerListenerRoundtrip(self):

        with rsb.createInformer(self.scope, dataType=str) as informer, \
             rsb.createListener(self.scope) as listener:

            def setReceived(event):
                with self.receivedCondition:
                    self.receivedData = event.data
                    self.receivedCondition.notifyAll()

            listener.addHandler(setReceived)
            data = 'our little test'
            informer.publishData(data)
            start = time.time()
            with self.receivedCondition:
                while self.receivedData is None:
                    self.receivedCondition.wait(1)
                    if time.time() > start + 10:
                        break
                self.assertEqual(data, self.receivedData)
Beispiel #14
0
 def __init__(self):
     self.informer = rsb.createInformer(str(sys.argv[1]), dataType=cv2.cv.iplimage)
Beispiel #15
0
import rsb
import rsb.converter

# See ./registration.py.
import sys
sys.path.append('.')
from SimpleImage_pb2 import SimpleImage

if __name__ == '__main__':
    # Pacify logger.
    logging.basicConfig()

    # See ./registration.py.
    converter = rsb.converter.ProtocolBufferConverter(messageClass=SimpleImage)
    rsb.converter.registerGlobalConverter(converter)

    rsb.setDefaultParticipantConfig(rsb.ParticipantConfig.fromDefaultSources())

    # Create an informer that will send the events carrying protocol
    # buffer payloads. See the informer.py example for a more detailed
    # explanation of informer creation.
    with rsb.createInformer("/example/converter",
                            dataType=SimpleImage) as informer:

        image = SimpleImage()
        image.width = 100
        image.height = 100
        image.data = str('bla')
        informer.publishData(image)
# mark-end::body
Beispiel #16
0
def updateRobotInfo():
    global robotname
    # print 'Number of arguments:', len(sys.argv), 'arguments.'
    # print 'Argument List:', str(sys.argv)
    if len(sys.argv) == 2:
        robotname = str(sys.argv[1])
        print "set robotname to " + robotname

    print "init updater"
    rospy.init_node('updateRobotInfos', anonymous=True)
    print "ros connection established"
    rsb_informer = rsb.createInformer("/tobi", dataType=str)
    rate = rospy.Rate(1)

    def checkForNavGoal():
        headers = {'Content-type': 'application/json'}
        r = requests.get(serverurl + robotname + "/setlocation",
                         headers=headers)
        # pos = r.json().split(',')
        # x = pos[0]
        # y = pos[1]
        # theta = pos[2]
        if r.json() == 'called':
            print "navgoal detected"
            headers = {'Content-type': 'application/json'}
            payload = 'none'
            r = requests.put(serverurl + robotname + "/setlocation",
                             headers=headers,
                             data=json.dumps(payload))
            # robot_call = "komm"
            # pub_called.publish(robot_call)
            # Create an informer for strings on scope "/example/informer".
            rsb_informer.publishData("")

    def positionCB(data):
        global current_location
        x = data.pose.pose.position.x
        y = data.pose.pose.position.y

        print "callback: " + str(x) + ", " + str(y)

        # get location from Position  (e.g "kitchen")

        if (pointInPoly((x, y), kitchen)):
            location = "er ist in der kche"
        elif (pointInPoly((x, y), livingroom)):
            location = "er ist im wohnzimmer"
        elif (pointInPoly((x, y), bedroom)):
            location = "er ist im schlafzimmer"
        elif (pointInPoly((x, y), diningroom)):
            location = "er ist im esszimmer"
        else:
            location = "er ist ausserhalb der arena"
        if current_location != location:
            print location
            current_location = location
            headers = {'Content-type': 'application/json'}
            payload = location
            r = requests.put(serverurl + robotname + "/location",
                             headers=headers,
                             data=json.dumps(payload))
            print r.json()

    def personsCB(data):
        global last_people_update
        global current_number_of_people
        last_people_update = time.time()
        numberOfPeople = str(len(data.people))
        # get number of persons from Persons (e.g. "2")
        # send curl -i -H 'Content-Type: application/json' -X PUT -d '"2"' http://localhost:5000/pepper/persons
        if numberOfPeople != current_number_of_people:
            current_number_of_people = numberOfPeople
            headers = {'Content-type': 'application/json'}
            payload = numberOfPeople
            r = requests.put(serverurl + robotname + "/numberOfPersons",
                             headers=headers,
                             data=json.dumps(payload))
            print r.json()

    position_sub = rospy.Subscriber('/amcl_pose', PoseWithCovarianceStamped,
                                    positionCB)
    person_sub = rospy.Subscriber('/people_tracker/people', People, personsCB)

    resetPeople()

    while not rospy.is_shutdown():
        rate.sleep()
        checkForNavGoal()
        if time.time() - last_people_update > 1:
            resetPeople()
Beispiel #17
0
 def testInformer(self):
     participant = None
     with rsb.createInformer('/') as informer:
         participant = informer
         self.assertEqual(self.creationCalls, [(participant, None)])
     self.assertEqual(self.destructionCalls, [participant])
Beispiel #18
0
 def testCreateInformer(self):
     self.assert_(rsb.createInformer("/"))
Beispiel #19
0
 def __init__(self):
     self._current = None
     self._mode = 'detect'
     self.rsb_informer = rsb.createInformer(rsb_face_scope)
     self.rsb_listener = rsb.createListener(rsb_face_mode)
     self.rsb_listener.addHandler(self.on_mode_change)
Beispiel #20
0
 def makeInformer(self):
     return rsb.createInformer(self.scope,
                               self.config,
                               parent=self,
                               dataType=self.requestType)
Beispiel #21
0
    def __init__(self):
        Gtk.Window.__init__(self, title="Robot GUI Quick Hack")
        self.set_border_width(3)

        self.informer = rsb.createInformer("/coman/left_arm/JointPositionCtrl", dataType=JointAngles)

        # TODO get home / safe posture
        self.commanded = [0] * 7;

        pane = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        pane.set_border_width(10)

        self.notebook = Gtk.Notebook()
        pane.add(self.notebook)

        button = Gtk.Button(label="Apply")
        button.connect("clicked", self.button_clicked)
        pane.add(button)

        self.add(pane)

        robot = {}

        robot['Torso'] = {}
        robot['Torso']['WaistLat'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Torso']['WaistSag'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Torso']['WaistYaw'] = JointInfo(0, 0, -1.57, 1.57)

        # LArm
        robot['Left Arm'] = {}
        robot['Left Arm']['LShSag'] = JointInfo(0, 0, -3.40, 1.65)
        robot['Left Arm']['LShLat'] = JointInfo(0, 0, -0.3, 2)
        robot['Left Arm']['LShYaw'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Left Arm']['LElbj'] = JointInfo(0, 0, -2.3, 0)
        robot['Left Arm']['LForearmPlate'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Left Arm']['LWrj1'] = JointInfo(0, 0, -0.5, 0.5)
        robot['Left Arm']['LWrj2'] = JointInfo(0, 0, -0.78, 1.39)

        for chain, joints in robot.iteritems():
            page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            page.set_border_width(10)
            for name, info in joints.iteritems():
                hbox = Gtk.Box(spacing=6)
                label = Gtk.Label(name)
                label.set_size_request(100, 30)
                hbox.add(label)

                # two adjustments (initial value, min value, max value,
                # step increment - press cursor keys to see!,
                # page increment - click around the handle to see!,
                # page size - not used here)
                ad1 = Gtk.Adjustment(info.initial, info.min, info.max, 0.1, 1, 0)

                # an horizontal scale
                h_scale = Gtk.Scale(
                    orientation=Gtk.Orientation.HORIZONTAL, adjustment=ad1)
                # of integers (no digits)
                h_scale.set_digits(1)
                # that can expand horizontally if there is space in the grid (see
                # below)
                h_scale.set_hexpand(True)
                # that is aligned at the top of the space allowed in the grid (see
                # below)
                h_scale.set_valign(Gtk.Align.START)
                h_scale.set_size_request(280, 30)
                # hbox.pack_start(h_scale, False, False, 0)
                hbox.add(h_scale)
                h_scale.connect("value-changed", self.scale_moved, h_scale, name)

                # adjustment = Gtk.Adjustment(0, 0, 100, 1, 10, 0)
                # spinbutton = Gtk.SpinButton()
                # spinbutton.set_adjustment(adjustment)
                # hbox.pack_start(spinbutton, False, False, 0)

                # check_numeric = Gtk.CheckButton("Numeric")
                # check_numeric.connect("toggled", self.on_numeric_toggled)
                # hbox.pack_start(check_numeric, False, False, 0)

                # check_ifvalid = Gtk.CheckButton("If Valid")
                # #check_ifvalid.connect("toggled", self.on_ifvalid_toggled)
                # hbox.pack_start(check_ifvalid, False, False, 0)

                page.add(hbox)

            self.notebook.append_page(page, Gtk.Label(chain))
Beispiel #22
0
# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
# express or implied. See the LGPL for the specific language
# governing rights and limitations.
#
# You should have received a copy of the LGPL along with this
# program. If not, go to http://www.gnu.org/licenses/lgpl.html
# or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# The development of this software was supported by:
#   CoR-Lab, Research Institute for Cognition and Robotics
#     Bielefeld University
#
# ============================================================

# mark-start::body
import logging

import rsb

if __name__ == '__main__':
    # Pacify logger.
    logging.basicConfig()

    # Create an informer for strings on scope "/example/informer".
    with rsb.createInformer("/example/informer", dataType=str) as informer:

        # Send and event using a method that directly accepts data.
        informer.publishData("example payload")
# mark-end::body
Beispiel #23
0
    def __init__(self):
        Gtk.Window.__init__(self, title="Robot GUI Quick Hack")
        self.set_border_width(3)

        self.informer = rsb.createInformer("/coman/left_arm/JointPositionCtrl",
                                           dataType=JointAngles)

        # TODO get home / safe posture
        self.commanded = [0] * 7

        pane = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        pane.set_border_width(10)

        self.notebook = Gtk.Notebook()
        pane.add(self.notebook)

        button = Gtk.Button(label="Apply")
        button.connect("clicked", self.button_clicked)
        pane.add(button)

        self.add(pane)

        robot = {}

        robot['Torso'] = {}
        robot['Torso']['WaistLat'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Torso']['WaistSag'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Torso']['WaistYaw'] = JointInfo(0, 0, -1.57, 1.57)

        # LArm
        robot['Left Arm'] = {}
        robot['Left Arm']['LShSag'] = JointInfo(0, 0, -3.40, 1.65)
        robot['Left Arm']['LShLat'] = JointInfo(0, 0, -0.3, 2)
        robot['Left Arm']['LShYaw'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Left Arm']['LElbj'] = JointInfo(0, 0, -2.3, 0)
        robot['Left Arm']['LForearmPlate'] = JointInfo(0, 0, -1.57, 1.57)
        robot['Left Arm']['LWrj1'] = JointInfo(0, 0, -0.5, 0.5)
        robot['Left Arm']['LWrj2'] = JointInfo(0, 0, -0.78, 1.39)

        for chain, joints in robot.iteritems():
            page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            page.set_border_width(10)
            for name, info in joints.iteritems():
                hbox = Gtk.Box(spacing=6)
                label = Gtk.Label(name)
                label.set_size_request(100, 30)
                hbox.add(label)

                # two adjustments (initial value, min value, max value,
                # step increment - press cursor keys to see!,
                # page increment - click around the handle to see!,
                # page size - not used here)
                ad1 = Gtk.Adjustment(info.initial, info.min, info.max, 0.1, 1,
                                     0)

                # an horizontal scale
                h_scale = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL,
                                    adjustment=ad1)
                # of integers (no digits)
                h_scale.set_digits(1)
                # that can expand horizontally if there is space in the grid (see
                # below)
                h_scale.set_hexpand(True)
                # that is aligned at the top of the space allowed in the grid (see
                # below)
                h_scale.set_valign(Gtk.Align.START)
                h_scale.set_size_request(280, 30)
                # hbox.pack_start(h_scale, False, False, 0)
                hbox.add(h_scale)
                h_scale.connect("value-changed", self.scale_moved, h_scale,
                                name)

                # adjustment = Gtk.Adjustment(0, 0, 100, 1, 10, 0)
                # spinbutton = Gtk.SpinButton()
                # spinbutton.set_adjustment(adjustment)
                # hbox.pack_start(spinbutton, False, False, 0)

                # check_numeric = Gtk.CheckButton("Numeric")
                # check_numeric.connect("toggled", self.on_numeric_toggled)
                # hbox.pack_start(check_numeric, False, False, 0)

                # check_ifvalid = Gtk.CheckButton("If Valid")
                # #check_ifvalid.connect("toggled", self.on_ifvalid_toggled)
                # hbox.pack_start(check_ifvalid, False, False, 0)

                page.add(hbox)

            self.notebook.append_page(page, Gtk.Label(chain))
Beispiel #24
0
        print str(e)

    return headobj


def publish(rstdata):
    informer.publishData(rstdata)


def callback(data):
    rospy.loginfo(rospy.get_caller_id() + ' Received %s', data)
    rstdata = convert(data)
    publish(rstdata)


def ros_listen():
    rospy.init_node('poselistener', anonymous=True)
    rospy.Subscriber('/some/topic', String, callback)
    rospy.spin()


if __name__ == '__main__':

    logging.basicConfig()

    rsb.converter.registerGlobalConverter(
        rsb.converter.ProtocolBufferConverter(messageClass=HeadObject))
    with rsb.createInformer("/pepper/headpose",
                            dataType=HeadObject) as informer:
        ros_listen()
            pass

        self.listener = rsb.createListener(inscope)
        self.lastImage = Queue(1)

        self.restart_listener = rsb.createListener(self.notification_scope)
        self.last_restart_request = Queue(1)

        try:
            rsb.converter.registerGlobalConverter(rsb.converter.ProtocolBufferConverter(messageClass=HeadObjects))
        except Exception, e:
            # If they are already loaded, the lib throws an exception ...
            # print ">> [Error] While loading RST converter: ", e
            pass

        self.person_publisher = rsb.createInformer(outscope, dataType=HeadObjects)

        # This must be set at last!
        rsb.setDefaultParticipantConfig(rsb.ParticipantConfig.fromDefaultSources())

    def add_last_image(self, image_event):
        try:
            self.lastImage.get(False)
        except Exception, e:
            pass
        self.lastImage.put((np.asarray(image_event.data[:, :]), image_event.getId()), False)

    def add_restart_request(self, restart_event):
        try:
            self.last_restart_request.get(False)
        except Exception, e:
 def __init__(self):
     self.informer = rsb.createInformer(str(sys.argv[1]), dataType=np.ndarray)
        self.listener = rsb.createListener(inscope)
        self.lastImage = Queue(1)

        self.restart_listener = rsb.createListener(self.notification_scope)
        self.last_restart_request = Queue(1)

        try:
            rsb.converter.registerGlobalConverter(
                rsb.converter.ProtocolBufferConverter(
                    messageClass=HeadObjects))
        except Exception, e:
            # If they are already loaded, the lib throws an exception ...
            # print ">> [Error] While loading RST converter: ", e
            pass

        self.person_publisher = rsb.createInformer(outscope,
                                                   dataType=HeadObjects)

        # This must be set at last!
        rsb.setDefaultParticipantConfig(
            rsb.ParticipantConfig.fromDefaultSources())

    def add_last_image(self, image_event):
        try:
            self.lastImage.get(False)
        except Exception, e:
            pass
        self.lastImage.put(
            (np.asarray(image_event.data[:, :]), image_event.getId()), False)

    def add_restart_request(self, restart_event):
        try:
Beispiel #28
0
 def mode(self, value):
     self._mode = value
     with rsb.createInformer(rsb_face_mode) as informer:
         informer.publishData(value)
Beispiel #29
0
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import rsb
import logging
import optparse

if __name__ == '__main__':
    usage = "Usage: %prog [options] <person_label>"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option("-s", "--scope", action="store", type="string", dest="scope",
                      default="/ocvfacerec/trainer/retrainperson",
                      help="Send a Re-Train Command to this Scope")
    (options, args) = parser.parse_args()
    # Pacify logger.
    logging.basicConfig()
    if len(args) < 1:
        print "Warning: You did not provide a person_label - will only retrain and restart the classifier!"
        args.append("")

    with rsb.createInformer(options.scope, dataType=str) as informer:
        print "Publishing name '%s' to scope '%s'" % (str(args[0]), options.scope)
        informer.publishData(str(args[0]))