예제 #1
0
    def run(cls):
        print(f"Starting {cls.__name__}...")

        url = "ws://%s:%s" % (config["analytics"]["host"], config["analytics"]["port"])

        runner = ApplicationRunner(url=url, realm=config["analytics"]["realm"])
        runner.run(AnalyticsWAMPComponent)
    def run(self):
        print("Starting Default Commands Component...")

        url = "ws://%s:%s/ws" % (config["crossbar"]["host"], config["crossbar"]["port"])

        runner = ApplicationRunner(url=url, realm=config["crossbar"]["realm"])
        runner.run(DefaultCommandsWAMPComponent)
예제 #3
0
파일: monitor.py 프로젝트: utfsmlabs/tirith
def main(args=None):
    
    if args is None:
        args = sys.argv[1:]
    print("tirith monitor 0.2.0")
    print("connecting")
    
    runner = ApplicationRunner(url=u"ws://frameshift:8080/ws", realm=u"realm1")
    runner.run(MonitorComponent)
예제 #4
0
파일: connector.py 프로젝트: go-smart/glot
def execute(action, actor, server, router, port, debug=False, **kwargs):
    responses = []
    if debug:
        logger.info("DEBUG ON")
        logging.getLogger('autobahn').setLevel(logging.DEBUG)

    runner = ApplicationRunner(url="ws://%s:%d/ws" % (router, port), realm="realm1")
    logger.debug("Starting connection")
    runner.run(partial(GlotConnector, responses=responses, action=action, actor=actor, debug=debug, server=server, **kwargs))
    return responses.pop() if responses else None
예제 #5
0
파일: client.py 프로젝트: utfsmlabs/tirith
def main(args=None):
    if args is None:
        args = sys.argv[1:]    
    print("tirith client 0.2.0")
    
    print ("connecting...")
    
    runner = ApplicationRunner(url=u"ws://frameshift:8080/ws", realm=u"realm1")
    # throws socket.gaierror on 404
    runner.run(TestComponent)
예제 #6
0
def main_entry(ssl_cert=None):
    from autobahn.asyncio.wamp import ApplicationRunner
    proto = "wss" if ssl_cert else "ws"
    options = None
    if ssl_cert:
        raise RuntimeError("asyncio backend does not support ssl")
    runner = ApplicationRunner(url=u"{0}://127.0.0.1:8181/ws".format(proto),
                               realm=u"realm1", ssl=options)
    try:
        runner.run(Component)
    except KeyboardInterrupt or Exception:
        raise KeyboardInterrupt
    print "shutting down kogniserver..."
예제 #7
0
def main():
    # load command-line options
    arguments = docopt.docopt(__doc__.format(sys.argv[0]), version="0.0.1")

    # All these dashes are stupid
    arguments = {k.lstrip('--'): v for k,v in arguments.items()}

    verbose = arguments.get("verbose", 0)
    quiet = arguments.get("quiet", 0)
    level = logging.WARN

    if verbose == 1:
        level = logging.INFO
    elif verbose == 2:
        level = logging.DEBUG
    elif verbose == 3:
        level = logging.DEBUG - 1
    elif verbose == 4:
        level = logging.DEBUG - 2
    elif quiet == 1:
        level = logging.ERROR
    elif quiet == 2:
        level = logging.CRITICAL + 1


    config = {}

    try:
        conf_path = arguments["config"]
        if not os.path.isfile(conf_path):
            conf_path = "/etc/orthogonalspace/conf.json"
        if not os.path.isfile(conf_path):
            conf_path = "/usr/lib/orthogonalspace/conf.json"
        if not os.path.isfile(conf_path):
            sys.exit("You must provide a config file")
         
        with open(conf_path) as conf_file:
            config = json.load(conf_file)

    except (OSError, IOError):
        LOG.exception("Could not load config file {}:".format(arguments["config"]))
        pass

    runner = ApplicationRunner(
        os.environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
        u'orthogonalspace',
        extra=config,
    )
    runner.run(OrthogonalSpaceComponent)
예제 #8
0
파일: poloniex.py 프로젝트: ligggooo/bitex
class PlnxEndpoint(mp.Process):
    def __init__(self, endpoint, q, **kwargs):
        super(PlnxEndpoint, self).__init__(name='%s Endpoint Process' %
                                                endpoint, **kwargs)
        self.endpoint = endpoint
        self.q = q
        self.is_killed = mp.Event()

    def run(self):
        self.runner = ApplicationRunner("wss://api.poloniex.com:443", 'realm1',
                                   extra={'channel': self.endpoint,
                                          'queue': self.q,
                                          'is_killed': self.is_killed})
        self.runner.run(PoloniexSession)

    def join(self, *args, **kwargs):
        self.is_killed.set()
        super(PlnxEndpoint, self).join(*args, **kwargs)
예제 #9
0
파일: lechbot.py 프로젝트: UrLab/lechbot
def run_wamp(bot):
    """
    Run LechBot in an Autobahn application
    """
    class Component(ApplicationSession):
        @asyncio.coroutine
        def onJoin(self, details): # NOQA
            bot.log.info("Joined WAMP realm !")

            last_seen_keys = {}

            def on_event(key, time, text):
                now = datetime.now()
                time = parse_time(time)

                # Outdated message
                if (now - time).total_seconds() > 120:
                    bot.log.info("Got outdated event " + repr({
                        'key': key, 'time': time, 'text': text
                    }))
                    return

                # Rate limit
                last_seen = last_seen_keys.get(key, datetime.fromtimestamp(0))
                if (now - last_seen).total_seconds() < RATELIMIT.get(key, 0):
                    bot.log.info("Got rate-limited event " + repr({
                        'key': key, 'time': time, 'text': text
                    }) + " / Last seen: " + repr(last_seen))
                    return

                bot.say(text, target=MAIN_CHAN)
                bot.log.debug("Got " + repr({
                    'key': key, 'time': time, 'text': text
                }))

                last_seen_keys[key] = now
            yield from self.subscribe(on_event, u'incubator.actstream')
            yield from self.subscribe(on_event, u'hal.eventstream')

    runner = ApplicationRunner(WAMP_HOST, WAMP_REALM)
    runner.run(Component)
