コード例 #1
0
    def start(self):
        update = task.LoopingCall(self.updateSchedule)
        update.start(600)  # Update from Google Calendar every 10 minutes

        execute = task.LoopingCall(self.execute)
        execute.start(60)  # Start and stop services every minute

        session_class = create_scheduler_session(self)

        component = make_component(session_class)
        run(component)

        self.log.info("Scheduler terminated.")
コード例 #2
0
    def start(self):
        if self.started:
            return
        super(StandaloneDVR, self).start()

        class MyDVRSession(DVRSession):
            def __init__(elf, config=None):
                super(MyDVRSession, elf).__init__(config, dvr=self)

        session_class = MyDVRSession
        component = make_component(session_class)
        run(component)
        self.log.info("DVR terminated.")
コード例 #3
0
    def start_rie_session(self, robot_name=None, robot_realm=None):
        try:
            if robot_realm is None:
                # get the realm from config
                name_key = "pepper" if robot_name is None else robot_name.lower(
                )
                robot_realm = config_helper.get_robot_settings(
                )["realm"][name_key]
            self.logger.info("{} REALM: {}".format(robot_name, robot_realm))

            self.rie = Component(transports=[{
                'url': u"wss://wamp.robotsindeklas.nl",
                'serializers': ['msgpack'],
                'max_retries': 0
            }],
                                 realm=robot_realm)
            self.logger.info("** {}".format(threading.current_thread().name))
            self.rie.on_join(self.on_connect)

            self.logger.info("Running the rie component")
            run([self.rie])
        except Exception as e:
            self.logger.error("Unable to run the rie component | {}".format(e))
コード例 #4
0
ファイル: index.py プロジェクト: Hrabal/autobahn-python
    ],
    realm=u"crossbardemo",
)

# 1. subscribe to a topic
@demo.subscribe(u'io.crossbar.demo.hello')
def hello(msg):
    print("Got hello: {}".format(msg))


# 2. register a procedure for remote calling
@demo.register(u'io.crossbar.demo.add2')
def add2(x, y):
    return x + y


# 3. after we've authenticated, run some code
@demo.on_join
async def joined(session, details):
    # publish an event (won't go to "this" session by default)
    session.publish('io.crossbar.demo.hello', 'Hello, world!')

    # 4. call a remote procedure
    result = await session.call('io.crossbar.demo.add2', 2, 3)
    print("io.crossbar.demo.add2(2, 3) = {}".format(result))

    await session.leave()

if __name__ == "__main__":
    run([demo])
コード例 #5
0
        return
    print("Rebuilding.")

    path = "{}/venv/bin:{}".format(basedir, environ.get('PATH', ''))
    environ['PATH'] = path
    from twisted.internet import reactor
    yield _run(reactor, join(basedir, u'git'), u'/usr/bin/git', u'pull')
    yield _run(reactor, join(basedir, u'git', u'docs'), '/usr/bin/make',
               'html')
    print("github push processed successfully")


@builder.subscribe(u'webhook.github.',
                   options=SubscribeOptions(match=u"prefix",
                                            details_arg="_details"))
def _github_notify(**kw):
    details = kw.pop("_details")
    print("{}: {} {}".format(details.topic, kw.get('created_at', ''),
                             kw.get('state', '')))
    # print(kw.keys())


@builder.on_join
def joined(session, details):
    print("builder joined: {} {}".format(session, details))
    session.set_payload_codec(keyring)  # e2e encryption keys


if __name__ == '__main__':
    run([builder])
コード例 #6
0

from autobahn.twisted.component import Component, run
from autobahn.wamp.types import RegisterOptions
from autobahn.wamp.exception import ApplicationError
from twisted.internet.defer import inlineCallbacks


component = Component(
    transports=u"ws://localhost:8080/auth_ws",
    realm=u"crossbardemo",
    authentication={
        u"scram": {
            u"authid": u"carol",
            u"authrole": u"authenticated",
            u"password": u"p4ssw0rd",
            u"kdf": u"argon2id13",
        }
    }
)

@component.on_join
def joined(session, details):
    print("Session joined: {}".format(details))


