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)
class Recognizer(object): def __init__(self, model, camera_id, cascade_filename, run_local, inscope="/rsbopencv/ipl", outscope="/ocvfacerec/rsb/people", wait=50, notification="/ocvfacerec/rsb/restart/", show_gui=False): self.model = model self.wait = wait self.notification_scope = notification self.show_gui = show_gui self.detector = CascadedDetector(cascade_fn=cascade_filename, minNeighbors=5, scaleFactor=1.1) if run_local: print ">> Error Run local selected in RSB based Recognizer" sys.exit(1) self.doRun = True self.restart = False def signal_handler(signal, frame): print "\n>> RSB Exiting" self.doRun = False signal.signal(signal.SIGINT, signal_handler) # RSB try: rsb.converter.registerGlobalConverter(IplimageConverter()) except Exception, e: # If they are already loaded, the lib throws an exception ... # print ">> [Error] While loading RST converter: ", e 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
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_rsb(self): mock = MagicMock() with rsb.createListener(self.TEST_SCOPE) as listener: listener.addHandler(mock) self.stuff.informer.publishData(0) time.sleep(0.1) self.assertTrue(mock.called)
def test_rsb(self): mock = MagicMock() with rsb.createListener(self.TEST_SCOPE) as listener: listener.addHandler(mock) self.stuff.informer.publishData(0) time.sleep(0.1) self.assertTrue(mock.called)
def _add_category_listener(self, iu_category): '''Create and store a listener on a specific category.''' if iu_category not in self._listener_store: cat_listener = rsb.createListener(rsb.Scope("/ipaaca/channel/"+str(self._channel)+"/category/"+str(iu_category)), config=self._participant_config) cat_listener.addHandler(self._handle_iu_events) self._listener_store[iu_category] = cat_listener self._category_interests.append(iu_category) LOGGER.info("Added listener in scope /ipaaca/channel/" + str(self._channel) + "/category/" + iu_category)
def run(self): print ">>> [RSB] Initializing ROSBAG REMOTE RECORD of: %s" % self.inscope.strip() rsb_subscriber = rsb.createListener(self.listen_scope) rsb_subscriber.addHandler(self.record_callback) while self.is_running is True: time.sleep(0.05) if self.recordprocess is not None: self.recordprocess.stop() rsb_subscriber.deactivate() print ">>> [RSB] Stopping ROSBAG REMOTE RECORD %s" % self.inscope.strip()
def send_primitive(test, session, data, data_type): def message_received(event): test.assertTrue(event.data, data) test.assertTrue(type(event.data), type(data)) with rsb.createListener('/test/scope') as listener: listener.addHandler(message_received) session.register_scope('/test/scope', data_type) session.scopes['/test/scope'].send_primitive_data(data) time.sleep(0.1)
def makeListener(self): receivingStrategy = None if self._allowParallelExecution: receivingStrategy = FullyParallelEventReceivingStrategy() listener = rsb.createListener(self.scope, self.config, parent=self, receivingStrategy=receivingStrategy) listener.addFilter(rsb.filter.MethodFilter(method='REQUEST')) listener.addHandler(self._handleRequest) return listener
def run(self): print ">>> [RSB] Initializing ROSBAG REMOTE RECORD of: %s" % self.inscope.strip( ) rsb_subscriber = rsb.createListener(self.listen_scope) rsb_subscriber.addHandler(self.record_callback) while self.is_running is True: time.sleep(0.05) if self.recordprocess is not None: self.recordprocess.stop() rsb_subscriber.deactivate() print ">>> [RSB] Stopping ROSBAG REMOTE RECORD %s" % self.inscope.strip( )
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()
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)
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 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)
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)
def run(self): def power_update(event): print("Received event: %s" % event) try: consumption = event.getData().power_consumption_state.consumption print 'new consumption is', consumption, 'W (at time', str(time.time()) + ')' if consumption > self.power_threshold: self.update_light_color(consumption) except Exception as e: print 'received illegal event (' + str(e) + ')' traceback.print_exc() # with rsb.createListener("/home/control/powerconsumptionsensor/") as listener: # print("consumptionscope:", self.consumptionscope, "; plug:", self.plug) # print("combined string:", self.consumptionscope % self.plug) with rsb.createListener(self.location_scope) as listener: listener.addHandler(power_update) while True: time.sleep(1)
def activate(self): if self.scope is not None and self.listener is None: logger.info("activate logger for scope %s" % self.scope) self.listener = rsb.createListener(self.scope) self.listener.addHandler(self._on_msg)
def testListener(self): participant = None with rsb.createListener('/') as listener: participant = listener self.assertEqual(self.creationCalls, [(participant, None)]) self.assertEqual(self.destructionCalls, [participant])
def testCreateListener(self): self.assert_(rsb.createListener("/"))
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 a listener that will receive the events carrying protocol # buffer payloads. See the listener.py example for a more detailed # explanation of listener creation. with rsb.createListener(rsb.Scope("/example/converter")) as listener: def printData(event): print("Received %s object with fields:\n%s" % (type(event.data).__name__, str(event.data))) listener.addHandler(printData) # wait endlessly for received events while True: time.sleep(100)
def activate(self): if self.scope is not None and self.listener is None: logger.info("activate logger for scope %s" % self.scope) self.listener = rsb.createListener(self.scope) self.listener.addHandler(self._on_msg)
def makeListener(self): listener = rsb.createListener(self.scope, self.config, parent=self) listener.addFilter(rsb.filter.MethodFilter(method='REPLY')) listener.addHandler(self._handleReply) return listener
def main(): # Initialisieren aller Pygame-Module und # Fenster erstellen (wir bekommen eine Surface, die den Bildschirm repräsentiert). pygame.init() mouseon = 1 keyson = 0 screenbreite = 800 screenhoehe = 672 screen = pygame.display.set_mode((screenbreite, screenhoehe)) # Titel des Fensters setzen, Mauszeiger nicht verstecken und Tastendrücke wiederholt senden. pygame.display.set_caption("Brawo: Neurofeedback Game") pygame.mouse.set_visible(mouseon) pygame.key.set_repeat(1, 30) # Clock Objekt erstellen, das wir benötigen, um die Framerate zu begrenzen. clock = pygame.time.Clock() # Wir erstellen eine Tilemap. global map map = Tilemap.Tilemap() pygame.mouse.set_pos(128,112) #(screenbreite/3.0,screenhoehe/3.0) logging.basicConfig() ###counter=0 ###sizerandom = 0 ###with rsb.createRemoteServer('/example/serverr') as server: with rsb.createListener("/example/informer") as listener: listener.addHandler(handle) # Die Schleife, und damit unser Spiel, läuft solange running == True. running = True while running: # Framerate auf 30 Frames pro Sekunde beschränken. # Pygame wartet, falls das Programm schneller läuft. clock.tick(30) ###if counter%30 == 29: ### counter = 0 ###print 'server replied to synchronous call: "%s"' % server.echo('bla') ###sizerandom = sizerandom + 1 ###map.changeSize(server.echo(sizerandom)) ###counter = counter+1 #print counter # screen Surface mit Schwarz (RGB = 0, 0, 0) füllen. screen.fill((0, 0, 0)) # Alle aufgelaufenen Events holen und abarbeiten. for event in pygame.event.get(): # Spiel beenden, wenn wir ein QUIT-Event finden. if event.type == pygame.QUIT: running = False # Wir interessieren uns auch für "Taste gedrückt"-Events. if event.type == pygame.KEYDOWN: # Wenn Escape gedrückt wird posten wir ein QUIT-Event in Pygames Event-Warteschlange. if event.key == pygame.K_ESCAPE: pygame.event.post(pygame.event.Event(pygame.QUIT)) # Alle Tastendrücke auch der Tilemap mitteilen. map.handleInput(event.key,keyson) if event.type == MOUSEMOTION and mouseon == 1: # If the mouse moves, move the player where the cursor is. map.handleMouse(event.pos[0],event.pos[1]) map.moveScript() # Die Tilemap auf die screen-Surface rendern. map.render(screen) # Inhalt von screen anzeigen pygame.display.flip()
# # ============================================================ # mark-start::body import time import logging import rsb def handle(event): print("Received event: %s" % event) if __name__ == '__main__': # Pacify logger. logging.basicConfig() # Create a listener on the specified scope. The listener will # dispatch all received events asynchronously to all registered # handlers. with rsb.createListener("/example/informer") as listener: # Add a handler to handle received events. Handlers are callable # objects with the received event as the single argument. listener.addHandler(handle) # Wait for events; clean up when interrupted. while True: time.sleep(1) # mark-end::body
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)