コード例 #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)
コード例 #2
0
    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
ファイル: async.py プロジェクト: aleneum/kogniserver
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
ファイル: base.py プロジェクト: lspestrip/striptease
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()
コード例 #11
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)
コード例 #12
0
                        help='Enable debug output.')
    parser.add_argument(
        '--url',
        dest='url',
        type=six.text_type,
        default=u'ws://104.199.76.81:8080/ws',
        help='The router URL (default: "ws://localhost:8080/ws").')
    #    parser.add_argument('--router', type=six.text_type,default=u'ws://104.199.76.81:8080/ws',help='WAMP router URL.')

    #    parser.add_argument('--realm',type=six.text_type, default='realm1',help='WAMP router realm.')
    parser.add_argument('--realm',
                        dest='realm',
                        type=six.text_type,
                        default='realm1',
                        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)
コード例 #13
0
        def ping():
            return

        def add2(a, b):
            return a + b

        def stars(nick="somebody", stars=0):
            return u"{} starred {}x".format(nick, stars)

        # noinspection PyUnusedLocal
        def orders(product, limit=5):
            return [u"Product {}".format(i) for i in range(50)][:limit]

        def arglen(*args, **kwargs):
            return [len(args), len(kwargs)]

        await self.register(ping, u'com.arguments.ping')
        await self.register(add2, u'com.arguments.add2')
        await self.register(stars, u'com.arguments.stars')
        await self.register(orders, u'com.arguments.orders')
        await self.register(arglen, u'com.arguments.arglen')
        print("Registered methods; ready for frontend.")


if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
        u"crossbardemo",
    )
    runner.run(Component)
コード例 #14
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)
コード例 #15
0
            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)
コード例 #16
0
ファイル: driver.py プロジェクト: RustamSitdikov/poloniex
def main():
    signal.signal(signal.SIGINT, signal_handler)
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
コード例 #17
0
ファイル: crepebot_plugin.py プロジェクト: tomsimonart/GLM
    @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)
コード例 #18
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)
コード例 #19
0
sys.path.insert(0,'../../python')

logging.basicConfig(level=logging.DEBUG)

from model.config import Config

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

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


'''
    Ejecuta el protocolo Wamp del sincronizador
'''
if __name__ == '__main__':

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


    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(WampSync)
コード例 #20
0
def main():
    runner = ApplicationRunner(url="ws://localhost:8080/ws", realm="realm1")
    runner.run(ClientSession)
コード例 #21
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)
コード例 #22
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()
コード例 #23
0
ファイル: runner.py プロジェクト: axelniklasson/adalyzer
 def run(self):
     runner = ApplicationRunner(url=u"ws://api.interchange.ericsson.net/v1", realm=u"interchange")
     runner.run(self.Component)
コード例 #24
0
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)
コード例 #25
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)
コード例 #26
0
#!/usr/bin/env python

import sys
import argparse

from autobahn.asyncio.wamp import ApplicationRunner

from light.autobahn.backend import BackendComponent
from light.database import DatabaseSpecifier

if sys.version_info < (3, 3):
    raise Exception('The light matter autobahn code needs Python 3.3 or '
                    'later.')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=('Start a WAMP-based distributed light-matter database '
                     'backend.'))

    databaseSpecifier = DatabaseSpecifier(allowInMemory=False)
    databaseSpecifier.addArgsToParser(parser)
    args = parser.parse_args()

    runner = ApplicationRunner(args.wampUrl, args.realm, extra=dict(args=args))
    runner.run(BackendComponent)
コード例 #27
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)
コード例 #28
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)
コード例 #29
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)
コード例 #30
0
'''
    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.issue.issue import WampIssue

    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(WampIssue)
コード例 #31
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)
コード例 #32
0
import sys
import asyncio

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

from .wamp import MyAuthenticator


DOMAIN = config('DOMAIN')
URL = f'wss://{DOMAIN}:443/ws'

runner = ApplicationRunner(URL, 'world')
runner.run(MyAuthenticator)
コード例 #33
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)
コード例 #34
0
def main():
    # application runner continusely calls the  event
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")

    runner.run(PoloniexComponent)
コード例 #35
0
def main():
    runner = ApplicationRunner(u"wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
コード例 #36
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)
コード例 #37
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(
        '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,
    }

    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)
コード例 #38
0
ファイル: mainFiles.py プロジェクト: Cloudxtreme/angular
'''
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)
コード例 #39
0
ファイル: game.py プロジェクト: dylwhich/swadge-game-flaschen
                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')