if __name__ == "__main__":
    run([component])  #, log_level='debug')
    def pub(topic):
        print("publishing '{}'".format(topic))
        return session.publish(
            topic,
            options=PublishOptions(exclude_me=False),
        )

    def call_progress(topic):
        print("calling '{}' progressively".format(topic))
        def on_progress(some_data):
            print("received: '{}'".format(some_data))
        return session.call(
            topic,
            options=CallOptions(on_progress=on_progress)
        )

    reactor.callLater(1, pub, u'com.example.foo')
    reactor.callLater(2, pub, u'com.non_matching')
    reactor.callLater(3, pub, u'com.example.some.other.uri')
    reactor.callLater(4, call_progress, u'com.example.progressive')
    reactor.callLater(7, session.leave)

@component.on_leave
def leave(session, details):
    print("Session leaving: {}: {}".format(details.reason, details.message))


if __name__ == '__main__':
    run(component)
    reactor.callLater(2, session.leave)


@inlineCallbacks
def setup_bob(reactor, session):
    print('bob created', session)

    def on_join(session, details):
        print('bob joined', session, details)

    session.on('join', on_join)
    yield sleep(1)
    print("bob done sleeping")
#    session.leave()


if __name__ == '__main__':
    transports = [
        {
            "type": "websocket",
            "url": "ws://127.0.0.1:8080/ws"
        }
    ]

    component1 = Component(on_join=setup_alice, transports=transports, realm=u'crossbardemo')
    component2 = Component(main=setup_bob, transports=transports, realm=u'crossbardemo')
    #run([component1, component2], log_level='debug')
    #run([component1, component2], log_level='info')
    run([component1], log_level='info')
    #run([component2], log_level='info')
