def onJoin(self, details): def handler1(msg, details=None): print("handler1: msg = '{0}', details = '{1}'".format( msg, details)) yield self.subscribe(handler1, "com.example.topic1", options=SubscribeOptions(details_arg="details")) def handler2(msg, details=None): print("handler2: msg = '{0}', details = '{1}'".format( msg, details)) yield self.subscribe(handler2, "com.example", options=SubscribeOptions(match="prefix", details_arg="details")) def handler3(msg, details=None): print("handler3: msg = '{0}', details = '{1}'".format( msg, details)) yield self.subscribe(handler3, "com..topic1", options=SubscribeOptions(match="wildcard", details_arg="details")) print("MyComponent: all event handlers subscribed!")
def onJoin(self, _): if not self.dvr.started: self.dvr.start() self.dvr.log.info("DVR session ready") yield self.subscribe(self.dvr.handle_service_message, RPC.STATE_PUBLISH.format(''), options=SubscribeOptions(match='prefix', details_arg='details')) yield self.subscribe(self.dvr.handle_analysis_message, 'livetiming.analysis', options=SubscribeOptions(match='prefix', details_arg='details')) yield self.subscribe(self.dvr.handle_control_message, Channel.CONTROL) yield self.subscribe(self.dvr.handle_control_message, Channel.DIRECTORY)
def onJoin(self, details): log.info("Successfully connected and authenticated on server") registrations = yield self.call("wamp.registration.list") for reg_type in registrations: for reg_id in registrations[reg_type]: try: reg = yield self.call("wamp.registration.get", reg_id) except Exception as e: log.exception(e) self.leave() if self.matches_pattern(reg['uri']): self.start_track(reg_id, reg['uri']) try: yield self.subscribe(self.on_create, 'wamp.registration.on_create') yield self.subscribe(self.on_delete, 'wamp.registration.on_delete') except Exception as e: log.exception(e) self.leave() # Subscribe to all events yield self.subscribe( self.sub_to_call, topic='ch.rentouch.piplanning', options=SubscribeOptions(match=u"prefix", details_arg='wamp_details')) number_of_procedures = len(self.subscriptions) log.debug(f"Subscribed to {number_of_procedures} wamp procedures") if number_of_procedures < 2: log.error("Was not able to track at least 2 WAMP procedures -> exit!") reactor.stop()
def subscribe(self, session): remote_uri = 'crossbarfabriccenter.node..worker..realm..root.' remote_uri_regex = r'^crossbarfabriccenter.node.([a-z0-9][a-z0-9_\-]*).worker.([a-z0-9][a-z0-9_\-]*).realm.([a-z0-9][a-z0-9_\-]*).root.(\S*)$' remote_uri_pat = re.compile(remote_uri_regex) def forward(*args, **kwargs): try: details = kwargs.pop('details', None) if details: match = remote_uri_pat.match(details.topic) if match and len(match.groups()) == 4: node_id, worker_id, realm_id, suffix_uri = match.groups() # reverse our hack: see crossbar.router.service.RouterServiceSession.publish suffix_uri = suffix_uri.replace('-', '.') local_uri = '{}{}'.format(self.PREFIX, suffix_uri) self.log.debug('RemoteWampApi.forward("{topic}") -> "{local_uri}"', topic=details.topic, local_uri=local_uri) return session.publish(local_uri, node_id, worker_id, realm_id, *args, **kwargs) # should not arrive here session.log.warn( 'received unexpected WAMP meta event to forward for management API: details={details}', details=details) except: session.log.failure() sub = session.subscribe(forward, remote_uri, SubscribeOptions(match='wildcard', details=True)) return [sub]
async def onConnect(self): """ Configure the component """ # subscription setup self.subscribed_topics = self.config.extra['config']['subscribed_topics'] self.subscribe_options = SubscribeOptions(**self.config.extra['config']['sub_options']) self.replay_events = self.config.extra['config']['replay_events'] # publishing setup self.publish_topic = self.config.extra['config']['publish_topic']['topic'] self.publish_options = PublishOptions(**self.config.extra['config']['pub_options']) # setup callback self.handlers = self.config.extra['handlers'] # put name on session self.name = self.config.extra['config']['name'] # setup db pool self.pool = await asyncpg.create_pool( user=EVENT_DB_USER, password=EVENT_DB_PASS, host=EVENT_DB_HOST, database=EVENT_DB_NAME ) # Check for replay option # if self.replay_events: # await replay_events(self) # join topic print("connected") self.join(self.config.realm)
def on_subscription_create(sub_id, sub_details, details=None): self.log.info( "Subscription created: {me} {sub_id} {sub_details} {details}", me=self, sub_id=sub_id, sub_details=sub_details, details=details, ) self._subs[sub_id] = sub_details uri = sub_details['uri'] def on_event(*args, **kwargs): details = kwargs.pop('details') # FIXME: setup things so out (the node's) identity gets disclosed self.publish(uri, *args, options=PublishOptions(), **kwargs) self.log.info( "forwarded from {other} event to {me} ({dir}): args={args}, details={details}", other=other, me=self, dir=self._DIR, args=args, details=details, ) sub = yield other.subscribe( on_event, uri, options=SubscribeOptions(details_arg="details")) self._subs[sub_id]['sub'] = sub self.log.info("{other} subscribed to {me}".format(other=other, me=uri))
def onJoin(self, details): self.log.info('session joined: {details}', details=details) def on_event(pid, seq, ran, details=None): self.log.info( 'event received on topic {topic}: pid={pid}, seq={seq}, ran={ran}, details={details}\n', topic=TOPIC, pid=pid, seq=seq, ran=binascii.b2a_hex(ran), details=details) reg = yield self.subscribe(on_event, TOPIC, options=SubscribeOptions(details=True)) self.log.info('subscribed to topic {topic}: registration={reg}', topic=TOPIC, reg=reg) pid = os.getpid() seq = 1 while True: pub = yield self.publish( TOPIC, pid, seq, os.urandom(8), options=PublishOptions(acknowledge=True, exclude_me=False), ) self.log.info('event published: publication={pub}\n', pub=pub) seq += 1 yield sleep(1)
async def joined(session, details): print('Buyer session joined', details) market_maker_adr = binascii.a2b_hex( session.config.extra['market_maker_adr'][2:]) print('Using market maker adr:', session.config.extra['market_maker_adr']) buyer_privkey = binascii.a2b_hex(session.config.extra['buyer_privkey'][2:]) # 100 XBR max_price = 100 * 10**18 buyer = SimpleBuyer(market_maker_adr, buyer_privkey, max_price) balance = await buyer.start(session, details.authid) balance = int(balance / 10**18) print("Remaining balance: {} XBR".format(balance)) async def on_event(key_id, enc_ser, ciphertext, details=None): try: payload = await buyer.unwrap(key_id, enc_ser, ciphertext) print('Received event {}:'.format(details.publication), payload) session.publish(u'xbr.myapp.cardata', payload['counter']) except Exception as e: print(e) session.leave() await session.subscribe(on_event, "io.crossbar.example", options=SubscribeOptions(details=True))
def onJoin(self, details): print("session attached {}".format(details)) def got_event(*args, **kw): print("got_event(): args={}, kwargs={}".format(args, kw)) # note: we're relying on 'com.example.history' (the one with # event-history enabled) being last so that "pub" has the # right ID for wamp.subscription.get_events after the loop for topic in ["com.example.no_history_here", "com.example.history"]: print("subscribing to '{}'".format(topic)) pub = yield self.subscribe( got_event, topic, options=SubscribeOptions(get_retained=True), ) print("id={}".format(pub.id)) events = yield self.call("wamp.subscription.get_events", pub.id) print("Using the WAMP Meta API:") print("wamp.subscription.get_events {}: {}".format( pub.id, len(events))) for event in events: print( " {event[timestamp]} {event[topic]} args={event[args]} kwargs={event[kwargs]}" .format(event=event))
async def joined(session, details): print('Buyer session joined', details) market_maker_adr = binascii.a2b_hex( session.config.extra['market_maker_adr'][2:]) print('Using market maker adr:', session.config.extra['market_maker_adr']) buyer_privkey = binascii.a2b_hex(session.config.extra['buyer_privkey'][2:]) max_price = 100 * 10**18 buyer = SimpleBuyer(market_maker_adr, buyer_privkey, max_price) balance = await buyer.start(session, details.authid) balance = int(balance / 10**18) print("Remaining balance: {} XBR".format(balance)) async def on_event(key_id, enc_ser, ciphertext, details=None): try: payload = await buyer.unwrap(key_id, enc_ser, ciphertext) except Exception as e: print(e) session.leave() else: print('Received event {}:'.format(details.publication), payload) print(payload.__class__) await session.subscribe(on_event, "com.conti.hackathon.team2", options=SubscribeOptions(details=True, match='prefix'))
def subscribe(self, handler, topic=None, options=None): """ Implements :func:`autobahn.wamp.interfaces.ISubscriber.subscribe` """ assert (topic is None or type(topic) == str) assert ((callable(handler) and topic is not None) or hasattr(handler, '__class__')) assert (options is None or isinstance(options, dict)) if not self._transport: raise exception.TransportLost() if callable(handler): # subscribe a single handler return self._subscribe(None, handler, topic, options) else: # subscribe all methods on an object decorated with "wamp.subscribe" on_replies = [] for k in inspect.getmembers(handler.__class__, is_method_or_function): proc = k[1] wampuris = filter(lambda x: x.is_handler(), proc.__dict__.get("_wampuris")) or () for pat in wampuris: subopts = pat.options or options or SubscribeOptions( match=u"wildcard" if pat.uri_type == uri.Pattern. URI_TYPE_WILDCARD else u"exact").message_attr() on_replies.append( self._subscribe(handler, proc, pat.uri(), subopts)) return txaio.gather(on_replies, consume_exceptions=True)
def onJoin(self, details): self.log.info('{klass}[{ident}].onJoin(details={details})', klass=self.__class__.__name__, ident=self.ident, details=details) yield self.subscribe(self, options=SubscribeOptions(details=True))
def onJoin(self, details): print("History session joined: {}".format(details)) # Automatically subscribe to all topics so that all events can be stored. def store_message(*args, **kwargs): details = kwargs.pop('details') HISTORY_SESSION_EVENT_MAP[details.topic][kwargs['originator']] = [ args, kwargs ] print('Got message from {} on {}'.format(kwargs['originator'], details.topic)) sub = yield self.subscribe(store_message, '.', options=SubscribeOptions( match=u'wildcard', details_arg='details')) print('Now tracking events from all topics.') # Register the `meta.last_event` remote procedure. def last_event(topic, originator): print('Looking up last message from {} on {}'.format( originator, topic)) return HISTORY_SESSION_EVENT_MAP.get(topic, {}).get(originator) reg = yield self.register(last_event, 'meta.last_event') print('Event history now available at `meta.last_event`.')
def save_link(self, link_name: str, link_spec): """ Create, save, and modify. All in one! We're going to be super lazy and assume the name engine won't collide too hard """ # print(link_name) # print(link_spec) list_name = link_spec['source']['list_name'] target_id = link_spec['target']['id'] source_id = link_spec['source']['id'] self.links[link_name] = Link(name=link_name, active=True, list_name=list_name, full_spec=link_spec) self.link_tgt_map[link_name] = target_id self.link_name_to_source[link_name] = list_name self.link_subs[link_name] = yield self.subscribe( self.pass_link, topic=source_id, options=SubscribeOptions(details_arg="details", correlation_id=link_name, correlation_is_anchor=True)) self._do_toggle(link_spec['target']['id'], exclude=link_name)
def onJoin(self, details): print("Session attached!") #TODO: Configuration for these #Command line args self.gameId = sys.argv[1] self.sessionId = sys.argv[2] #URIs join_game_uri = 'com.game{}.joingame'.format(self.gameId) # call a remote procedure. res = yield self.call(join_game_uri, self.sessionId) if res[0] == 1: print("The following error occurred.") print(res[1]) self.leave() return self.id = res[1] print("The agent was assigned the id: {}".format(self.id)) self.endpoints = { 'REQUEST': 'monopoly.game{}.agent{}.request', 'RESPONSE': 'monopoly.game{}.agent{}.response' } self.phaseToMethod = { 'START_GAME': self.startGame, 'JAIL': self.jailDecision, 'BUY': self.buyProperty, 'BUY_RESULT': self.buyResult, 'AUCTION': self.auctionProperty, 'MORTGAGE': self.mortgage, 'UNMORTGAGE': self.unmortgage, 'SELL_HOUSES': self.sellHouses, 'TRADE': self.getTradeDecision, 'TRADE_RESPONSE': self.respondTrade, 'BUY_HOUSES': self.buyHouses, 'END_GAME': self.endGame, 'START_TURN': self.startTurn, #'JAIL_RESULT' : 'DICE_ROLL': self.diceRoll, #'CHANCE_CARD' : #'COMMUNITY_CHEST' : #'AUCTION_RESULT' : #'MORTGAGE_RESULT' : #'UNMORTGAGE_RESULT' : #'SELL_HOUSES_RESULT' : #'TRADE_RESULT' : #'BUY_HOUSES_RESULT' : 'END_TURN': self.endTurn, } uri = self.endpoints['REQUEST'].format(self.gameId, self.sessionId) self.requestId = yield self.subscribe( self.mapper, uri, options=SubscribeOptions(get_retained=True)) print("Successfully registered!")
def onJoin(self, details): skyid = self.args.skyId topic = str("sky.devices.") + str(skyid) self.log.info("Client session joined {details}", details=details) self.log.info("Topic: {topic}", topic=topic) def cmd_agent_update(): os.execl("/etc/sky/agent/agent", "") def cmd_get_config(): config = { "network": str(subprocess.check_output(['ls', '-l'])), "memory": str(subprocess.check_output(['ls', '-l'])) } return str(config) def dev_internal(message, details): self.log.info("Message {message}", message=message) def dev_public(message, details): self.log.info("Message {message}", message=message) cmd_agent_update() yield self.subscribe(dev_internal, u"{topic}", options=SubscribeOptions(details_arg='details')) self.log.info("subscribed to topic '{topic}'", topic=topic) yield self.subscribe(dev_public, u"sky.devices", options=SubscribeOptions(details_arg='details')) self.log.info("subscribed to topic sky.devices") self.publish(u"sky.devices", { "skyId": str(skyid), "action": "up", "config": Agent.get_config() }) self.publish( u"sky.devices", { "skyId": str(skyid), "action": "chilli_state", "clients": Agent.get_chilli() })
def onJoin(self, details): from autobahn.wamp.types import SubscribeOptions self.log.debug("Joined realm '{realm}' on node management router", realm=details.realm) # When a (native) worker process has connected back to the router of # the node controller, the worker will publish this event # to signal it's readyness. # def on_worker_ready(res): worker_id = res['id'] if worker_id in self._workers: ready = self._workers[worker_id].ready if not ready.called: # fire the Deferred previously stored for # signaling "worker ready" ready.callback(worker_id) else: self.log.error("Internal error: on_worker_ready() fired for process {process}, but already called earlier", process=worker_id) else: self.log.error("Internal error: on_worker_ready() fired for process {process}, but no process with that ID", process=worker_id) self.subscribe(on_worker_ready, u'crossbar.worker..on_worker_ready', SubscribeOptions(match=u'wildcard')) yield NativeProcess.onJoin(self, details) # above upcall registers procedures we have marked with @wamp.register(None) # we need to catch SIGINT here to properly shutdown the # node explicitly (a Twisted system trigger wouldn't allow us to distinguish # different reasons/origins of exiting ..) def signal_handler(_signal, frame): if _signal == signal.SIGINT: # CTRL-C'ing Crossbar.io is considered "willful", and hence we want to exit cleanly self._shutdown_was_clean = True elif _signal == signal.SIGTERM: self._shutdown_was_clean = False else: # FIXME: can we run into others here? self._shutdown_was_clean = False self.log.warn('Controller received SIGINT [signal={signal}]: shutting down node [shutdown_was_clean={shutdown_was_clean}] ..', signal=_signal, shutdown_was_clean=self._shutdown_was_clean) # the following will shutdown the Twisted reactor in the end self.shutdown() signal.signal(signal.SIGINT, signal_handler) self.log.info('Signal handler installed on process {pid} thread {tid}', pid=os.getpid(), tid=threading.get_ident()) self._started = utcnow() self.publish(u"crossbar.on_ready") self.log.debug("Node controller ready")
def onJoin(self, details): print("session attached {}".format(details)) def got_meta(*args, **kw): details = kw.pop('details') print("meta: '{}' args={}, kw={}".format(details.topic, args, kw)) yield self.subscribe( got_meta, u'', options=SubscribeOptions(match=u'prefix', details_arg='details'), )
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)
def onJoin(self, details): self.log.info('session joined: {details}', details=details) # setup application payload end-to-end encryption ("WAMP-cryptobox") # when a keyring was set, end-to-end encryption is performed automatically if False: # this is simplest keyring: for all URIs, use one key for both # originators and responders. keyring = KeyRing(PRIVKEY) else: # this is a more specialized keyring: we only make URIs starting # with "com.myapp.encrypted." encrypted, and only with private key # for originator (= this session, as it is "calling" and "publishing") keyring = KeyRing() # since we want to act as "callee" and "subscriber") we are thus a "responder" # and responders need the responder private key. however, we don't act as "callers" # or "publishers", and hence can get away with the public key for the originator only! key = Key(originator_pub=ORIGINATOR_PUB, responder_priv=RESPONDER_PRIV) keyring.set_key('com.myapp.encrypted.', key) self.set_payload_codec(keyring) # now start the testing .. def add2(a, b, details=None): self.log.info('call received: a={a}, b={b}, details={details}', a=a, b=b, details=details) # when the procedure args were encrypted, the result will be always encrypted too! return a + b options = RegisterOptions(details_arg='details') reg1 = yield self.register(add2, 'com.myapp.add2', options=options) reg2 = yield self.register(add2, 'com.myapp.encrypted.add2', options=options) def failme(encrypted_error, details=None): # IMPORTANT: independent of whether the "failme" procedure args were encrypted or not, # an error returned to the caller will be encrypted or not depending soley # on the error URI! if encrypted_error: raise ApplicationError("com.myapp.encrypted.error1", custom1=23, custom2='Hello') else: raise ApplicationError("com.myapp.error1", custom1=23, custom2='Hello') reg3 = yield self.register(failme, 'com.myapp.failme', options=options) reg4 = yield self.register(failme, 'com.myapp.encrypted.failme', options=options) def on_hello(msg, details=None): self.log.info('event received: msg="{msg}", details={details}', msg=msg, details=details) options = SubscribeOptions(details=True) sub1 = yield self.subscribe(on_hello, 'com.myapp.hello', options=options) sub2 = yield self.subscribe(on_hello, 'com.myapp.encrypted.hello', options=options) self.log.info('session ready!')
def onJoin(self, details): from autobahn.wamp.types import SubscribeOptions self.log.info("Joined realm '{realm}' on node management router", realm=details.realm) # When a (native) worker process has connected back to the router of # the node controller, the worker will publish this event # to signal it's readyness. # def on_worker_ready(res): id = res['id'] if id in self._workers: ready = self._workers[id].ready if not ready.called: # fire the Deferred previously stored for # signaling "worker ready" ready.callback(id) else: self.log.error( "Internal error: on_worker_ready() fired for process {process}, but already called earlier", process=id) else: self.log.error( "Internal error: on_worker_ready() fired for process {process}, but no process with that ID", process=id) self.subscribe(on_worker_ready, u'crossbar.worker..on_worker_ready', SubscribeOptions(match=u'wildcard')) yield NativeProcessSession.onJoin(self, details) # register node controller procedures: 'crossbar.node.<ID>.<PROCEDURE>' # dl = [] for proc in self.PROCS: uri = '{}.{}'.format(self._uri_prefix, proc) self.log.info('Registering management API procedure "{proc}"', proc=uri) dl.append( self.register(getattr(self, proc), uri, options=RegisterOptions(details_arg='details'))) regs = yield DeferredList(dl) self.log.debug("Registered {cnt} management API procedures", cnt=len(regs)) self._started = utcnow() self.publish(u"crossbar.on_ready") self.log.debug("Node controller ready")
def subscribe(self, service, _filter): self.filter = _filter self.emulated = False options = dict(details_arg=str('details')) if None in _filter: options["match"] = "wildcard" options = SubscribeOptions(**options) _filter = WampMQ.messageTopic(_filter) self.unreg = yield service.subscribe(self.invoke, _filter, options=options) if self.callback is None: yield self.stopConsuming()
async def onJoin(self, details): self.received = 0 def on_event(i, details=None): print("Got event, publication ID {}, publisher {}: {}".format(details.publication, details.publisher, i)) self.received += 1 if self.received > 5: self.leave() await self.subscribe(on_event, u'com.myapp.topic1', options=SubscribeOptions(details_arg='details'))
def subscribe(self, handler, topic, options=None): print('subscribe:', handler, topic) if options == None: options = {'details_arg': 'details'} if topic.endswith('.*'): options['match'] = 'prefix' elif '..' in topic: options['match'] = 'wildcard' super().subscribe(handler, topic, options=SubscribeOptions(**options))
async def _subscribe(self, subscriber: Subscriber): async def wrapper(*args, _event_details: EventDetails, **kwargs): async with EventContext(self._context, self._session_details, _event_details) as ctx: retval = subscriber.handler(ctx, *args, **kwargs) if isawaitable(retval): await retval options = SubscribeOptions(details_arg='_event_details', **subscriber.options) await self._session.subscribe(wrapper, subscriber.topic, options)
async def onJoin(self, details): """ Get called if the component successful connected to the wamp router :param details: :return: """ await self.subscribe(self.on_more_info, "sofia.channel..messages.MoreInfo", options=SubscribeOptions(match='wildcard', details_arg='details')) print("Registered methods; ready for actions. Give me some... ")
def onJoin(self, details): # SUBSCRIBE to a topic and receive events # def onhello(msg, details=None): self.log.info("event for 'onhello' received: {msg} {details}", msg=msg, details=details) yield self.subscribe(onhello, 'com.example.onhello', options=SubscribeOptions(details_arg='details')) self.log.info("subscribed to topic 'onhello'") # REGISTER a procedure for remote calling # def add2(x, y, details=None): self.log.info("add2() called with {x} and {y} - {details}", x=x, y=y, details=details) return x + y yield self.register(add2, 'com.example.add2', options=RegisterOptions(details_arg='details')) self.log.info("procedure add2() registered") # PUBLISH and CALL every second .. forever # counter = 0 while True: # PUBLISH an event # yield self.publish('com.example.oncounter', counter) self.log.info("published to 'oncounter' with counter {counter}", counter=counter) counter += 1 # CALL a remote procedure # try: res = yield self.call('com.example.mul2', counter, 3) self.log.info("mul2() called with result: {result}", result=res) except ApplicationError as e: # ignore errors due to the frontend not yet having # registered the procedure we would like to call if e.error != 'wamp.error.no_such_procedure': raise e yield sleep(1)
def _start_event_forwarding(self): # setup event forwarding (events originating locally are forwarded uplink) # @inlineCallbacks def on_management_event(*args, **kwargs): if not (self._manager and self._manager.is_attached()): self.log.warn( "Can't foward management event: CFC session not attached") return details = kwargs.pop('details') # a node local event such as 'crossbar.node.on_ready' is mogrified to 'local.crossbar.node.on_ready' # (one reason is that URIs such as 'wamp.*' and 'crossbar.*' are restricted to trusted sessions, and # the management bridge is connecting over network to the uplink CFC and hence can't be trusted) # topic = self._translate_uri(details.topic) try: yield self._manager.publish( topic, *args, options=PublishOptions(acknowledge=True), **kwargs) except Exception: self.log.failure( "Failed to forward event on topic '{topic}': {log_failure.value}", topic=topic, ) else: if topic.endswith('.on_log'): log = self.log.debug else: log = self.log.debug log('Forwarded management {forward_type} to CFC [local_uri={local_topic}, remote_uri={remote_topic}]', forward_type=hl('EVENT'), local_topic=hlid(details.topic), remote_topic=hlid(topic)) try: sub = self._sub_on_mgmt = yield self.subscribe( on_management_event, u"crossbar.", options=SubscribeOptions(match=u"prefix", details_arg="details")) self.log.debug( "Setup prefix subscription to forward node management events: {sub}", sub=sub) except: self.log.failure()
def onJoin(self, details): subscriptions = self.config.extra["subscriptions"] debug = self.config.extra.get("debug", False) method = self.config.extra.get("method", "POST") expectedCode = self.config.extra.get("expectedcode") @inlineCallbacks def on_event(url, *args, **kwargs): headers = Headers({ b"Content-Type": [b"application/json"] }) body = json.dumps( {"args": args, "kwargs": kwargs}, sort_keys=True, separators=(',', ':'), ensure_ascii=False ) # http://treq.readthedocs.org/en/latest/api.html#treq.request res = yield self._webtransport.request( method, url.encode('utf8'), data=body.encode('utf8'), headers=headers ) if expectedCode: if not res.code == expectedCode: raise ApplicationError( "Request returned {}, not the expected {}".format(res.code, expectedCode)) if debug: content = yield self._webtransport.text_content(res) self.log.debug(content) for s in subscriptions: # Assert that there's "topic" and "url" entries assert "topic" in s assert "url" in s yield self.subscribe( partial(on_event, s["url"]), s["topic"], options=SubscribeOptions(match=s.get("match", "exact")) ) self.log.debug("MessageForwarder subscribed to {topic}", topic=s["topic"])
async def joined(session, details): print('Buyer session joined', details) market_maker_adr = binascii.a2b_hex( session.config.extra['market_maker_adr'][2:]) print('Using market maker adr:', session.config.extra['market_maker_adr']) buyer_privkey = binascii.a2b_hex(session.config.extra['buyer_privkey'][2:]) max_price = 100 * 10 ** 18 buyer = SimpleBuyer(market_maker_adr, buyer_privkey, max_price) balance = await buyer.start(session, details.authid) balance = int(balance / 10 ** 18) print("Remaining balance: {} XBR".format(balance)) # seller seller_privkey = binascii.a2b_hex( session.config.extra['seller_privkey'][2:]) api_id = UUID('627f1b5c-58c2-43b1-8422-a34f7d3f5a04').bytes topic_seller = 'com.conti.hackathon.team1.sell' topic_buyer = "com.conti.hackathon.team1" counter = 1 seller = SimpleSeller(market_maker_adr, seller_privkey) price = 35 * 10 ** 18 interval = 10 seller.add(api_id, topic_seller, price, interval, None) balance = await seller.start(session) balance = int(balance / 10 ** 18) print("Remaining balance: {} XBR".format(balance)) async def on_event(key_id, enc_ser, ciphertext, details=None): try: payload = await buyer.unwrap(key_id, enc_ser, ciphertext) print(payload) key_id, enc_ser, ciphertext = await seller.wrap(api_id, topic_seller, payload) pub = await session.publish(topic_seller, key_id, enc_ser, ciphertext, options=PublishOptions(acknowledge=True)) print('Published event {}: {}'.format(pub.id, payload)) except Exception as e: print(e) session.leave() else: print('Received event {}:'.format(details.publication), payload) await session.subscribe(on_event, topic_buyer, options=SubscribeOptions(details=True, match="prefix"))