예제 #10
0
    def connect(self,url,realm):
        '''connect to websocket
           :param str url: url to which connect
        '''
        self.url = url
        if self.conn.id is None:
            self.conn.login()

        self.th = Thread(target=self.__f)
        self.runner = ApplicationRunner(url=url, ssl=True, realm=realm, headers={'cookie':'sessionid=%s' % self.conn.id})
        self.loop = asyncio.get_event_loop()
        self.session = ApplicationSession()
        coro = self.runner.run(self.session,start_loop = False)
        (self.__transport, self.__protocol) = self.loop.run_until_complete(coro)
        self.th.start()
예제 #11
0
class WampBase(object):
    '''Base class for websocket streaming
    '''
    def __init__(self,con):
        ''':param web.rest.base.Connection con: the base http connection
        '''
        self.conn    = con
        self.runner  = None
        self.url     = None
        self.loop    = None
        self.session = None
        self.th      = None

    def connect(self,url,realm):
        '''connect to websocket
           :param str url: url to which connect
        '''
        self.url = url
        if self.conn.id is None:
            self.conn.login()

        self.th = Thread(target=self.__f)
        self.runner = ApplicationRunner(url=url, ssl=True, realm=realm, headers={'cookie':'sessionid=%s' % self.conn.id})
        self.loop = asyncio.get_event_loop()
        self.session = ApplicationSession()
        coro = self.runner.run(self.session,start_loop = False)
        (self.__transport, self.__protocol) = self.loop.run_until_complete(coro)
        self.th.start()

    def subscribe(self,callback,topic):
        if self.session is None:
            raise RuntimeError('no Connection active')
        return self.session.subscribe(callback,topic)


    def leave(self):
        if self.session is not None:
            self.session.leave()
            self.stop()

    def stop(self):
        if self.loop is not None:
            self.loop.stop()
            self.loop = None

    def __f(self):
        #asyncio.set_event_loop(self.loop)
        self.loop.run_forever()
예제 #12
0
        def __init__(self,config=None):
            logging.debug('instanciando WampMain')
            ApplicationSession.__init__(self, config)


        def _userIdentified(self,data):
            logging.info('--- Usuario identificado ---')
            logging.info(data)
            sys.exit(0)

        @coroutine
        def onJoin(self, details):
            logging.debug('session joined')

            yield from self.subscribe(self._userIdentified,'assistance.firmware.identify')

            try:
                yield from self.call('assistance.firmware.login',dni,password)

            except Exception as e:
                logging.exception(e)
                sys.exit(1)



    from autobahn.asyncio.wamp import ApplicationRunner

    runner = ApplicationRunner(url='ws://localhost:8000/ws',realm='assistance',debug=True, debug_wamp=True, debug_app=True)
    runner.run(WampCommand)
예제 #13
0
'''
if __name__ == '__main__':

    import sys
    import logging
    import inject
    sys.path.insert(0, '../python')

    logging.basicConfig(level=logging.DEBUG)

    from autobahn.asyncio.wamp import ApplicationRunner
    from model.config import Config
    from actions.systems.files.files import FilesWamp

    def config_injector(binder):
        binder.bind(Config, Config('server-config.cfg'))

    inject.configure(config_injector)
    config = inject.instance(Config)

    url = config.configs['server_url']
    realm = config.configs['server_realm']
    debug = config.configs['server_debug']

    runner = ApplicationRunner(url=url,
                               realm=realm,
                               debug=debug,
                               debug_wamp=debug,
                               debug_app=debug)
    runner.run(FilesWamp)
예제 #14
0
from model.config import Config

logging.basicConfig(level=logging.DEBUG)

def config_injector(binder):
    binder.bind(Config,Config('firmware-config.cfg'))

inject.configure(config_injector)
config = inject.instance(Config)


'''
    Ejecuta el protocolo Wamp del modelo del firmware
'''
if __name__ == '__main__':

    from autobahn.asyncio.wamp import ApplicationRunner
    from autobahn.wamp.serializer import JsonSerializer
    from network.wampFirmware import WampFirmware




    url = config.configs['firmware_url']
    realm = config.configs['firmware_realm']
    debug = config.configs['firmware_debug']

    json = JsonSerializer()
    runner = ApplicationRunner(url=url,realm=realm,debug=debug, debug_wamp=debug, debug_app=debug, serializers=[json])
    runner.run(WampFirmware)
예제 #15
0
파일: server.py 프로젝트: Shane32/euchre-2
        async def join_server(name=None):
            player_id = self.player_count
            if name is None:
                name = "Player {}".format(player_id)
            self.player_count += 1
            player = Player(player_id, name, self)
            self.players[player_id] = player
            self.publish('players', {player_id: name})

            await self.register(player.perform_move,
                                'player{n}.perform_move'.format(n=player_id))
            await self.register(player.start_game,
                                'player{n}.start_game'.format(n=player_id))
            await self.register(player.join_seat,
                                'player{n}.join_seat'.format(n=player_id))
            await self.register(player.set_name,
                                'player{n}.set_name'.format(n=player_id))
            await self.register(player.change_seat,
                                'player{n}.change_seat'.format(n=player_id))

            return player_id, name

        await self.register(join_server, 'join_server')
        await self.register(self.get_players, 'players')
        await self.register(self.get_seats, 'seats')


if __name__ == '__main__':
    runner = ApplicationRunner(url=u"ws://localhost:8080/ws", realm=u"realm1")
    runner.run(Coordinator)
예제 #16
0
'''
    Se conecta al router wamp y hace correr AssistanceWamp y JustificationsWamp