コード例 #9
0
    A first component, which gets called "setup-like". When
    it returns, this signals that the component is ready for work.
    """
    # expose the API on the session
    yield session.expose(api)


@coroutine
def component2(reactor, session):
    """
    A second component, which gets called "main-like".
    When it returns, this will automatically close the session.
    """
    result = yield session.call(u'com.example.add2', 2, 3)
    session.publish(u'com.example.on-hello', u'result={}'.format(result))


if __name__ == '__main__':
    from autobahn.twisted.component import Component, run

    # Components wrap either a setup or main function and
    # can be configured with transports, authentication and so on.
    components = [
        Component(setup=component1),
        Component(main=component2)
    ]

    # a convenience runner is provided which takes a list of
    # components and runs all of them
    run(components)
コード例 #10
0
    }
)


# the "on_join" notification runs when the WAMP session has
# successfully connected, authenticated and hence joined a realm on
# the router.
@hook.on_join
@defer.inlineCallbacks
def join(session, details):
    print("joined: {}".format(details))
    session.set_payload_codec(keyring)  # e2e encryption keys

    topic = u'webhook.github.push'
    print("Publishing to: {}".format(topic))
    data = {
        "ref": "refs/heads/master",
        "commits": [
            {
                "id": "deadbeef",
                "message": "a commit message",
            }
        ]
    }
    yield session.publish(topic, **data)
    yield session.leave()


if __name__ == '__main__':
    run([hook])  #, log_level='debug')
コード例 #11
0
    print('Buyer session joined', details)

    market_maker_adr = binascii.a2b_hex(
        session.config.extra['market_maker_adr'][2:])
    print('Using market maker adr:', session.config.extra['market_maker_adr'])
    buyer_privkey = binascii.a2b_hex(session.config.extra['buyer_privkey'][2:])

    # 100 XBR
    max_price = 100 * 10**18
    buyer = SimpleBuyer(market_maker_adr, buyer_privkey, max_price)
    balance = await buyer.start(session, details.authid)
    balance = int(balance / 10**18)
    print("Remaining balance: {} XBR".format(balance))

    async def on_event(key_id, enc_ser, ciphertext, details=None):
        try:
            payload = await buyer.unwrap(key_id, enc_ser, ciphertext)
            print('Received event {}:'.format(details.publication), payload)
            session.publish(u'xbr.myapp.cardata', payload['counter'])
        except Exception as e:
            print(e)
            session.leave()

    await session.subscribe(on_event,
                            "io.crossbar.example",
                            options=SubscribeOptions(details=True))


if __name__ == '__main__':
    run([buyer_component])
コード例 #12
0
                'path': '/tmp/cb1.sock'
            }
        },
        {
            'type': 'websocket',
            'url': 'ws://127.0.0.1:8080/ws',
            'endpoint': {
                'type': 'tcp',
                'host': '127.0.0.1',
                'port': 8080
            }
        }
    ]

    transports = TransportPool(transports)

    components = [
        Component(
            transports,
            config=Config(realm=u'realm1'),
            setup=component1_setup
        ),
        Component(
            transports,
            config=Config(realm=u'realm1', extra={'foo': 23}),
            main=component2_main
        )
    ]

    run(components)
コード例 #13
0
ファイル: eas-set-wc-state.py プロジェクト: crispinus2/pyeas
from twisted.internet.defer import inlineCallbacks

if len(sys.argv) < 3 or (sys.argv[2] != "0" and sys.argv[2] != "1"):
    print("Usage: eas-set-wc-state.py SERVER 0|1")
    print("where 0 means free and 1 means occupied")
    sys.exit(1)

easclient = Component(
    transports=u"ws://%s/ws" % (sys.argv[1]),
    realm=u"eas",
)


@easclient.on_join
@inlineCallbacks
def join(session, details):
    print("Joined session")
    try:
        wcstate = False
        if sys.argv[2] == "1":
            wcstate = True
        res = yield session.call(u'com.eas.set_wc_state', wcstate)
    except ApplicationError as e:
        print("ApplicationError, aborting: %s" % (e))

    yield session.leave()


if __name__ == '__main__':
    run([easclient])
コード例 #14
0
    ],
                     realm="realm1",
                     authentication=AUTHENTICATION)


@comp.on_join
@inlineCallbacks
def _(session, details):
    print("joined: {}".format(details))
    topic_name = u"demo.foo"
    pid = os.getpid()
    counter = 0

    while session.is_connected():
        print("pid {} publish {} to '{}'".format(pid, counter, topic_name))
        data = os.urandom(10)
        session.publish(
            topic_name,
            pid,
            counter,
            foo='0x' + binascii.b2a_hex(data).decode(),
            baz=data,
            options=PublishOptions(exclude_me=False),
        )
        counter += 1
        yield sleep(1)


if __name__ == "__main__":
    run([comp], log_level='info')
コード例 #15
0
                        help='Optional service name.')

    parser.add_argument('--service_uuid',
                        dest='service_uuid',
                        type=six.text_type,
                        default=None,
                        help='Optional service UUID.')

    args = parser.parse_args()

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

    # any extra info we want to forward to our ClientSession (in self.config.extra)
    extra = {
        u'service_name': args.service_name or "default",
        u'service_uuid': args.service_uuid,
    }
    client = Component(transports=args.url,
                       realm=args.realm,
                       main=main,
                       extra=extra,
                       authentication={
                           "anonymous": {
                               "authrole": "anonymous",
                           },
                       })

    # starts the reactor, and logging -- this won't return unless all
    # our components complete
    run([client])
コード例 #16
0
def main():
    load_env()
    Logger().info("Starting directory service...")

    component = make_component(Directory)
    run(component)
コード例 #17
0
)


# 1. subscribe to a topic
@demo.subscribe(u'io.crossbar.demo.hello')
def hello(msg):
    print("Got hello: {}".format(msg))


# 2. register a procedure for remote calling
@demo.register(u'io.crossbar.demo.add2')
def add2(x, y):
    return x + y


# 3. after we've authenticated, run some code
@demo.on_join
async def joined(session, details):
    # publish an event (won't go to "this" session by default)
    session.publish('io.crossbar.demo.hello', 'Hello, world!')

    # 4. call a remote procedure
    result = await session.call('io.crossbar.demo.add2', 2, 3)
    print("io.crossbar.demo.add2(2, 3) = {}".format(result))

    await session.leave()


if __name__ == "__main__":
    run([demo])
コード例 #18
0
#
###############################################################################

import datetime
import os
import random

from autobahn.twisted.component import Component, run
import txaio

odometer_component = Component(transports=os.environ.get(
    'XBR_INSTANCE', u'ws://localhost:8080/ws'),
                               realm=os.environ.get('XBR_REALM', u'realm1'))


@odometer_component.on_join
async def joined(session, _details):
    print("session joined...")
    counter = 20000
    while session.is_attached():
        date = datetime.datetime.now()
        print('Odometer Simulator publishing xbr.myapp.odometer', counter,
              date)
        session.publish(u'xbr.myapp.odometer', f'{counter} {date}')
        counter += random.randint(1, 10)
        await txaio.sleep(1)


if __name__ == '__main__':
    run([odometer_component])
コード例 #19
0
            "endpoint": {
                "type": "tcp",
                "host": "localhost",
                "port": 8443,
            },
            "serializers": ["json", "cbor"],
        },
    ],
    realm="realm1",
)


@comp.on_join
@inlineCallbacks
def _(session, details):
    print("joined: {}".format(session))
    topic_name = u"io.crossbar.demo.public.foo"

    def _foo(*args, **kw):
        print("{}: {} {}".format(topic_name, args, kw))

    session.subscribe(_foo, topic_name)
    print("subscribed")
    while session.is_connected():
        print(".")
        yield sleep(1)


if __name__ == "__main__":
    run([comp])  #, log_level='debug')
コード例 #20
0
        "type": "websocket",
        "url": "wss://127.0.0.1:8083/ws",
        "endpoint": SSL4ClientEndpoint(
            reactor,
            '127.0.0.1',
            8080,
            optionsForClientTLS('localhost'),
        ),
    }

    clearnet_transport = {
        "type": "websocket",
        "url": "ws://127.0.0.1:8080/ws",
        "endpoint": TCP4ClientEndpoint(reactor, 'localhost', 8080)
    }

    transports = [
        tls_transport_untrusted,
        tls_transport,
        clearnet_transport,
    ]

    # try main= vs. setup= to see different exit behavior
    component = Component(main=setup, transports=transports, realm='crossbardemo')
    #component = Component(setup=setup, transports=transports, realm='crossbardemo')

    # can add this confirm logging of more error-cases
    #component.session_factory = Foo
    txaio.start_logging(level='info')
    run(component)
コード例 #21
0
    reactor.callLater(2, session.leave)


@inlineCallbacks
def setup_bob(reactor, session):
    print('bob created', session)

    def on_join(session, details):
        print('bob joined', session, details)

    session.on('join', on_join)
    yield sleep(1)
    print("bob done sleeping")


#    session.leave()

if __name__ == '__main__':
    transports = [{"type": "websocket", "url": "ws://127.0.0.1:8080/ws"}]

    component1 = Component(on_join=setup_alice,
                           transports=transports,
                           realm=u'crossbardemo')
    component2 = Component(main=setup_bob,
                           transports=transports,
                           realm=u'crossbardemo')
    #run([component1, component2], log_level='debug')
    #run([component1, component2], log_level='info')
    run([component1], log_level='info')
    #run([component2], log_level='info')
コード例 #22
0
ファイル: daemon.py プロジェクト: deskconn/piconn
    }
    component = Component(transports=[transport],
                          realm="deskconn",
                          session_factory=GPIOComponent)
    component._transports[0].max_retries = 0
    return component


if __name__ == '__main__':
    if os.environ.get("SNAP_NAME") == "piconn":
        crossbar = os.path.expandvars(
            "$SNAP_COMMON/crossbar-runtime-dir/bin/crossbar")
        if not os.path.exists(crossbar):
            print(
                "Waiting for crossbar runtime directory interface to connect")
            while not os.path.exists(crossbar):
                time.sleep(1)
        print("Found crossbar runtime environment")
    else:
        os.environ['SNAP_COMMON'] = os.path.expandvars('$HOME')

    sock_path = os.path.join(
        os.path.expandvars('$SNAP_COMMON/deskconnd-sock-dir'),
        'deskconnd.sock')
    print("finding deskconnd...")
    while not os.path.exists(sock_path):
        time.sleep(1)
    print("found, now connecting.")

    run([assemble()])
コード例 #23
0
from autobahn.twisted.component import Component, run
from autobahn.twisted.util import sleep
from twisted.internet.defer import inlineCallbacks
import os

url = os.environ.get('CBURL', u'ws://localhost:8080/ws')
realmvalue = os.environ.get('CBREALM', u'realm1')
component = Component(transports=url, realm=realmvalue)

@component.on_join
@inlineCallbacks
def joined(session, details):
    print("session ready")

    def oncounter(count):
        print("event received: {0}", count)

    try:
        yield session.subscribe(oncounter, u'my.com.hello')
        print("subscribed to topic")
    except Exception as e:
        print("could not subscribe to topic: {0}".format(e))

if __name__ == "__main__":
    run([component])        
コード例 #24
0
from autobahn.twisted.component import Component, run

display_component = Component(
    transports=os.environ.get('XBR_INSTANCE', u'ws://localhost:8080/ws'),
    realm=os.environ.get('XBR_REALM', u'realm1')
)


@display_component.on_join
async def joined(session, _details):
    data = None

    def get_distance():
        return data

    def on_car_data(self, car_data):
        print("Got event: {}".format(car_data))
        nonlocal data
        data = car_data

    print("session attached")
    sub = await session.subscribe(on_car_data, 'xbr.myapp.cardata')
    print("Subscribed to xbr.myapp.cardata with {}".format(sub.id))
    await session.register(get_distance, 'xbr.myapp.get_distance')
    print("Procedure {} registered".format("xbr.myapp.get_distance"))


if __name__ == '__main__':
    run([display_component])
コード例 #25
0
    topic = 'io.crossbar.example'

    seller = SimpleSeller(market_maker_adr, seller_privkey)
    # 1 XBR
    price = 1 * 10 ** 18
    interval = 12
    seller.add(api_id, topic, price, interval, None)

    balance = await seller.start(session)
    balance = int(balance / 10 ** 18)
    print("Remaining balance: {} XBR".format(balance))

    async def on_odometer_data(count):
        print("event received: {}".format(count))
        payload = {'data': 'py-seller', 'counter': count}
        key_id, enc_ser, ciphertext = await seller.wrap(api_id, topic, payload)
        pub = await session.publish(topic, key_id, enc_ser, ciphertext,
                                    options=PublishOptions(acknowledge=True))

        print('Published event {}: {}'.format(pub.id, payload))

    try:
        await session.subscribe(on_odometer_data, "xbr.myapp.odometer")
        print("subscribed to topic '{}'".format("xbr.myapp.odometer"))
    except Exception as e:
        print("could not subscribe to topic: {}".format(e))


if __name__ == '__main__':
    run([seller_component])
コード例 #26
0
    def do(self, command):

        self.__define_action_to_subscribe(command)
        run(self.__component)
コード例 #27
0
    seller.add(api_id, topic, price, interval, None)

    balance = await seller.start(session)
    balance = int(balance / 10**18)
    print("Remaining balance: {} XBR".format(balance))

    while running:
        payload = {'data': 'py-seller', 'counter': counter}
        key_id, enc_ser, ciphertext = await seller.wrap(api_id, topic, payload)
        pub = await session.publish(topic,
                                    key_id,
                                    enc_ser,
                                    ciphertext,
                                    options=PublishOptions(acknowledge=True))

        print('Published event {}: {}'.format(pub.id, payload))

        counter += 1
        await sleep(10)


@comp.on_leave
def left(session, details):
    print('Seller session left', details)
    global running
    running = False


if __name__ == '__main__':
    run([comp])
コード例 #28
0
    def launcher(config, privkey_file, id, python, workdir):
        """
        Runs the CTS 'Launcher' process.

        The launcher is a CTS process started on a host taking part in a
        CTS test setup and is responsible for starting processes like
        probes and testees. It exposes an API via WAMP.

        This function is also specified as an entry point in setup.py
        for the `ctslauncher` script.
        """
        # create clean working directory for Python virtualenvs
        #
        if not os.path.exists(workdir):
            print("Working directory {} does not exist. Creating ...".format(
                workdir))
            os.makedirs(workdir)
        else:
            if not os.path.isdir(workdir):
                print(
                    "Fatal: path {} for working directory exists, but is not a directory"
                    .format(workdir))
                sys.exit(1)
            else:
                print(
                    "Working directory {} exists already - cleaning and recreating."
                    .format(workdir))
                try:
                    shutil.rmtree(workdir)
                except Exception as e:
                    print(
                        "Fatal: error during cleaning of working directory - {}"
                        .format(e))
                os.makedirs(workdir)

        with open(privkey_file, 'rb') as f:
            privkey = f.read()

        comp = Component(
            transports=[{
                u"type": u"websocket",
                u"url": config.router,
            }],
            realm="io.crossbar.cts",
            authentication={
                "cryptosign": {
                    "authid": id,
                    "privkey": binascii.b2a_hex(privkey),
                }
            },
        )

        from twisted.internet import reactor

        @comp.on_join
        async def setup_launcher(session, details):
            ip = await session.call("io.crossbar.cts.launcher_ip",
                                    details.session)
            print("address: {}".format(ip))
            print("Launcher '{}' connected, session_id={}".format(
                id, details.session))
            try:
                # XXX since we already loaded the key, maybe privkey= instead of privkey_file here?
                launch = await create_launcher(reactor,
                                               session,
                                               id,
                                               ip,
                                               workdir,
                                               config.router,
                                               privkey_file,
                                               pythons=python)
            except Exception as e:
                print(str(e))
                raise
                ##await session.leave()

        run([comp], log_level=("debug" if config.debug else "info"))
コード例 #29
0
from autobahn.wamp.types import RegisterOptions
from autobahn.wamp.exception import ApplicationError
from twisted.internet.defer import inlineCallbacks, CancelledError


@inlineCallbacks
def main(reactor, session):
    print("Client session={}".format(session))
    d = session.call("example.foo", "some", "args")
    print("Called 'example.foo': {}".format(d))
    print("cancel()-ing the above Deferred")

    d.cancel()

    try:
        res = yield d
        print("somehow we got a result: {}".format(res))
    except CancelledError:
        print("call was canceled successfully")
    print("done")


component = Component(
    transports="ws://localhost:8080/auth_ws",
    main=main,
    realm="crossbardemo",
)

if __name__ == "__main__":
    run([component])  #, log_level='debug')
コード例 #30
0
webapp = Klein()


@webapp.route('/', methods=['POST'])
def index(request: Request):
    content = json.loads(request.content.read())
    try:
        new_state = GameState(**content)

    except Exception as e:
        print(content)
        print(e)
        return "wew"

    wamp_component.state = new_state
    print(wamp_component.state.map.game_state)

    return "ok"


if __name__ == "__main__":
    from twisted.web.server import Site
    from twisted.internet import reactor, task

    import sys
    print(sys.path)

    reactor.listenTCP(8016, Site(webapp.resource()))
    run([wamp_component])
コード例 #31
0
ファイル: device1.py プロジェクト: anhhuy0501/Crossbar
    print(f"New interval: {rules[0]['interval']}")
    # Check rules
    for rule in rules:
        schedule_work(rule["interval"])


@component.on_join
@inlineCallbacks
def joined(session, details):
    global save_session
    global save_detail
    save_session = session
    save_detail = details

    print("session ready")
    print(f"Device id: {device_id}")

    try:
        session.subscribe(oncounter, topic)
        print("subscribed to topic")
    except Exception as e:
        print("could not subscribe to topic: {0}".format(e))

    yield 0

    # yield perodic_work()


if __name__ == "__main__":
    run([component])
コード例 #32
0
    print("Session attached")
    if mySession is None:
        mySession = session

    rooms = Room.select().join(Patient, JOIN.LEFT_OUTER)

    for room in rooms:
        mySession.publish(u"com.eas.room_added",
                          name=room.name,
                          priority=room.priority)
        if room.patient is not None:
            mySession.publish(
                u"com.eas.room_populated", unicode(room.name), {
                    u"id": unicode(room.patient.patId),
                    u"name": unicode(room.patient.name),
                    u"surname": unicode(room.patient.surname),
                    u"title": unicode(room.patient.title)
                })


def createTables():
    with db:
        db.create_tables([Patient, Room])


if __name__ == '__main__':
    db.connect()
    createTables()

    run([eascomp])