def main_brain_process(robot_name, planner_name, episode_dir, host, web_port, wamp_port): logger.warn('brain process for {}'.format(robot_name)) while True: try: # get robot info robot_info = requests.get('http://{}:{}/robots/{}'.format(host, web_port, robot_name)).json() async def on_brain_join(session, details): brain = Brain(robot_info, planner_name, episode_dir, session) logger.info('brain subscribing to {}'.format(robot_name)) session.subscribe(brain.on_signal, 'gp.robots.{}'.format(robot_name), options=ab_types.SubscribeOptions(match='prefix')), asyncio.get_event_loop().create_task(brain.main_brain_loop()) async def on_brain_leave(session, details): logger.warn('brain disconnecting from {}'.format(robot_name)) # create a wamp component and run forever component = wamp_utils.get_wamp_component(host, wamp_port) component.on_join(on_brain_join) component.on_leave(on_brain_leave) ab_utils.run([component]) except: time.sleep(2) logger.warn('unable to get robot_info for {}. Trying again...'.format(robot_name))
def handle(self, *args, **options): comp = Component( transports="ws://crossbar:8080/ws", realm="realm1", session_factory=GPSComponent, ) run([comp])
def main(options): """Main function.""" auth = build_authentication(options) comp = Component(transports=[{ 'url': args.url, 'max_retries': -1, 'max_retry_delay': 30, }], realm=args.realm, authentication=auth, extra={ 'market_maker_adr': os.environ.get( 'XBR_MARKET_MAKER_ADR', '0x3e5e9111ae8eb78fe1cc3bb8915d5d461f3ef9a9'), 'seller_privkey': options.privkey, }) if options.privkey is None: pub = WampPublisher() else: pub = SellingPublisher(options.name) factory = VehicleFleetFactory() sim_type = factory.create_simulation(options.type) _ = sim_type(comp, pub, options.sumo_cfg, options.name) run([comp])
def handle(self, *args, **options): url = settings.CROSSBAR_URL realm = settings.CROSSBAR_REALM comp = Component( transports=url, realm=realm, session_factory=RemoteInterface, ) run([comp])
def worker(robot_signal): # now create a wamp connection and run the signal (sensor/control) wamp_component = self._get_wamp_component() wamp_component.on_join(robot_signal.on_join) wamp_component.on_leave(robot_signal.on_leave) # first register to handle SIGINT so we can shutdown cleanly def on_shutdown(sig, frame): # this calls on_leave, which calls sensor.cleanup() wamp_component.stop() signal.signal(signal.SIGUSR1, on_shutdown) autobahn_utils.run([wamp_component])
def start_with_asyncio(self): wamp_component = self._get_wamp_component() # callback controls for control in self.controls: wamp_component.on_join(control.on_join) wamp_component.on_leave(control.on_leave) # callback sensors for sensor in self.sensors: wamp_component.on_join(sensor.on_join) wamp_component.on_leave(sensor.on_leave) autobahn_utils.run([wamp_component])
def run_test_peer(component, test_name): print('running test peer:', test_name) # pylint: disable=unused-variable @component.on_join async def joined(session, details): print('test component joined:', test_name, session, details) if test_name == 'publishOneMessage': await publish_one_message_on_joined(session, details) else: print('test failed: unknown test name') run([component])
def subscribe_and_run_forever(host, wamp_port, callback, channel, match='prefix'): # create wamp component wamp_component = get_wamp_component(host, wamp_port) async def on_join(session, details): logger.info('wamp component: joining') session.subscribe(callback, channel, options=ab_types.SubscribeOptions(match='prefix')) async def on_leave(session, details): logger.info('wamp component: leaving') # subscribe an episode writer wamp_component.on_join(on_join) wamp_component.on_leave(on_leave) # run component ab_utils.run([wamp_component])
def stream(self, dsn, market_patterns): log.info('stream: About to configure websocket component') websocket = component.Component(realm='realm1', transports=[{ 'url': self.handler.ws_url, 'options': { 'fail_by_drop': True, 'open_handshake_timeout': 2500, 'close_handshake_timeout': 1000, 'auto_ping_interval': 10000, 'auto_ping_timeout': 5000, } }]) @websocket.on_connect async def connect(session, details): log.info(f'connect: {details}') @websocket.on_ready async def ready(session, details): log.info(f'ready: {details}') @websocket.on_join async def join(session, details): log.info(f'join: {details}') options = SubscribeOptions(details=True, match='prefix') async with self.handler(dsn) as handler: for pattern in market_patterns: await session.subscribe(handler=handler, options=options, topic=pattern) @websocket.on_leave async def leave(session, details): log.info(f'leave: {details}') @websocket.on_disconnect async def disconnect(session, details): log.info(f'disconnect: {details}') log.info(f'Connecting to {self.__class__.__name__} websocket API') component.run([websocket])
def run(self): print("Running...") run(self.components) print("Bye.")
print("Successfully paired with server\n") print("Public key: {}".format(public_key_hex)) print("Private key: {}\n".format(private_key_hex)) if os.path.exists(KEYS_FILE): Path(KEYS_FILE).unlink() with open(KEYS_FILE, 'w+') as file: file.write("{}\n".format(public_key_hex)) file.write("{}".format(private_key_hex)) print("Keys are save in {}".format(KEYS_FILE)) else: print("Invalid OTP") session.leave() if __name__ == '__main__': parser = argparse.ArgumentParser("DeskConnD pairing") parser.add_argument("otp", type=int) args = parser.parse_args() key = PrivateKey.generate() signing_key = SigningKey.from_key_bytes(key.encode()) public_key_hex = signing_key.public_key() private_key_hex = key.encode(HexEncoder).decode('ascii') auth = AuthAnonymous(authrole='anonymous') component = Component(transports="ws://localhost:5020/ws", realm="deskconn", authentication={"anonymous": auth}) main() run(component, log_level='warn')
"options": { "open_handshake_timeout": 100, } }, ], realm=u"crossbardemo", ) @component.on_join def join(session, details): print("joined {}".format(details)) @component.register( u"example.foo", options=RegisterOptions(details_arg='details'), ) @asyncio.coroutine def foo(*args, **kw): print("foo({}, {})".format(args, kw)) for x in range(5, 0, -1): print(" returning in {}".format(x)) yield from asyncio.sleep(1) print("returning '42'") return 42 if __name__ == "__main__": run([component])
# Not sure why we need this but the first published result never gets picked # up by the subscriber. session.publish("speedtest") while True: s = Speedtest() logger.info("Starting speedtest...") loop = asyncio.get_event_loop() await loop.run_in_executor(None, s.get_best_server) await loop.run_in_executor(None, s.download) result = { key: s.results.dict()[key] for key in ["download", "timestamp"] } logger.info( f"Speedtest completed: {result['download'] / 10 ** 6:.2f} Mbps") session.publish("speedtest", result) await asyncio.sleep(60) @monitor.on_join async def get_cpu_temp(session, details): while True: result = psutil.cpu_percent() logger.info(f"cpu percent: {result}") session.publish("cpu_percent", result) await asyncio.sleep(10) if __name__ == "__main__": run([monitor])
def main(): RouterProxy(remote_comp, local_comp) run([local_comp, remote_comp])
from autobahn.asyncio.component import Component, run from autobahn.wamp.protocol import ApplicationSession from tortoise import Tortoise from serializers import ProfileSerializer component = Component(transports="ws://*****:*****@component.register("io.crossbar.register") async def register_user(name: str, age: str, height: str): serializer = ProfileSerializer() return await serializer.create(name=name, age=age, height=height) @component.on_join async def joined(session: ApplicationSession, _details): await init_db() session.log.info("ready to rock") if __name__ == '__main__': run(component)
def run_main(): run([component], log_level=None) component.start()
class Backend(ApplicationSession): def __init__(self, config=None): config.realm = "realm1" super().__init__(config) async def onJoin(self, details): print('Register test_echo_payload') await self.register(self.test_echo_payload, 'test.echo.payload') async def onDisconnect(self): loop = asyncio.get_event_loop() loop.stop() async def test_echo_payload(self, value: bytes) -> bytes: if not isinstance(value, bytes): print('Value is not an instance of bytes but is a %s' % (type(value))) return value if __name__ == '__main__': backend = Component(session_factory=Backend, transports=[{ 'type': 'websocket', 'serializers': ['msgpack'], 'url': 'ws://localhost:8080/ws', 'max_retries': 3 }]) run([backend])
wamp_session.publish(u'location_info', location_info) wamp_session.publish(u'temperature', temperature) else: print("WAMP session not existent") reset_timers() # Fall intensity elif (fields['data'][0] == 0x7b): max_accel = struct.unpack("<f", bytearray(fields['data'][1:5])) print(max_accel) if wamp_session != None: wamp_session.publish(u'fall_alert', True) wamp_session.publish(u"fall_intensity", max_accel) else: print("WAMP session not existent") def on_connect(client, userdata, flag, rc): print("MQTT connected") client.subscribe(path) if __name__ == "__main__": mqtt_thread = threading.Thread(target=mqtt_runner, args=(1, )) mqtt_thread.start() run([wamp_component])
async def onJoin(self, details): print('Call test_echo_payload') loop = asyncio.get_running_loop() loop.create_task(self.test_echo_payload()) async def onDisconnect(self): loop = asyncio.get_event_loop() loop.stop() async def test_echo_payload(self): message_bytes = b'\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10' ret = await self.call('test.echo.payload', message_bytes) print("Received response:", ret) if __name__ == '__main__': client = Component( session_factory = Client, transports = [ { 'type': 'websocket', 'serializers': ['msgpack'], 'url': 'ws://localhost:8080/ws', 'max_retries': 3 } ] ) run([client])
def run(cls): print(f"Starting {cls.__name__}...") run([component])
res = yield from session.register( lambda: None, u"prefix.fail.", options=RegisterOptions(match=u'prefix'), ) print("\n\nshould have failed\n\n") except ApplicationError as e: print("prefix-match 'prefix.fail.' failed as expected: {}".format( e.error)) print("calling 'example.foo'") res = yield from session.call(u"example.foo") print("example.foo() = {}".format(res)) print("done") component = Component(transports=u"ws://localhost:8080/auth_ws", main=main, realm=u"crossbardemo", authentication={ u"wampcra": { u"authid": u"bob", u"authrole": "dynamic_authed", u"secret": u"p4ssw0rd", } }) if __name__ == "__main__": run([component])
from autobahn.asyncio.component import Component, run from .controller import Controller COMPONENT = Component(transports="ws://localhost:8081/ws", realm="realm1") CONTROLLER = Controller(COMPONENT) run([COMPONENT])