'''
if __name__ == '__main__':

    import sys
    import logging
    import inject
    inject.configure()

    sys.path.insert(0, '../python')

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger().setLevel(logging.DEBUG)

    from autobahn.asyncio.wamp import ApplicationRunner
    from actions.systems.assistance.assistance import AssistanceWamp
    # from actions.systems.assistance.justifications import JustificationsWamp
    from model.registry import Registry

    reg = inject.instance(Registry)
    registry = reg.getRegistry('wamp')
    url = registry.get('url')
    realm = registry.get('realm')
    debug = registry.get('debug')

    logging.info('iniciando app en {} {} {}'.format(url, realm, debug))
    runner = ApplicationRunner(url=url, realm=realm)
    runner.run(AssistanceWamp)
    # runner.run(JustificationsWamp)
예제 #17
0
from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner


class MyComponent(ApplicationSession):
    def onJoin(self, details):
        print("session ready")


runner = ApplicationRunner(url=u"ws://192.168.1.130:8080/ws", realm=u"realm1")
runner.run(MyComponent)
import sys

from autobahn.asyncio.wamp import ApplicationRunner
from prettyconf import config

from .wamp import WampClient

URL = config('WAMP_URL', default='ws://crossbar.dronemapp.com:80/ws')
REALM = config('WAMP_REALM', default='kotoko')

runner = ApplicationRunner(URL, REALM)
try:
    runner.run(WampClient)
except OSError as ex:
    print('OSError:', ex)
    sys.exit(100)
예제 #19
0
def main():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
예제 #20
0
 def start_publishing(self):
     runner = ApplicationRunner(url=u"wss://demo.crossbar.io/ws",
                                realm=u"realm1")
     runner.run(PublishStock.PublishStockRunner)
예제 #21
0
                self.publish(target, 0, 0, "Plays: " + str(player.plays))
                self.publish(target, 0, 1, "Wins:  " + str(player.wins))

            self.screen.clear()
            self.screen.send()

            for player in self.players.values():
                player.reset()

            self.powerups = []
            self.entities = []

    def onDisconnect(self):
        """
        Called when the WAMP connection is disconnected
        :return: None
        """
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    if GAME_ID == 'demo_game':
        print("Please change GAME_ID to something else!")
        exit(1)

    runner = ApplicationRunner(
        WAMP_URL,
        WAMP_REALM,
    )
    runner.run(GameComponent, log_level='info')
예제 #22
0
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
import ssl


class Component(ApplicationSession):
    """
    An application component that publishes an event every second.
    """
    async def onJoin(self, details):
        counter = 0
        while True:
            print("publish: com.myapp.topic1", counter)
            self.publish(u'com.myapp.topic1', counter)
            counter += 1
            await asyncio.sleep(1)


if __name__ == '__main__':
    # see README; this way everything accesses same cert-files
    cert_path = '../../../../twisted/wamp/pubsub/tls/server.crt'
    print(cert_path)
    # create an ssl.Context using just our self-signed cert as the CA certificates
    options = ssl.create_default_context(cadata=open(cert_path, 'r').read())
    # ...which we pass as "ssl=" to ApplicationRunner (passed to loop.create_connection)
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"wss://127.0.0.1:8083/ws"),
        u"crossbardemo",
        ssl=options,  # try removing this, but still use self-signed cert
    )
    runner.run(Component)
예제 #23
0
            # read config and add macs to library
            self.auto_prefixes = self.redis.get()

        # self.scan_runner = task.LoopingCall(self.do_scan())
        # self.scan_runner.start(self.SCAN_TICKS)
        # d = threads.deferToThread(self.do_scan)
        # d.addCallback(self.save_device_scan)
        # d.addErrback(self.err_device_scan)
        await self.do_scan()

    async def do_scan(self):
        print("scanning")
        result = await self.scanner.discover()
        for d in result:
            print(d)

    def save_device_scan(self, results: List):
        pass

    def err_device_scan(self, *args, **kwargs):
        print("err")
        print(args)

    def write_config(self):
        pass

if __name__ == '__main__':
    url = os.environ.get("XBAR_ROUTER", u"ws://127.0.0.1:8083/ws")
    realm = u"realm1"
    runner = ApplicationRunner(url, realm)
    runner.run(BLEScanSession)
예제 #24
0
def main():
    runner = ApplicationRunner(url="ws://localhost:8080/ws", realm="realm1")
    runner.run(ClientSession)
예제 #25
0
파일: Base.py 프로젝트: Yoko-Mao/STC
def Start(ToRun, RealmName="realm1"):
    Runner = ApplicationRunner(environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), RealmName)
    Runner.run(ToRun)
예제 #26
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-x',
                        '--crossbar',
                        metavar='URL',
                        type=str,
                        default=os.environ.get("LG_CROSSBAR",
                                               "ws://127.0.0.1:20408/ws"),
                        help="crossbar websocket URL")
    parser.add_argument(
        '-n',
        '--name',
        dest='name',
        type=str,
        default=None,
        help='public name of this exporter (defaults to the system hostname)')
    parser.add_argument(
        '--hostname',
        dest='hostname',
        type=str,
        default=None,
        help=
        'hostname (or IP) published for accessing resources (defaults to the system hostname)'
    )
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        default=False,
                        help="enable debug mode")
    parser.add_argument(
        '-i',
        '--isolated',
        action='store_true',
        default=False,
        help="enable isolated mode (always request SSH forwards)")
    parser.add_argument('resources',
                        metavar='RESOURCES',
                        type=str,
                        help='resource config file name')

    args = parser.parse_args()

    level = 'debug' if args.debug else 'info'

    extra = {
        'name': args.name or gethostname(),
        'hostname': args.hostname or gethostname(),
        'resources': args.resources,
        'isolated': args.isolated
    }

    crossbar_url = args.crossbar
    crossbar_realm = os.environ.get("LG_CROSSBAR_REALM", "realm1")

    print("crossbar URL: {}".format(crossbar_url))
    print("crossbar realm: {}".format(crossbar_realm))
    print("exporter name: {}".format(extra['name']))
    print("exporter hostname: {}".format(extra['hostname']))
    print("resource config file: {}".format(extra['resources']))

    extra['loop'] = loop = asyncio.get_event_loop()
    if args.debug:
        loop.set_debug(True)
    runner = ApplicationRunner(url=crossbar_url,
                               realm=crossbar_realm,
                               extra=extra)
    runner.run(ExporterSession, log_level=level)
    if reexec:
        exit(100)
예제 #27
0
 def __init__(self, config: ConfigObj or dict() = {}):
     self.secrets = config
     self.limiter = RateLimiter(max_calls=self.max_calls,
                                period=self.max_period)
     self.runner = ApplicationRunner(self.ws_uri, self.ws_realm)
예제 #28
0
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner


class Component(ApplicationSession):
    """
    An application component that subscribes and receives events, and
    stop after having received 5 events.
    """
    @asyncio.coroutine
    def onJoin(self, details):

        self.received = 0

        def on_event(*args, **kwargs):
            print(args, kwargs)

        yield from self.subscribe(on_event, u'incubator.actstream')

    def onDisconnect(self):
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://snips.lan:8081/ws"),
        u"urlab",
        debug_wamp=False,  # optional; log many WAMP details
        debug=False,  # optional; log even more details
    )
    runner.run(Component)
예제 #29
0
    @coroutine
    def onJoin(self, details):
        def onRefresh(*queue):
            try:
                self.refresh(queue[0]['percent'], queue[0]['name'])
            except ValueError as e:
                print(e)
            except IndexError as e:
                print(e)
            print(queue)

        self.subscribe(onRefresh, 'queue')

    def refresh(self, percentage, name):
        self.splash.edit(str(name).lower)
        self.refresh_bar(percentage)
        self.percentage_text.edit(str(percentage) + '%')
        self.screen.refresh()

    def refresh_bar(self, percentage):
        self.bar.draw_line(x1=0, y1=0, x2=percentage // 5, y2=0)
        self.bar.draw_line(x1=0, y1=1, x2=percentage // 5, y2=1)

if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://titoubuntu:8080/ws"),
        u"crepinator"
        )
    runner.run(CrepeBot)
예제 #30
0
 def run(self):
     runner = ApplicationRunner(url=u"ws://api.interchange.ericsson.net/v1", realm=u"interchange")
     runner.run(self.Component)
예제 #31
0
def run(main=None, parser=None):
    # parse command line arguments
    parser = parser or argparse.ArgumentParser()
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true',
                        default=False,
                        help='Enable logging at level "debug".')
    parser.add_argument(
        '--url',
        dest='url',
        type=str,
        default=u'wss://fabric.crossbario.com',
        help='The Crossbar.io Fabric Center (CFC) WebSocket URL '
        '(default: wss://fabric.crossbario.com')
    parser.add_argument('--realm',
                        dest='realm',
                        type=str,
                        help='The management realm to join on CFC')
    parser.add_argument(
        '--keyfile',
        dest='keyfile',
        type=str,
        default=u'~/.cbf/default.priv',
        help='The private client key file to use for authentication.')
    parser.add_argument('--authmethod',
                        dest='authmethod',
                        type=str,
                        default=u'cryptosign',
                        help='Authentication method: cryptosign or anonymous')
    args = parser.parse_args()

    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    extra = None
    if args.authmethod == u'cryptosign':

        # for authenticating the management client, we need a Ed25519 public/private key pair
        # here, we are reusing the user key - so this needs to exist before
        privkey_file = os.path.expanduser(args.keyfile)
        privkey_hex = None
        user_id = None

        if not os.path.exists(privkey_file):
            raise Exception(
                'private key file {} does not exist'.format(privkey_file))
        else:
            with open(privkey_file, 'r') as f:
                data = f.read()
                for line in data.splitlines():
                    if line.startswith('private-key-ed25519'):
                        privkey_hex = line.split(':')[1].strip()
                    if line.startswith('user-id'):
                        user_id = line.split(':')[1].strip()

        if privkey_hex is None:
            raise Exception('no private key found in keyfile!')

        if user_id is None:
            raise Exception('no user ID found in keyfile!')

        key = cryptosign.SigningKey.from_key_bytes(
            binascii.a2b_hex(privkey_hex))

        extra = {
            u'args': args,
            u'key': key,
            u'authid': user_id,
            u'main': main,
            u'return_code': None
        }

    elif args.authmethod == u'anonymous':

        extra = {u'args': args, u'main': main, u'return_code': None}

    else:
        raise Exception('logic error')

    runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra)

    if args.authmethod == u'cryptosign':
        runner.run(ManagementClientSession)
    elif args.authmethod == u'anonymous':
        runner.run(ManagementAnonymousClientSession)
    else:
        raise Exception('logic error')

    return_code = extra[u'return_code']
    if isinstance(return_code, int) and return_code != 0:
        sys.exit(return_code)
예제 #32
0
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='Enable debug output.')
    parser.add_argument(
        '--url',
        dest='url',
        type=str,
        default=url,
        help='The router URL (default: "ws://localhost:8080/ws").')
    parser.add_argument('--realm',
                        dest='realm',
                        type=str,
                        default=realm,
                        help='The realm to join (default: "realm1").')

    args = parser.parse_args()

    # start logging
    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    # any extra info we want to forward to our ClientSession (in self.config.extra)
    extra = {u'foobar': u'A custom value'}

    # now actually run a WAMP client using our session class ClientSession
    runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra)
    runner.run(ClientSession)
예제 #33
0
from os import environ
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner


class MyComponent(ApplicationSession):
    @asyncio.coroutine
    def onJoin(self, details):
        # listening for the corresponding message from the "backend"
        # (any session that .publish()es to this topic).
        def onevent(msg):
            print("Got event: {}".format(msg))

        yield from self.subscribe(onevent, u'com.myapp.hello')

        # call a remote procedure.
        res = yield from self.call(u'com.myapp.add2', 2, 3)
        print("Got result: {}".format(res))


if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
        u"crossbardemo",
        debug=False,  # optional; log even more details
    )
    runner.run(MyComponent)
예제 #34
0
 def run(self, url="ws://127.0.0.1:8080/ws",
             realm="realm1", debug_wamp=False, debug=False):
     runner = ApplicationRunner(url, realm,
                                                  debug_wamp=debug_wamp,
                                                  debug=debug)
     runner.run(self)
예제 #35
0
            global done
            if not done:
                self.leave()  # Disconnect
            done = True

        subscribe_args = {"options": {"return": ["id", "name", "category"]}}

        # Subscribe to ak.wwise.core.object.created
        # Calls on_object_created whenever the event is received
        yield From(
            self.subscribe(on_object_created,
                           WAAPI_URI.ak_wwise_core_object_created,
                           **subscribe_args))

        print("Create an object in the Project Explorer")

    def onDisconnect(self):
        print("The client was disconnected.")
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    runner = ApplicationRunner(url=u"ws://127.0.0.1:8080/waapi",
                               realm=u"get_ancestors_demo")
    try:
        runner.run(MyComponent)
    except Exception as e:
        print(
            type(e).__name__ +
            ": Is Wwise running and Wwise Authoring API enabled?")
예제 #36
0
파일: test.py 프로젝트: greizgh/lockr
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
from asyncio import coroutine


class TestComponent(ApplicationSession):
    @coroutine
    def onJoin(self, details):
        print("session ready")

        try:
            res = yield from self.call('lockr.seat.get_id')
            print("call result: {}".format(res))
        except Exception as e:
            print("call error: {0}".format(e))


if __name__ == '__main__':
    runner = ApplicationRunner(url='ws://localhost:8080/ws', realm='lockr')
    runner.run(TestComponent)
예제 #37
0
    @locked
    async def cancel_reservation(self, token, details=None):
        if not isinstance(token, str):
            return False
        if token not in self.reservations:
            return False
        del self.reservations[token]
        self.schedule_reservations()
        return True

    @locked
    async def poll_reservation(self, token, details=None):
        try:
            res = self.reservations[token]
        except KeyError:
            return None
        res.refresh()
        return res.asdict()

    @locked
    async def get_reservations(self, details=None):
        return {k: v.asdict() for k, v in self.reservations.items()}

if __name__ == '__main__':
    runner = ApplicationRunner(
        url=environ.get("WS", u"ws://127.0.0.1:20408/ws"),
        realm="realm1",
    )
    runner.run(CoordinatorComponent)
예제 #38
0
파일: sender.py 프로젝트: om26er/wamp-shell
                threading.Thread(target=self.actually_run_command,
                                 args=(cmd, )).start()
            else:
                self.publish("io.crossbar.command.stdout", key)
        else:
            self.buffer += key
            self.publish("io.crossbar.command.on_key", key)

    def actually_run_command(self, cmd):
        process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
        self.stdout.append("{}:$ {}".format(self.name, cmd))
        for line in process.stdout:
            self.stdout.append(line.decode().strip())

    async def start_publishing(self):
        while len(self.stdout) > 0:
            self.publish("io.crossbar.command.stdout", self.stdout.popleft())
        while len(self.stdout) == 0:
            await asyncio.sleep(0.2)
        await self.start_publishing()

    async def onJoin(self, details):
        await self.register(self.get_prompt, "io.crossbar.command.id")
        await self.register(self.process_key, "io.crossbar.command.send_key")
        await self.start_publishing()


if __name__ == '__main__':
    runner = ApplicationRunner("ws://localhost:8080/ws", "realm1")
    runner.run(STDOutSession)
예제 #39
0
파일: client.py 프로젝트: ejoerns/labgrid
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-x',
        '--crossbar',
        metavar='URL',
        type=str,
        default="ws://127.0.0.1:20408/ws",
        help="crossbar websocket URL"
    )
    subparsers = parser.add_subparsers(dest='command')

    place_parser = argparse.ArgumentParser(add_help=False)
    if 'PLACE' in os.environ:
        place_parser.add_argument(
            '-p',
            '--place',
            type=str,
            required=False,
            default=os.environ.get('PLACE')
        )
    else:
        place_parser.add_argument('-p', '--place', type=str, required=True)

    subparser = subparsers.add_parser('resources')
    subparser.add_argument('-a', '--acquired', action='store_true')
    subparser.set_defaults(func=ClientSession.print_resources)

    subparser = subparsers.add_parser('places')
    subparser.add_argument('-a', '--acquired', action='store_true')
    subparser.set_defaults(func=ClientSession.print_places)

    subparser = subparsers.add_parser('add-place')
    subparser.set_defaults(func=ClientSession.add_place)
    subparser.add_argument('place')

    subparser = subparsers.add_parser('del-place')
    subparser.set_defaults(func=ClientSession.del_place)
    subparser.add_argument('place')

    subparser = subparsers.add_parser('add-alias', parents=[place_parser])
    subparser.add_argument('alias')
    subparser.set_defaults(func=ClientSession.add_alias)

    subparser = subparsers.add_parser('del-alias', parents=[place_parser])
    subparser.add_argument('alias')
    subparser.set_defaults(func=ClientSession.del_alias)

    subparser = subparsers.add_parser('set-comment', parents=[place_parser])
    subparser.add_argument('comment')
    subparser.set_defaults(func=ClientSession.set_comment)

    subparser = subparsers.add_parser('add-match', parents=[place_parser])
    subparser.add_argument('pattern')
    subparser.set_defaults(func=ClientSession.add_match)

    subparser = subparsers.add_parser('del-match', parents=[place_parser])
    subparser.add_argument('pattern')
    subparser.set_defaults(func=ClientSession.del_match)

    subparser = subparsers.add_parser('acquire', parents=[place_parser])
    subparser.set_defaults(func=ClientSession.acquire)

    subparser = subparsers.add_parser('release', parents=[place_parser])
    subparser.set_defaults(func=ClientSession.release)

    subparser = subparsers.add_parser('env', parents=[place_parser])
    subparser.set_defaults(func=ClientSession.env)

    subparser = subparsers.add_parser('power', parents=[place_parser])
    subparser.add_argument('action', choices=['on', 'off', 'cycle', 'get'])
    subparser.set_defaults(func=ClientSession.power)

    subparser = subparsers.add_parser('connect', parents=[place_parser])
    subparser.add_argument('-l', '--loop', action='store_true')
    subparser.set_defaults(func=ClientSession.connect)

    #subparser = subparsers.add_parser('attach', parents=[place_parser])
    #subparser.set_defaults(func=ClientSession.attach)

    args = parser.parse_args()

    extra = {
        'args': args,
    }

    if args.command:
        extra['loop'] = loop = asyncio.get_event_loop()
        #loop.set_debug(True)
        runner = ApplicationRunner(
            url=args.crossbar, realm="realm1", extra=extra
        )
        runner.run(ClientSession)
    else:
        parser.print_usage()
예제 #40
0
from os import environ
from autobahn.wamp.types import CallResult
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner


class Component(ApplicationSession):
    """
    Application component that calls procedures which
    produce complex results and showing how to access those.
    """

    async def onJoin(self, details):

        res = await self.call('com.myapp.add_complex', 2, 3, 4, 5)
        print("Result: {} + {}i".format(res.kwresults['c'], res.kwresults['ci']))

        res = await self.call('com.myapp.split_name', 'Homer Simpson')
        print("Forname: {}, Surname: {}".format(res.results[0], res.results[1]))

        self.leave()

    def onDisconnect(self):
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws")
    realm = "crossbardemo"
    runner = ApplicationRunner(url, realm)
    runner.run(Component)
예제 #41
0
def timeserverNow():
    return datetime.datetime.now()


def computeCtrPredictionModel(adImpressions):
    # TODO: Implement Logic
    """
    Features:
    1. Timestamp: Hashed with 8 categorical values
    2. Cosine Similarity: Search Phrases & Ad Target Phrases
    3. Search Phrase: Hashed with n categorical values
    4. Ad ID: Hashed with n categorical values, where n = count(ad) where ad.impressions > threshold
    """

    return 100


def computeCpm(searchPhrases, qualifyingAds, currentTime):
    # TODO: Implement Logic
    return 100


class RegisterProcedure(ApplicationSession):
    def onJoin(self, details):
        self.register(timeserverNow, 'com.timeserver.now')
        self.register(computeCtrPredictionModel, 'compute.ctr')
        self.register(computeCpm, 'compute.cpm')


runner = ApplicationRunner(url=CROSSBAR_URL, realm=CROSSBAR_REALM)
runner.run(RegisterProcedure)
예제 #42
0
# -*- coding: utf-8 -*-
'''
    Se conecta al router wamp y hace correr el Wamp de Users