コード例 #40
0
ファイル: server.py プロジェクト: greizgh/lockr
            self._locker_id = client
            self._free = False
            self.refresh()
            return True

    def unlock(self, client):
        """Release the resource

        Returns True if successfully released, False otherwise
        """
        if not self._free and client == self._locker_id:
            self._free = True
            self.refresh()
            return True
        else:
            return False

    @coroutine
    def onJoin(self, details):
        try:
            yield from self.register(self.get_id, 'lockr.seat.get_id')
            yield from self.register(self.lock, 'lockr.seat.lock')
            yield from self.register(self.unlock, 'lockr.seat.unlock')
            yield from self.subscribe(self.refresh, 'lockr.seat.refresh')
        except Exception as e:
            print("Register error: {}".format(e))

if __name__ == '__main__':
    runner = ApplicationRunner(url='ws://localhost:8080/ws', realm='lockr')
    runner.run(SeatComponent)
コード例 #41
0
    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
        logging.debug('instanciando WampMain')
        ApplicationSession.__init__(self, config)

    @coroutine
    def onJoin(self, details):
        mails = yield from self.call('users.mails.findMails',
                                     'd44e92c1-d277-4a45-81dc-a72a76f6ef8d')

        logging.info("********** EMAILS **********")
        for mail in mails:
            logging.info(mail)


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)
コード例 #43
0
ファイル: CoAPbackend.py プロジェクト: Suretronic/trap
            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