'''

import inject
inject.configure()

if __name__ == '__main__':

    import sys
    import logging
    sys.path.insert(0, '../python')

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger().setLevel(logging.DEBUG)

    from autobahn.asyncio.wamp import ApplicationRunner
    from actions.systems.tutors.tutors import TutorsWamp
    from model.registry import Registry

    reg = inject.instance(Registry)
    registry = reg.getRegistry('wamp')
    url = registry.get('url')
    realm = registry.get('realm')
    debug = registry.get('debug')

    runner = ApplicationRunner(url=url, realm=realm)
    runner.run(TutorsWamp)
예제 #43
0
            s = memcache.Client(["127.0.0.1:11211"])
            keytext = sessDetails.realm + '.' + topic
            obj = s.get(keytext) # try get cached topic object
            if obj != None:
                print('backend re-publishing armote.trap.reedsensor', obj)
                #self.publish(topic, obj)
                return obj

        try:
            yield from asyncio.async(self.register(lastEvent, u'armote.trap.reedsensorLast'))
            print("procedure registered")
        except Exception as e:
            print("could not register procedure: {0}".format(e))
	   
        yield from asyncio.async(coap_request(self,sessDetails))

if __name__ == '__main__':
	
    wampAddress = u"ws://192.168.1.11:8080/ws"
    wampRealm = u"trapsensor"

    runner = ApplicationRunner(
        #environ.get("AUTOBAHN_TRAPSENSOR_ROUTER", u"ws://192.168.1.112:8080/ws"),
        wampAddress,
        realm = wampRealm,
        debug_wamp=False,  # optional; log many WAMP sessDetails
        debug=False,  # optional; log even more sessDetails
    )
    runner.run(AppSession)

예제 #44
0
파일: app.py 프로젝트: bercab/crossbartest

if __name__ == '__main__':

    # Crossbar.io connection configuration
    url = os.environ.get('CBURL', u'ws://localhost:8080/ws')
    realm = os.environ.get('CBREALM', u'realm1')

    # parse command line parameters
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output.')
    parser.add_argument('--url', dest='url', type=six.text_type, default=url, help='The router URL (default: "ws://localhost:8080/ws").')
    parser.add_argument('--realm', dest='realm', type=six.text_type, default=realm, help='The realm to join (default: "realm1").')

    args = parser.parse_args()

    # start logging
    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    # any extra info we want to forward to our ClientSession (in self.config.extra)
    extra = {
        u'foobar': u'A custom value'
    }

    # now actually run a WAMP client using our session class ClientSession
    runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra)
    runner.run(Component1)
예제 #45
0
def main():
    signal.signal(signal.SIGINT, signal_handler)
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
예제 #46
0
# -*- coding: utf-8 -*-
'''
    Se conecta al router wamp y hace correr el Wamp del Digesto