ファイル: mainOffice.py プロジェクト: Cloudxtreme/angular
'''
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.offices.offices import OfficesWamp

    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(OfficesWamp)
コード例 #45
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)
コード例 #46
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)
コード例 #47
0
ファイル: manage.py プロジェクト: kuc2477/anchor-backend
 def run(self):
     url = app.config['CROSSBAR_URL']
     realm = app.config['CROSSBAR_REALM']
     runner = ApplicationRunner(url=url, realm=realm)
     runner.run(notifier)
コード例 #48
0
ファイル: poloniexWs.py プロジェクト: cmaliwal/coin-scanner
def connectPoloniex():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
コード例 #49
0
ファイル: Wamp_Backend.py プロジェクト: icefo/PyQt5-Wamp
    @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 Poloniex(object):
    def __init__(self, config_file_path=None, api_key=None, secret=None):
        '''
		Constructor. You can instantiate this class with either file path or with all three values that would otherwise
		 be found in the config file.
		:param config_file_path: path to the file with the config
		:param api_key: API key found on https://www.poloniex.com/apiKeys/
		:param secret: Secret found on https://www.poloniex.com/apiKeys/ (disappears after some time)
		:return: The client object
		'''
        # None of the parameters are necessary, but to work properly, we need at least one pair from one source
        if config_file_path is None and (api_key is None or secret is None):
            raise Exception(
                'You need to pass either config_file_path parameter or all of api_key and secret'
            )

        if config_file_path is not None:
            self.api_key, self.secret = self.__get_credentials(
                config_file_path)
        else:
            self.api_key = api_key
            self.secret = secret

        # Rather do it once instead of at every signing
        self.secret = self.secret.encode('utf8')

        # If still not api key and no secret, raise
        if self.api_key is None or self.api_key.strip(
        ) == '' or self.secret is None or self.secret.strip() == '':
            raise Exception('No credentials were found')

        self.api_endpoint = 'https://api.poloniex.com/'
        self.private_api_endpoint = 'https://www.poloniex.com/'

        # Init the runner to None
        self.runner = None
        self.websockets_endpoint = 'wss://api.poloniex.com/'

    def __str__(self):
        '''
		Two API clients are the same if they use the same credentials. They must behave equally in respect to all the calls.
		:return: None
		'''
        return json.dumps([self.api_key, self.secret])

    def __eq__(self, other):
        return str(self) == str(other)

    def __ne__(self, other):
        return str(self) != str(other)

    def __get_credentials(self, config_file_path):
        '''
		This method will try to interpret the file on the path in one of three ways:
		* first it will try to interpret it as an ini file (regardless of the file extension)
		* then it will try to interpret it as a JSON file (regardless of the file extension)
		* lastly it will try to interpret it as a Python file (file extension must be py)
		:param config_file_path: absolute path to the config file
		:return: api key, secret and customer id (tuple)
		'''
        api_key = None
        secret = None

        # All of the following tries catch all exceptions that can occur (as there are plenty): missing file,
        # wrong type, misconfigured.
        try:
            config_parser = ConfigParser()
            config_parser.read(config_file_path)
            api_key = config_parser.get('CONFIG', 'apiKey')
            secret = config_parser.get('CONFIG', 'secret')
            return api_key, secret
        except:
            pass

        try:
            with open(config_file_path, 'rb') as file:
                blob = json.loads(file.read().decode())
                api_key = blob.get('apiKey')
                secret = blob.get('secret')
            return api_key, secret
        except:
            pass

        # This is deprecated in python 3.4 (but it will work), so if working with later, try using ini or json approaches instead
        try:
            import importlib.machinery

            loader = importlib.machinery.SourceFileLoader(
                'poloniex.config', config_file_path)
            config = loader.load_module()

            api_key = config.api_key
            secret = config.secret
            return api_key, secret
        except:
            pass

        if api_key is None or secret is None:
            raise Exception(
                'While the config file was found, it was not configured correctly. Check for examples here: {}'
                .format(EXAMPLES_URL))

        return api_key, secret

    def __prepare_request_data(self, params):
        '''
		Returns the signature for the next REST API call. nonce will be a timestamp (time.time()) multiplied by 1000,
		so we include some of the decimal part to reduce the chance of sending the same one more than once.
		:param params - python dict that includes all the parameters for the call
		:return: encoded params, header with signature
		'''
        params['nonce'] = int(time.time() * 1000)
        encoded_params = urllib.parse.urlencode(params).encode('utf8')
        headers = {
            'Sign':
            hmac.new(self.secret, encoded_params, hashlib.sha512).hexdigest(),
            'Key':
            self.api_key
        }
        return params, headers

    def ticker(self):
        '''
		This method will call ticker resource and return the result.
		:return: ticker blob (dict)
		'''
        resource = 'public'
        params = {
            'command': 'returnTicker',
        }

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def daily_volume(self):
        '''
		This method will call return last 24 hour volume for all the currency pairs.
		:return: volume blob (dict)
		'''
        resource = 'public'
        params = {
            'command': 'return24hVolume',
        }

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def currencies(self):
        '''
		This method will call return information about all the tradable currencies
		:return: volume blob (dict)
		'''
        resource = 'public'
        params = {
            'command': 'returnCurrencies',
        }

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def order_book(self, pair=None, depth=10):
        '''
		This method will call return last 24 hour volume for all the currency pairs.
		:pair - currency pair for the order book
		:depoth - depth of the order book
		:return: volume blob (dict)
		'''
        resource = 'public'
        params = {'command': 'returnOrderBook', 'depth': depth}

        if pair is not None:
            params['currencyPair'] = pair

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def trade_history(self, pair, start, end):
        '''
		This method will call return last 24 hour volume for all the currency pairs.
		:pair - currency pair for the trade history
		:start - Unix timestamp of the start of the interval
		:end - Unix timestamp of the end of the interval
		:return: volume blob (dict)
		'''
        resource = 'public'
        params = {
            'command': 'returnOrderBook',
            'pair': pair,
            'start': start,
            'end': end,
        }

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def chart_data(self, pair, start, end, period=CANDLE_PERIOD_14400):
        '''
		This method will call return last 24 hour volume for all the currency pairs.
		:pair - currency pair for the trade history
		:start - Unix timestamp of the start of the interval
		:end - Unix timestamp of the end of the interval
		:period - period for the candle representation
		:return: volume blob (dict)
		'''
        resource = 'public'
        params = {
            'command': 'returnOrderBook',
            'pair': pair,
            'start': start,
            'end': end,
            'period': period,
        }

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def loan_orders(self, currency):
        '''
		This method will call return last 24 hour volume for all the currency pairs.
		:currency - currency for which to return loan orders
		:return: volume blob (dict)
		'''
        resource = 'public'
        params = {
            'command': 'returnLoanOrders',
            'currency': currency,
        }

        response = requests.get('{}{}'.format(self.api_endpoint, resource),
                                params=params)

        return json.loads(response.text)

    def balances(self):
        '''
		Returns a blob of all the balances the account holds
		:return: balances blob (dict)
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnBalances',
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def complete_balances(self):
        '''
		Returns a blob of all the balances the account holds, detailed
		:return: detailed balances blob (dict)
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnCompleteBalances',
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def deposit_addresses(self):
        '''
		Returns a blob of all the deposit addresses for all the currencies
		:return: addresses blob (dict)
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnDepositAddresses',
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def new_deposit_address(self, currency):
        '''
		Generates a new address for a specified currency
		:param currency: one of the supported currencies
		:return: blob that contains the new address under the key 'response'
		'''
        resource = 'tradingApi'
        params = {
            'command': 'generateNewAddress',
            'currency': currency,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def deposits_and_withdrawals(self, start, end):
        '''
		Returns a blob containing all deposits and withdrawals for all currencies
		:param start - Unix timestamp for start of the time interval
		:param end - Unix timestamp for end of the time interval
		:return: blob that contains all deposits and withdrawals
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnDepositsWithdrawals',
            'start': start,
            'end': end,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def open_orders(self, pair='all'):
        '''
		Returns a blob containing all deposits and withdrawals for all currencies
		:param pair - currency pair for which orders are to be fetched
		:return: blob that contains all the open orders for requested currency pairs
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnOpenOrders',
            'currencyPair': pair,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def user_trade_history(self, start, end, pair='all'):
        '''
		Returns a blob containing all trades for the selected currency pair (default timespan is day)
		:param start - Unix timestamp for start of the time interval
		:param end - Unix timestamp for end of the time interval
		:param pair - currency pair for which orders are to be fetched
		:return: blob that contains all the trades for the specified currency pair and timespan
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnTradeHistory',
            'currencyPair': pair,
            'start': start,
            'end': end,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def order_trades(self, order_id):
        '''
		Returns a blob containing all trades for the specified order. If no trades are present for the order or if order
		doesn't belong to the user calling, expect an error
		:param order_id - Order id
		:return: blob that contains all the trades for the specified order
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnOrderTrades',
            'orderNumber': order_id,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def cancel_order(self, order_id):
        '''
		Cancel an order
		:param order_id - Order id
		:return: blob that contains success or failure data
		'''
        resource = 'tradingApi'
        params = {
            'command': 'cancelOrder',
            'orderNumber': order_id,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def buy(self,
            currency_pair,
            rate,
            amount,
            post_only=1,
            fill_or_kill=0,
            immediate_or_cancel=0):
        '''
		Places a buy order
		:param currency_pair - Selected currency pair
		:param rate - rate or price for this order
		:param amount - amount of the counter that you wish to buy
		:return: blob that contains the placed order data
		'''
        resource = 'tradingApi'
        params = {
            'command': 'buy',
            'currencyPair': currency_pair,
            'rate': rate,
            'amount': amount,
            'fillOrKill': fill_or_kill,
            'immediateOrCancel': immediate_or_cancel,
            'postOnly': post_only,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def sell(self,
             currency_pair,
             rate,
             amount,
             post_only=1,
             fill_or_kill=0,
             immediate_or_cancel=0):
        '''
		Places a sell order
		:param currency_pair - Selected currency pair
		:param rate - rate or price for this order
		:param amount - amount of the counter that you wish to sell
		:return: blob that contains the placed order data
		'''
        resource = 'tradingApi'
        params = {
            'command': 'sell',
            'currencyPair': currency_pair,
            'rate': rate,
            'amount': amount,
            'fillOrKill': fill_or_kill,
            'immediateOrCancel': immediate_or_cancel,
            'postOnly': post_only,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def fee_info(self):
        '''
		Fetches fee data
		:return: blob that contains the fee data
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnFeeInfo',
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def available_balances(self, account='exchange'):
        '''
		Fetches available balance data
		:return: blob that contains the available balances
		'''
        resource = 'tradingApi'
        params = {
            'command': 'returnAvailableAccountBalances',
            'account': account,
        }

        params, headers = self.__prepare_request_data(params)
        response = requests.post('{}{}'.format(self.private_api_endpoint,
                                               resource),
                                 data=params,
                                 headers=headers)

        return json.loads(response.text)

    def attach_trollbox(self, callback):
        '''
		Attach your method to a websocket trollbox channel
		:param callback: this method should accept the following parameters: type, message number, username, message, reputation
		:return:
		'''
        def trollbox_wrapper(wrapped_callback):
            def wrapper(*args, **kwargs):
                message_type = args[0]
                message_number = args[1]
                username = args[2]
                message = args[3]
                reputation = args[4]

                wrapped_callback(message_type, message_number, username,
                                 message, reputation)

            return wrapper

        class Trollbox(ApplicationSession):
            def onJoin(self, details):
                yield self.subscribe(trollbox_wrapper(callback), 'trollbox')

        if self.runner is None:
            self.runner = ApplicationRunner(url=self.websockets_endpoint,
                                            realm='realm1')
        self.runner.run(Trollbox)

    def attach_ticker(self, callback):
        '''
		Attach your method to a websocket channel
		:param callback: this method should accept the following parameters: currency pair, last, lowest ask, highest bid, percent change, base volume, quote volume, is frozen, 24hr high, 24hr low
		:return:
		'''
        def ticker_wrapper(wrapped_callback):
            def wrapper(*args, **kwargs):
                currency_pair = args[0]
                last = decimal.Decimal(args[1])
                lowest_ask = decimal.Decimal(args[2])
                highest_bid = decimal.Decimal(args[3])
                change = decimal.Decimal(args[4])
                base_volume = decimal.Decimal(args[5])
                quote_volume = decimal.Decimal(args[6])
                is_frozen = args[7] == 1
                high = decimal.Decimal(args[8])
                low = decimal.Decimal(args[9])

                wrapped_callback(currency_pair, last, lowest_ask, highest_bid,
                                 change, base_volume, quote_volume, is_frozen,
                                 high, low)

            return wrapper

        class Ticker(ApplicationSession):
            def onJoin(self, details):
                yield self.subscribe(ticker_wrapper(callback), 'ticker')

        if self.runner is None:
            self.runner = ApplicationRunner(url=self.websockets_endpoint,
                                            realm='realm1')
        self.runner.run(Ticker)

    def attach_order_book(self, callback, currency_pair):
        '''
		Attach a method to a websocket channel for orderbook of your choice
		:param callback: this method should accept the following parameters: modifications, removals, trades, sequence
		:param currency_pair: the pair for which one wishes to follow the order book
		:return:
		'''
        def order_book_wrapper(wrapped_callback):
            def wrapper(*args, **kwargs):
                modifications = []
                removals = []
                trades = []
                for arg in args:
                    blob = {}
                    data = arg.get('data')

                    if arg.get('type') == 'orderBookModify':
                        blob = {
                            'amount': decimal.Decimal(data.get('amount')),
                            'rate': decimal.Decimal(data.get('rate')),
                            'type': data.get('type'),
                        }
                        modifications.append(blob)
                    elif arg.get('type') == 'orderBookRemove':
                        blob = {
                            'rate': decimal.Decimal(data.get('rate')),
                            'type': data.get('type'),
                        }
                        removals.append(blob)
                    else:  # New trade
                        blob = {
                            'tradeID':
                            data.get('tradeID'),
                            'rate':
                            decimal.Decimal(data.get('rate')),
                            'amount':
                            decimal.Decimal(data.get('amount')),
                            'total':
                            decimal.Decimal(data.get('total')),
                            'date':
                            datetime.datetime.strptime(data.get('date'),
                                                       '%Y-%m-%d %H:%M:%S'),
                            'type':
                            data.get('type'),
                        }
                        from pprint import pprint
                        pprint(blob)
                        trades.append(blob)

                wrapped_callback(modifications, removals, trades, **kwargs)

            return wrapper

        class OrderBook(ApplicationSession):
            def onJoin(self, details):
                yield self.subscribe(order_book_wrapper(callback),
                                     currency_pair)

        if self.runner is None:
            self.runner = ApplicationRunner(url=self.websockets_endpoint,
                                            realm='realm1')
        self.runner.run(OrderBook)
コード例 #51
0
ファイル: run.py プロジェクト: Tekkadan/iron-strategy-server
def main():
    ws = initialize_component()
    # secret = read_secret()
    runner = ApplicationRunner(ws, u"realm1")
    runner.run(AppSession)
コード例 #52
0
    async def orders_pending_initial(self):
        async with self.engine.acquire() as connection:
            pending_orders = await db_select_pending_orders(connection)
        print("Initial orders", pending_orders)
        return pending_orders

    async def onJoin(self, details):
        await self.register(self.order_create, u'order.create')
        await self.register(self.order_finish, u'order.finish')
        await self.register(self.stock_initial, u'stock.initial')
        await self.register(self.orders_pending_initial,
                            u'orders.pending.initial')
        self.engine = await create_engine(user=DB_USER, database=DB_NAME)
        async with self.engine.acquire() as connection:
            await db_create_tables(connection)

    async def _publish_stock(self):
        async with self.engine.acquire() as connection:
            stocks_by_product = await db_select_stock(connection)
        print("Publishing stock: {}".format(stocks_by_product))
        self.publish(u'stock.onchange', stocks_by_product)

    async def _publish_order(self, order):
        print("Publishing order: {}".format(order))
        self.publish(u'orders.onchange', order)


runner = ApplicationRunner(url=u"ws://localhost:8080/ws", realm=u"realm1")
runner.run(ServerComponent)
コード例 #53
0
ファイル: ticker.py プロジェクト: DuaneNielsen/poloniex
def main():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)
コード例 #54
0
ファイル: wamplitude.py プロジェクト: mameebox/mameebox
 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)
コード例 #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
config_file.close()

config_wamp = config["wamp_client"]

class MyComponent(ApplicationSession):

    @asyncio.coroutine
    def onJoin(self, details):
        quote = "CNY"
        base = "BTS"
        def print_order_book(order_book):
          print("order_bid:")
          for order in order_book["bid"]:
            print(order["price"], order["volume"], order["balance"])
          print("order_ask:")
          for order in order_book["ask"]:
            print(order["price"], order["volume"], order["balance"])
        def on_order_book(order_book, c=None):
          print_order_book(order_book)

        yield from self.subscribe(on_order_book, 'btsbots.demo.order_book_%s_%s'%(quote,base))

        res = yield from self.call('btsbots.get_last', 'btsbots.demo.order_book_%s_%s'%(quote,base))
        print_order_book(res)

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

runner = ApplicationRunner(url = config_wamp["url"], realm = config_wamp["realm"])
runner.run(MyComponent)
コード例 #57
0
ファイル: frontend.py プロジェクト: shuyunqi/AutobahnPython
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
 def start_publishing(self):
     runner = ApplicationRunner(url=u"wss://demo.crossbar.io/ws",
                                realm=u"realm1")
     runner.run(PublishStock.PublishStockRunner)
コード例 #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
'''
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.laboralinsertion.laboralInsertion import LaboralInsertionWamp

    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(LaboralInsertionWamp)