'''
if __name__ == '__main__':

    import sys, logging, inject
    sys.path.insert(0,'../python')

    logging.basicConfig(level=logging.DEBUG)

    from autobahn.asyncio.wamp import ApplicationRunner
    from model.config import Config
    from actions.systems.digesto.digesto import WampDigesto

    def config_injector(binder):
        binder.bind(Config,Config('server-config.cfg'))

    inject.configure(config_injector)
    config = inject.instance(Config)

    url = config.configs['server_url']
    realm = config.configs['server_realm']
    debug = config.configs['server_debug']

    runner = ApplicationRunner(url=url,realm=realm,debug=debug, debug_wamp=debug, debug_app=debug)
    runner.run(WampDigesto)
예제 #47
0
 def run(self):
     url = app.config['CROSSBAR_URL']
     realm = app.config['CROSSBAR_REALM']
     runner = ApplicationRunner(url=url, realm=realm)
     runner.run(notifier)
예제 #48
0
            yield from self.register(current_frames, key+'.frames.state')

            def set_frames(frames, animation=anim):
                clean = lambda x: 0 if x is None else max(0, min(255, int(x)))
                animation.frames = map(clean, frames)
            yield from self.register(set_frames, key+'.frames.set')

            @anim.on_change
            def publish_anim(animation):
                key = "animation.%s" % animation.name
                self.publish(key+'.loop', animation.looping)
                self.publish(key+'.play', animation.playing)
                self.publish(key+'.fps', animation.fps)
                self.publish(key+'.frames', animation.frames)

    @asyncio.coroutine
    def onJoin(self, details):
        self.hal = HAL(HALFS_ROOT)
        yield from self.register(self.tree, u'tree')
        yield from self.register_switchs()
        yield from self.register_triggers()
        yield from self.register_animations()
        yield from self.register_rgbs()
        self.hal.install_loop()
        yield from self.periodic_tasks()


if __name__ == '__main__':
    runner = ApplicationRunner(WAMP_BROKER, WAMP_REALM, debug_wamp=DEBUG)
    runner.run(Component)
예제 #49
0
    @asyncio.coroutine
    def time_teller(self):
        while True:
            time_now = str(datetime.now().replace(microsecond=0))
            self.publish('com.myapp.the_time', time_now)
            yield from asyncio.sleep(2)

    @wrap_in_future  # the signal handler can't call a coroutine directly so we wrap it in a future
    @asyncio.coroutine
    def exit_cleanup(self):
        print("closing_time")

        # do some cleaning, wait for subprocess/coroutines to complete..,
        yield from asyncio.sleep(5)

        loop = asyncio.get_event_loop()
        for task in asyncio.Task.all_tasks():
            # this is to avoid the cancellation of this coroutine because this coroutine need to be the last one running
            # to cancel all the others.
            if task is not asyncio.Task.current_task():
                task.cancel()

        print("everything has been cancelled")
        loop.stop()


if __name__ == "__main__":
    runner = ApplicationRunner(url="ws://127.0.0.1:8080/ws", realm="realm1",
                               extra={'key': 'value that will be passed to MyBackend'})
    runner.run(MyBackend)
예제 #50
0
class API:
    # http
    public_url = "https://poloniex.com/public"
    private_url = "https://poloniex.com/tradingApi"
    topic = None
    limiter = None
    max_calls = 6
    max_period = 60
    secrets = None

    # wamp
    ws_uri = "wss://api.poloniex.com"
    ws_realm = "realm1"
    runner = None
    callback = None

    class RunningAPI(ApplicationSession):
        async def onJoin(self, details):
            await self.subscribe(self.callback, self.topic)

    def __init__(self, config: ConfigObj or dict() = {}):
        self.secrets = config
        self.limiter = RateLimiter(max_calls=self.max_calls,
                                   period=self.max_period)
        self.runner = ApplicationRunner(self.ws_uri, self.ws_realm)

    # WAMP Streaming API

    def subscribe(self, topic: str, callback: callable):
        self.callback = callback
        self.topic = topic
        self.runner.run(API.RunningAPI())

    # Public HTTP API, no credentials needed.

    def returnTicker(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def return24Volume(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def returnOrderBook(self, currencyPair: str = 'BTC_NXT', depth: int = 10):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnTradeHistory(self,
                           currencyPair: str = 'BTC_NXT',
                           start: int = 1410158341,
                           end: int = 1410499372):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnChartData(self,
                        currencyPair: str = 'BTC_NXT',
                        start: int = 1405699200,
                        end: int = 9999999999,
                        period: int = 14400):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnCurrencies(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def returnLoanOrders(self, currency: str = 'BTC'):
        return self._call(sys._getframe().f_code.co_name, locals())

    # Private HTTP API Methods, Require API Key, and Secret on INIT

    def returnBalances(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def returnCompleteBalances(self, account: str = 'all'):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnDepositAddresses(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def generateNewAddress(self, currency: str = 'BTC'):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnDepositsWithdrawals(self,
                                  start: int = 1410158341,
                                  end: int = 1410499372):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnOpenOrders(self, currencyPair: str = 'BTC_XCP'):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnOrderTrades(self, orderNumber: int = None):
        return self._call(sys._getframe().f_code.co_name, locals())

    def buy(self, rate: float, amount: float, currencyPair: str,
            fillOrKill: int, immediateOrCancel: int, postOnly: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def sell(self, rate: float, amount: float, currencyPair: str,
             fillOrKill: int, immediateOrCancel: int, postOnly: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def cancelOrder(self, orderNumber: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def moveOrder(self, orderNumber: int, rate: float, amount: float,
                  immediateOrCancel: int, postOnly: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def withdraw(self, currency: str, amount: float, address: str,
                 paymentId: str):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnFeeInfo(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def returnAvailableAccountBalances(self, account: str = 'all'):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnTradableBalances(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def transferBalance(self, currency: str, amount: float, fromAccount: str,
                        toAccount: str):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnMarginAccountSummary(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def marginBuy(self, currencyPair: str, rate: float, amount: float):
        return self._call(sys._getframe().f_code.co_name, locals())

    def marginSell(self, currencyPair: str, rate: float, amount: float):
        return self._call(sys._getframe().f_code.co_name, locals())

    def getMarginPosition(self, currencyPair: str):
        return self._call(sys._getframe().f_code.co_name, locals())

    def closeMarginPosition(self, currencyPair: str):
        return self._call(sys._getframe().f_code.co_name, locals())

    def createLoanOffer(self, currency: str, amount: float, duration: int,
                        autoRenew: int, lendingRate: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def cancelLoanOffer(self, orderNumber: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def returnOpenLoanOffers(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def returnActiveLoans(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def returnLendingHistory(self):
        return self._call(sys._getframe().f_code.co_name, {})

    def toggleAutoRenew(self, orderNumber: int):
        return self._call(sys._getframe().f_code.co_name, locals())

    def _call(self, topic: str, args: dict() = {}):
        if topic in [
                'returnTicker', 'return24Volume', 'returnOrderBook',
                'returnTradeHistory', 'returnChartData', 'returnCurrencies',
                'returnLoanOrders'
        ]:
            api = [self.public_url, 'get', topic]
        else:
            api = [self.private_url, 'post', topic, self.secrets]

        def __call(api_details, uri):
            request = getattr(requests, api_details[1])
            headers = {}
            del uri['self']
            uri['command'] = api_details[2]
            if api_details[2] == 'post':
                uri['nonce'] = int(time.time() * 1000)
                sign = hmac.new(api_details[3]['secret'], uri,
                                hashlib.sha512).hexdigest()
                headers['Sign'] = sign
                headers['Key'] = api_details[3]['api_key']
            return json.loads(
                request(api_details[0], uri, headers=headers).content.decode())

        with self.limiter:
            return __call(api, args)
예제 #51
0
def main():
    ws = initialize_component()
    # secret = read_secret()
    runner = ApplicationRunner(ws, u"realm1")
    runner.run(AppSession)
예제 #52
0
class MyComponent(ApplicationSession):
    def onJoin(self, details):
        try:
            res = yield From(self.call(
                WAAPI_URI.ak_wwise_core_getinfo))  # RPC call without arguments
        except Exception as ex:
            print("call error: {}".format(ex))
        else:
            # Call was successful, displaying information from the payload.
            print(
                "Hello {} {}".format(res.kwresults['displayName'],
                                     res.kwresults['version']['displayName']))

        self.leave()

    def onDisconnect(self):
        print("The client was disconnected.")
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    runner = ApplicationRunner(url=u"ws://127.0.0.1:8080/waapi",
                               realm=u"realm1")
    try:
        runner.run(MyComponent)
    except Exception as e:
        print(
            type(e).__name__ +
            ": Is Wwise running and Wwise Authoring API enabled?")
예제 #53
0
def main():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
예제 #54
0
        return order_book

      quote = "CNY"
      base = "BTS"
      order_book_last = {}
      while True:
        try:
          order_book = get_order_book(quote,base)
          if (order_book_last != order_book):
            order_book_last = order_book
            #print("update now")
            #pprint(order_book)
            self.mypublish(u'btsbots.demo.order_book_%s_%s'%(quote,base), order_book)
          #else:
            #print("don't need update")
        except Exception as e:
          print(e)
        yield from sleep(10)

   def onLeave(self, details):
      print("onLeave: {}".format(details))
      self.disconnect()

   def onDisconnect(self):
      self.IsConnect = False
      print("onDisconnect: {}".format(details))

runner = ApplicationRunner(url = config_wamp["url"], realm = config_wamp["realm"])
runner.run(MyComponent)

예제 #55
0
def make(config):
    ##
    # This component factory creates instances of the
    # application component to run.
    ##
    # The function will get called either during development
    # using the ApplicationRunner below, or as  a plugin running
    # hosted in a WAMPlet container such as a Crossbar.io worker.
    ##
    if config:
        return Component1(config)
    else:
        # if no config given, return a description of this WAMPlet ..
        return {'label': 'Awesome WAMPlet 1',
                'description': 'This is just a test WAMPlet that provides some procedures to call.'}


if __name__ == '__main__':
    from autobahn.asyncio.wamp import ApplicationRunner

    # test drive the component during development ..
    runner = ApplicationRunner(
        url="ws://127.0.0.1:8080/ws",
        realm="realm1",
        debug=False,  # low-level WebSocket debugging
        debug_wamp=False,  # WAMP protocol-level debugging
        debug_app=True)  # app-level debugging

    runner.run(make)
예제 #56
0

class Component(ApplicationSession):
    """
    An application component calling the different backend procedures.
    """

    async def onJoin(self, details):

        def on_event(val):
            print("Someone requested to square non-positive: {}".format(val))

        await self.subscribe(on_event, u'com.myapp.square_on_nonpositive')

        for val in [2, 0, -2]:
            res = await self.call(u'com.myapp.square', val, options=CallOptions())
            print("Squared {} = {}".format(val, res))

        await self.leave()

    def onDisconnect(self):
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
        u"crossbardemo",
    )
    runner.run(Component)
예제 #57
0
from os import environ
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner

class MyComponent(ApplicationSession):
    @asyncio.coroutine
    def onJoin(self, details):
        # listening for the corresponding message from the "backend"
        # (any session that .publish()es to this topic).
        def onevent(msg):
            print("Got event: {}".format(msg))
        yield from self.subscribe(onevent, 'com.myapp.hello')

        # call a remote procedure.
        res = yield from self.call('com.myapp.add2', 2, 3)
        print("Got result: {}".format(res))


if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws"),
        u"crossbardemo",
        debug_wamp=False,  # optional; log many WAMP details
        debug=False,  # optional; log even more details
    )
    runner.run(MyComponent)
예제 #58
0
import asyncio
import uvloop
from autobahn.asyncio.wamp import ApplicationRunner

from readserial import Output, create_serial_connection
from sendreadings import MyComponent
import functools

ARDUINO = '/dev/ttyACM0'
SPEED = 115200
commqueue = asyncio.Queue()

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    coro = create_serial_connection(loop, Output, commqueue, ARDUINO ,baudrate=SPEED)
    try:
        #loop.run_until_complete(coro)
        runner = ApplicationRunner(url=u"ws://localhost:8080/ws", realm=u"realm1", extra={"commqueue":commqueue})
        import ipdb
        ipdb.set_trace()
        asyncio.ensure_future(coro, loop=loop)
        runner.run(MyComponent)
    except KeyboardInterrupt as e:
        print("Caught keyboard interrupt.")
        loop.run_forever()
    finally:
        loop.close()

예제 #59
0
        user = yield from self.call('users.findByDni', dni)
        
        userEmail = {
          'user_id': user["id"],
          'email': email,
          'confirmed': False
        }
        
        emailId = yield from self.call('users.mails.persistMail', userEmail)

        yield from self.call('users.mails.sendEmailConfirmation', emailId)

        sys.exit("***** Email alternativo agregado: " + user["name"] + " " + user["lastname"] + " " + email + " (" + emailId + ")")
        


if __name__ == '__main__':

        from autobahn.asyncio.wamp import ApplicationRunner
        from autobahn.wamp.serializer import JsonSerializer


        url = config.configs['server_url']
        realm = config.configs['server_realm']
        debug = config.configs['server_debug']

        json = JsonSerializer()
        runner = ApplicationRunner(url=url,realm=realm,debug=debug, debug_wamp=debug, debug_app=debug, serializers=[json])
        runner.run(WampMain)
예제 #60
0
    """
    An application component calling the different backend procedures.
    """
    @asyncio.coroutine
    def onJoin(self, details):
        def on_event(val):
            print("Someone requested to square non-positive: {}".format(val))

        yield from self.subscribe(on_event, 'com.myapp.square_on_nonpositive')

        for val in [2, 0, -2]:
            res = yield from self.call('com.myapp.square',
                                       val,
                                       options=CallOptions(disclose_me=True))
            print("Squared {} = {}".format(val, res))

        self.leave()

    def onDisconnect(self):
        asyncio.get_event_loop().stop()


if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", "ws://localhost:8080/ws"),
        u"crossbardemo",
        debug_wamp=False,  # optional; log many WAMP details
        debug=False,  # optional; log even more details
    )
    runner.run(Component)