Пример #1
0
def main():
    Gst.init([])
    gbulb.install()

    clock = NetTimeClock()
    sink = VideoSink()

    loop = asyncio.get_event_loop()
    coro = loop.create_server(VoctoMixProtocol, '0.0.0.0', 9999)
    server = loop.run_until_complete(coro)

    print('Control server listening on {}'.format(
          server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    clock.stop()
    sink.stop()
    try:
        loop.run_until_complete(server.wait_closed())
    except KeyboardInterrupt:
        # Gets carried through to here under glib main loop, for some reason...
        pass
    loop.close()
Пример #2
0
def test_subprocesses_read_after_closure(glib_loop):
    import asyncio
    import subprocess

    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb

    gbulb.install()

    async def coro():
        proc = await asyncio.create_subprocess_exec(
            "cat",
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        proc.stdin.write(b"hey\n")
        await proc.stdin.drain()

        proc.stdin.close()

        out = await proc.stdout.read()
        assert out == b"hey\n"

        await proc.wait()

    glib_loop.run_until_complete(coro())
Пример #3
0
def test_subprocesses_readline_without_closure(glib_loop):
    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb

    gbulb.install()

    async def run():
        proc = await asyncio.create_subprocess_exec(
            "cat",
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
        )

        try:
            proc.stdin.write(b"test line\n")
            await proc.stdin.drain()

            line = await asyncio.wait_for(proc.stdout.readline(), timeout=5)
            assert line == b"test line\n"

            proc.stdin.close()

            line = await asyncio.wait_for(proc.stdout.readline(), timeout=5)
            assert line == b""
        finally:
            await proc.wait()

    glib_loop.run_until_complete(run())
Пример #4
0
def main_async():
    gbulb.install(gtk=True)
    loop = gbulb.get_event_loop()
    q = asyncio.Queue()
    console = async_console_window(loop, q)
    asyncio. async (stuff(q))
    loop.run_forever()
Пример #5
0
def test_install(gtk, gtk_available):
    from gbulb import install
    import sys

    called = False

    def set_event_loop_policy(pol):
        nonlocal called
        called = True
        cls_name = pol.__class__.__name__
        if gtk:
            assert cls_name == "GtkEventLoopPolicy"
        else:
            assert cls_name == "GLibEventLoopPolicy"

    if gtk and "gbulb.gtk" in sys.modules:
        del sys.modules["gbulb.gtk"]

    mock_repository = mock.Mock()
    if not gtk_available:
        del mock_repository.Gtk

    with mock.patch.dict("sys.modules", {"gi.repository": mock_repository}):
        with mock.patch("asyncio.set_event_loop_policy",
                        set_event_loop_policy):
            import_error = gtk and not gtk_available
            try:
                install(gtk=gtk)
            except ImportError:
                assert import_error
            else:
                assert not import_error
                assert called
Пример #6
0
def main():
    Gst.init([])
    gbulb.install()

    clock = NetTimeClock()
    sink = VideoSink()

    loop = asyncio.get_event_loop()
    coro = loop.create_server(VoctoMixProtocol, '0.0.0.0', 9999)
    server = loop.run_until_complete(coro)

    print('Control server listening on {}'.format(
        server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    clock.stop()
    sink.stop()
    try:
        loop.run_until_complete(server.wait_closed())
    except KeyboardInterrupt:
        # Gets carried through to here under glib main loop, for some reason...
        pass
    loop.close()
Пример #7
0
def test_install(gtk, gtk_available):
    from gbulb import install
    import sys

    called = False

    def set_event_loop_policy(pol):
        nonlocal called
        called = True
        cls_name = pol.__class__.__name__
        if gtk:
            assert cls_name == "GtkEventLoopPolicy"
        else:
            assert cls_name == "GLibEventLoopPolicy"

    if gtk and "gbulb.gtk" in sys.modules:
        del sys.modules["gbulb.gtk"]

    mock_repository = mock.Mock()
    if not gtk_available:
        del mock_repository.Gtk

    with mock.patch.dict("sys.modules", {"gi.repository": mock_repository}):
        with mock.patch("asyncio.set_event_loop_policy", set_event_loop_policy):
            import_error = gtk and not gtk_available
            try:
                install(gtk=gtk)
            except ImportError:
                assert import_error
            else:
                assert not import_error
                assert called
Пример #8
0
    def __init__(self):
        self._logger = get_logger('uchroma.server')

        gbulb.install()

        parser = argparse.ArgumentParser(description='UChroma daemon')
        parser.add_argument("-v", "--version", action='version', version='self.version')
        parser.add_argument("-d", "--debug", action='append_const', const=True,
                            help='Enable debug output')

        args = parser.parse_args()


        self._loop = asyncio.get_event_loop()

        level = logging.INFO
        asyncio_debug = False

        if args.debug is not None:
            if len(args.debug) > 2:
                level = LOG_PROTOCOL_TRACE
                asyncio_debug = True
            elif len(args.debug) == 2:
                level = LOG_TRACE
                asyncio_debug = True
            elif len(args.debug) == 1:
                level = logging.DEBUG

        logging.getLogger().setLevel(level)
        self._loop.set_debug(asyncio_debug)
Пример #9
0
def test_subprocesses_readline_without_closure(glib_loop):
    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb
    gbulb.install()

    @asyncio.coroutine
    def run():
        proc = yield from asyncio.create_subprocess_exec(
            'cat',
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
            loop=glib_loop)

        try:
            proc.stdin.write(b'test line\n')
            yield from proc.stdin.drain()

            line = yield from asyncio.wait_for(proc.stdout.readline(),
                                               timeout=5,
                                               loop=glib_loop)
            assert line == b'test line\n'

            proc.stdin.close()

            line = yield from asyncio.wait_for(proc.stdout.readline(),
                                               timeout=5,
                                               loop=glib_loop)
            assert line == b''
        finally:
            yield from proc.wait()

    glib_loop.run_until_complete(run())
Пример #10
0
 def run_main(cls, main: Callable, *main_args, **main_kwargs):
     try:
         main(*main_args, **main_kwargs)
         if cls.config_type(
         ).event_loop_type == AsyncEventLoopType.GLIB_ONLY:
             Gtk.main()
         elif cls.config_type().event_loop_type == AsyncEventLoopType.GBULB:
             gbulb.install(gtk=True)
             gbulb.get_event_loop().set_exception_handler(
                 async_handle_exeception)
             from skytemple.core.events.manager import EventManager
             GLib.idle_add(EventManager.instance().async_init)
             asyncio.get_event_loop().run_forever()
         else:
             raise RuntimeError("Invalid async configuration")
     except OSError as ex:
         if hasattr(ex, 'winerror') and ex.winerror == 6:  # type: ignore
             # [WinError 6] The handle is invalid
             # Originates in gi/_ossighelper.py - Some issues with socket cleanup. We will ignore that.
             pass
         else:
             raise
     except (SystemExit, KeyboardInterrupt):
         pass
     finally:
         # TODO: Currently always required for Debugger compatibility
         #  (since that ALWAYS uses this async implementation)
         AsyncTaskRunner.end()
Пример #11
0
def test_subprocesses_read_after_closure(glib_loop):
    import asyncio
    import subprocess

    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb
    gbulb.install()

    @asyncio.coroutine
    def coro():
        proc = yield from asyncio.create_subprocess_exec(
            'cat',
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE,
            loop=glib_loop)

        proc.stdin.write(b'hey\n')
        yield from proc.stdin.drain()

        proc.stdin.close()

        out = yield from proc.stdout.read()
        assert out == b'hey\n'

        yield from proc.wait()

    glib_loop.run_until_complete(coro())
Пример #12
0
def main_async():
    q = asyncio.Queue()
    gbulb.install(gtk=True)
    loop = gbulb.get_event_loop()
    console = async_console_window(loop, q)
    # asyncio.async(gui_loop(console
    asyncio.ensure_future(input_handler(console))
    loop.run_forever()
Пример #13
0
Файл: app.py Проект: pybee/toga
    def __init__(self, interface):
        self.interface = interface
        self.interface._impl = self

        gbulb.install(gtk=True)
        self.loop = asyncio.get_event_loop()

        self.create()
Пример #14
0
    def __init__(self, profile):
        gbulb.install(gtk=False)

        self.profile = profile
        self.loop = asyncio.get_event_loop()
        self.load_config()
        self.pages = {}
        self.highlight_matches = {}
Пример #15
0
def main(version):
    gbulb.install(gtk=True)

    loop = asyncio.get_event_loop()
    client = TelexClient(loop=loop)
    application = TelexApplication(client=client)

    loop.run_forever(application, sys.argv)
Пример #16
0
    def __init__(self, interface):
        self.interface = interface
        self.interface._impl = self

        gbulb.install(gtk=True)
        self.loop = asyncio.get_event_loop()

        self.create()
Пример #17
0
def main():
    args = parser.parse_args()

    gbulb.install()
    agent = PolicyAgent(args.socket_path)

    loop = asyncio.get_event_loop()
    tasks = [
        agent.run(),
    ]
    loop.run_until_complete(asyncio.wait(tasks))
Пример #18
0
def start(cfg: dict) -> None:
    """
    Start a panel given a config dict

    Parameters:
    cfg -- config dict
    """
    gbulb.install(gtk=False)
    loop = asyncio.get_event_loop()
    panel = Panel(cfg['widgets'], cfg['out_fmt'], cfg['out_adapter'])
    asyncio.ensure_future(panel.run())
    loop.run_forever()
Пример #19
0
    def __init__(self):
        gbulb.install(gtk=False)

        try:
            self.loop = asyncio.get_event_loop()
        except RuntimeError:
            # woo threads
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)

        self.load_config()
        self.pages = {}
        self.highlight_matches = {}
Пример #20
0
def main(version: str) -> int:
    logger.debug("main")

    gbulb.install(gtk=True)
    loop = asyncio.get_event_loop()

    application: Application = INJECTOR.get(Application)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                         application.quit)
    loop.run_forever(application=application, argv=sys.argv)

    # no idea how to get the exit status
    cleanup()
    return sys.exit(0)
Пример #21
0
 def __init__(self, argv=None):
     """Parse command line options, read config and initialize members."""
     gbulb.install(gtk=True)
     # parse program options (retrieve log level and config file name):
     args = docopt(self.usage, version='udiskie ' + self.version)
     default_opts = self.option_defaults
     program_opts = self.program_options(args)
     # initialize logging configuration:
     log_level = program_opts.get('log_level', default_opts['log_level'])
     debug = log_level <= logging.DEBUG
     logging.config.dictConfig({
         'version': 1,
         'disable_existing_loggers': False,
         'formatters': {
             'plain':  {'format': _('%(message)s')},
             'detail': {'format': _('%(levelname)s [%(asctime)s] %(name)s: %(message)s')},
         },
         'filters': {
             'info': {'()': 'udiskie.cli.SelectLevel', 'level': logging.INFO},
         },
         'handlers': {
             'info':  {'class': 'logging.StreamHandler',
                       'stream': 'ext://sys.stdout',
                       'formatter': 'plain',
                       'filters': ['info']},
             'error': {'class': 'logging.StreamHandler',
                       'stream': 'ext://sys.stderr',
                       'formatter': 'plain',
                       'level': 'WARNING'},
             'debug': {'class': 'logging.StreamHandler',
                       'stream': 'ext://sys.stderr',
                       'formatter': 'detail'},
         },
         # configure root logger:
         'root': {
             'handlers': ['info', 'debug' if debug else 'error'],
             'level': log_level,
         },
     })
     # parse config options
     config_file = OptionalValue('--config')(args)
     config = udiskie.config.Config.from_file(config_file)
     options = {}
     options.update(default_opts)
     options.update(config.program_options)
     options.update(program_opts)
     # initialize instance variables
     self.config = config
     self.options = options
Пример #22
0
def main():
    gbulb.install(gtk=True)
    loop = gbulb.get_event_loop()

    display = Gtk.Entry()
    vbox = Gtk.VBox()

    vbox.pack_start(display, True, True, 0)

    win = Gtk.Window(title='Counter window')
    win.connect('delete-event', lambda *args: loop.stop())
    win.add(vbox)

    win.show_all()

    asyncio.async(counter(display))
    loop.run_forever()
Пример #23
0
Файл: gtk.py Проект: yropb/gbulb
def main():
    gbulb.install(gtk=True)
    loop = gbulb.get_event_loop()

    display = Gtk.Entry()
    vbox = Gtk.VBox()

    vbox.pack_start(display, True, True, 0)

    win = Gtk.Window(title='Counter window')
    win.connect('delete-event', lambda *args: loop.stop())
    win.add(vbox)

    win.show_all()

    asyncio. async (counter(display))
    loop.run_forever()
Пример #24
0
    def __init__(self):
        Gst.init(sys.argv)
        # Gst.debug_set_active(True)
        # Gst.debug_set_default_threshold(4)

        print("Initializing videomixer application...")
        gbulb.install()
        loop = asyncio.get_event_loop()

        self.mixerapi = mixerapi.MixerApi()
        handler = self.mixerapi.get_handler()
        web_server = loop.create_server(handler, self.bind_addr,
                                        self.listen_port)

        print("Ready! Listening on {}:{}".format(self.bind_addr,
                                                 self.listen_port))
        loop.run_until_complete(web_server)
        loop.run_forever()
Пример #25
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s',
                        '--silent',
                        action='store',
                        help="don't print time logs")
    args = parser.parse_args()

    Notify.init('你的Personal Timer')
    gbulb.install()
    loop = asyncio.get_event_loop()
    clock = Clock(silent=args.silent)
    try:
        loop.run_until_complete(clock.run())
    except KeyboardInterrupt:
        pass
    finally:
        clock.close()
Пример #26
0
    def __init__(self):
        gbulb.install()

        parser = argparse.ArgumentParser(description='UChroma daemon')
        parser.add_argument('-v',
                            "--version",
                            action='version',
                            version='self.version')
        parser.add_argument('-d',
                            "--debug",
                            action='append_const',
                            const=True,
                            help="Increase logging verbosity")
        parser.add_argument('-C',
                            "--colorlog",
                            action='store_true',
                            help="Use colored log output")

        args = parser.parse_args()

        self._loop = asyncio.get_event_loop()

        level = logging.INFO
        asyncio_debug = False
        colorlog = False
        if args.colorlog is not None:
            colorlog = args.colorlog

        Log.enable_color(colorlog)
        self._logger = Log.get('uchroma.server')

        if args.debug is not None:
            if len(args.debug) > 2:
                level = LOG_PROTOCOL_TRACE
                asyncio_debug = True
            elif len(args.debug) == 2:
                level = LOG_TRACE
                asyncio_debug = True
            elif len(args.debug) == 1:
                level = logging.DEBUG

        logging.getLogger().setLevel(level)
        self._loop.set_debug(asyncio_debug)
Пример #27
0
def test_install(gtk, gtk_available):
    from gbulb import install

    called = False

    def set_event_loop_policy(pol):
        nonlocal called
        called = True
        cls_name = pol.__class__.__name__
        if gtk:
            assert cls_name == "GtkEventLoopPolicy"
        else:
            assert cls_name == "GLibEventLoopPolicy"

    with mock.patch("gbulb.utils.gtk_available", return_value=gtk_available):
        with mock.patch("asyncio.set_event_loop_policy", set_event_loop_policy):
            try:
                install(gtk=gtk)
            except ValueError:
                assert gtk and not gtk_available
            else:
                assert called
Пример #28
0
def test_subprocesses(glib_loop):
    import asyncio
    import subprocess

    # needed to ensure events.get_child_watcher() returns the right object
    import gbulb
    gbulb.install()

    @asyncio.coroutine
    def coro():
        proc = yield from asyncio.create_subprocess_exec(
            'cat', stdout=subprocess.PIPE, stdin=subprocess.PIPE,
            stderr=subprocess.PIPE, loop=glib_loop)

        proc.stdin.write(b'hey\n')
        yield from proc.stdin.drain()

        proc.stdin.close()

        out = yield from proc.stdout.read()
        assert out == b'hey\n'

    glib_loop.run_until_complete(coro())
Пример #29
0
#!/usr/bin/env python3

import gbulb
from aiohttp import web

from router import setup_routes
from view import setup_view

gbulb.install()  # Use Glib Mainloop implementation

app = web.Application()
setup_routes(app)
setup_view(app)

app['logic'] = Logic()
app['ws'] = {}
app.on_startup.append(app['logic'].onStartup)
app.on_shutdown.append(app['logic'].onShutdown)

web.run_app(app, host='0.0.0.0', port=80)
Пример #30
0
def main():
    if sys.platform == "linux":
        clients = {
            "introspective": None,  # assign later because of dependencies
            "playerctl": ForkingPlayerctlClient,
            "unixsocket": UnixSocketClient
        }
        default_client = "introspective"

    elif sys.platform == "darwin":
        clients = {"unixsocket": UnixSocketClient}
        default_client = "unixsocket"

    elif sys.platform == "windows":
        print("windows not yet supported")
        loop = asyncio.ProactorEventLoop()  # for subprocesses on windows
        asyncio.set_event_loop(loop)
        return 1
    else:
        print(f"Platform '{sys.platform}' not supported")
        return 1

    def get_commit_id():
        # called on every launch, but that's ok for now
        return subprocess.run(["git", "describe", "--always"],
                              stdout=subprocess.PIPE,
                              timeout=0.5).stdout.decode('utf-8').strip()

    # argparse setup
    # noinspection PyTypeChecker
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='datenight client')

    # optional arguments
    parser.add_argument('-v',
                        action='count',
                        help="verbosity increases with each 'v' "
                        "| critical/error/warning/info/debug",
                        default=0)
    parser.add_argument('-s',
                        '--server',
                        type=str,
                        default="http://localhost",
                        help="hostname to connect to")
    parser.add_argument('-p',
                        '--port',
                        default=None,
                        type=int,
                        help="port to connect to (if unspecified, defaults to "
                        "80 for http:// and 443 for https://)")
    parser.add_argument('-c',
                        '--client',
                        default=default_client,
                        type=str,
                        choices=clients.keys(),
                        help="Choice of client to use")
    parser.add_argument('-a',
                        '--alias',
                        type=str,
                        default=None,
                        help="Name by which this publisher will be known as")
    parser.add_argument('-o',
                        '--offset',
                        default=0,
                        type=int,
                        help="Offset (+/- <seconds> if any), to apply on the "
                        "local file")
    parser.add_argument('-V',
                        '--version',
                        action='version',
                        version="%(prog)s v{} ({})".format(
                            '.'.join(map(str, version)), get_commit_id()),
                        help="Show version and exit")

    args = parser.parse_args()
    if args.client not in clients:
        # fallback if the default_client is invalid
        print(f"Must choose a client (-c) from {clients.keys()}")
        return 1
    if args.client == "introspective":
        try:
            from client.vlc.introspective import IntrospectiveVLCClient
        except ValueError:
            print("You don't have playerctl installed "
                  "(needed for the playerctl client)\n"
                  "Install it or use an alternative client with the -c flag")
            return 1
        else:
            clients['introspective'] = IntrospectiveVLCClient

        try:
            # noinspection PyUnresolvedReferences
            import gbulb
        except ImportError:
            print(
                "You don't have the gbulb module installed. Falling back to "
                "asyncio_glib which has an upstream issue preventing it from "
                "reporting status immediately (delaying async events)")
            try:
                import asyncio_glib
            except ImportError:
                print(
                    "You don't have the asyncio_glib module installed "
                    "(needed for the introspective client)\n"
                    "Install it or use an alternative client with the -c flag")
                return 1
            else:
                asyncio.set_event_loop_policy(
                    asyncio_glib.GLibEventLoopPolicy())
        else:
            gbulb.install()

    # logger setup
    level = max(10, 50 - (10 * args.v))
    print(f'Logging level is: {logging.getLevelName(level)}')
    logger = logging.getLogger(__name__)
    logger.setLevel(level)
    formatter = logging.Formatter('%(asctime)s: %(levelname)s:\t%(message)s')
    sh = logging.StreamHandler()
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    logger = logging.getLogger('client')
    logger.setLevel(level)
    logger.addHandler(sh)

    if args.port is None:
        if args.server.startswith("https"):
            args.port = 443
        elif args.server.startswith("http"):
            args.port = 80

    return asyncio.run(start_loop(args, clients))
Пример #31
0
def main(argv):
    progname = argv.pop(0).rpartition('/')[2]
    parser = argparse.ArgumentParser(prog=progname)
    parser.add_argument("DEVICE", help="The joystick device name.")
    parser.add_argument('-t',
                        '--type',
                        default='auto',
                        help="Specify the controller type to use")
    parser.add_argument('-l',
                        '--layout',
                        default='distance',
                        help="Name of the layout to use")
    parser.add_argument('-T',
                        '--theme',
                        default='default',
                        help="Specify the theme to use")
    args = parser.parse_args(argv)

    import overlayapi as api
    api.import_all_config()

    try:
        ctype = api.CONTROLLER_TYPES[args.type]()
    except KeyError:
        raise ArgvError("no such controller type: %r" % (args.type, ), parser)
    try:
        layoutcls = api.LAYOUTS[args.layout]
    except KeyError:
        raise ArgvError("no such layout: %r" % (args.layout, ), parser)
    try:
        theme = api.THEMES[args.theme]()
    except KeyError:
        raise ArgvError("no such theme: %s" % (args.theme, ), parser)

    import gi
    gi.require_version('Gtk', '3.0')
    import gbulb
    import gbulb.gtk
    from gi.repository import Gtk
    from live import JsWidget, LiveWorker

    asyncio.set_event_loop_policy(gbulb.gtk.GtkEventLoopPolicy())
    gbulb.install(gtk=True)
    loop = asyncio.get_event_loop()

    layout = layoutcls(ctype)
    evs = js.HandlerJsEvents()
    context = api.Context(theme, ctype, evs)

    anim = api.LiveControlsAnimation(context, layout.controls)
    anim.init()
    jswidget = JsWidget(layout, anim)

    win = Gtk.Window()
    win.connect("delete-event", lambda *args: task.cancel())
    win.set_property('decorated', False)
    screen = win.get_screen()
    argb = screen.get_rgba_visual()
    if argb:
        win.set_visual(argb)
    win.add(jswidget)
    win.show_all()

    worker = LiveWorker(args.DEVICE, evs)
    worker.on_init = lambda: jswidget.enable()
    worker.on_event = lambda: jswidget.queue_draw()
    task = asyncio.ensure_future(worker.do_work())

    with suppress(asyncio.CancelledError):
        loop.run_until_complete(task)
 def setUp(self):
     gbulb.install()
     self.loop = asyncio.get_event_loop()
     self.bluetoothMonitorConfig = BluetoothMonitorConfigManager(self.loop)
     self.fakes = TestFakeMethods(self.bluetoothMonitorConfig)
Пример #33
0
def initialize_input_driver(config):
    """Set up GTK main loop for use with asyncio."""
    gbulb.install(gtk=True)
Пример #34
0
def main():
    if sys.platform == "linux":
        clients = {
            "introspective": None,  # assign later because of dependencies
            "playerctl": ForkingPlayerctlClient,
            "unixsocket": UnixSocketClient
        }
        default_client = "introspective"

    elif sys.platform == "darwin":
        clients = {
            "unixsocket": UnixSocketClient
        }
        default_client = "unixsocket"

    elif sys.platform == "windows":
        print("windows not yet supported")
        loop = asyncio.ProactorEventLoop()  # for subprocesses on windows
        asyncio.set_event_loop(loop)
        return 1
    else:
        print("Platform '{}' not supported".format(sys.platform))
        return 1

    def get_commit_id():
        # called on every launch, but that's ok for now
        return subprocess.run(["git", "describe", "--always"],
                              stdout=subprocess.PIPE,
                              timeout=0.5).stdout.decode('utf-8').strip()

    # argparse setup
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='datenight client')

    # optional arguments
    parser.add_argument('-v', action='count',
                        help="verbosity increases with each 'v' "
                             "| critical/error/warning/info/debug",
                        default=0)
    parser.add_argument('-s', '--server', type=str, default="localhost",
                        help="hostname to connect to")
    parser.add_argument('-p', '--port', default=None, type=int,
                        help="port to connect to (if unspecified, defaults to "
                             "80 for http:// and 443 for https://)")
    parser.add_argument('-c', '--client', default=default_client, type=str,
                        choices=clients.keys(), help="Choice of client to use")
    parser.add_argument('-a', '--alias', type=str, default=None,
                        help="Name by which this publisher will be known as")
    parser.add_argument('-o', '--offset', default=0, type=int,
                        help="Offset (+/- <seconds> if any), to apply on the "
                             "local file")
    parser.add_argument('-V', '--version', action='version',
                        version="%(prog)s v{} ({})".format(
                            '.'.join(map(str, _version)), get_commit_id()),
                        help="Show version and exit")

    args = parser.parse_args()
    if args.client not in clients:
        # fallback if the default_client is invalid
        print("Must choose a client (-c) from {}".format(clients.keys()))
        return 1
    if args.client == "introspective":
        try:
            from client.vlc.introspective import IntrospectiveVLCClient
        except ValueError:
            print(
                "You don't have playerctl installed "
                "(needed for the playerctl client)\n"
                "Install it or use an alternative client with the -c flag")
            return 1
        else:
            clients['introspective'] = IntrospectiveVLCClient

        try:
            import gbulb
        except ImportError:
            print(
                "You don't have the gbulb module installed "
                "(needed for the introspective client)\n"
                "Install it or use an alternative client with the -c flag")
            return 1
        else:
            gbulb.install()

    # logger setup
    level = max(10, 50 - (10 * args.v))
    print('Logging level is: {}'.format(logging.getLevelName(level)))
    logger = logging.getLogger(__name__)
    logger.setLevel(level)
    formatter = logging.Formatter('%(asctime)s: %(levelname)s:\t%(message)s')
    sh = logging.StreamHandler()
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    logger = logging.getLogger('client')
    logger.setLevel(level)
    logger.addHandler(sh)

    # main loop
    # logging.getLogger('').setLevel(logging.DEBUG)  # socketio debug
    if args.port is None:
        if args.server.startswith("https"):
            args.port = 443
        elif args.server.startswith("http"):
            args.port = 80
    socket_io = SocketIO(host=args.server, port=args.port)
    publish = socket_io.define(PublishNamespace, path='/publish')
    if args.alias:
        publish.update_alias(args.alias)

    loop = asyncio.get_event_loop()
    loop.call_soon(publish.regular_peek, loop)

    client = clients[args.client](publish, args.offset)
    publish.initialize_namespace(client)

    # loop.set_debug(True)
    # logging.getLogger('asyncio').setLevel(logging.DEBUG)
    loop.run_forever()
Пример #35
0
import asyncio

import gbulb
import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

from ui.pages.overview.main import OverviewPage
from ui.pages.account.main import AccountPage
from ui.pages.portfolio.main import PortfolioPage

gbulb.install(gtk=True)
# loop = gbulb.get_event_loop()
loop = asyncio.get_event_loop()


class MyWindow(Gtk.ApplicationWindow):
    def __init__(self, app):
        Gtk.ApplicationWindow.__init__(self, application=app)

        self.builder = Gtk.Builder()
        self.builder.add_from_file("main.glade")

        # set tabs
        main_tabs = self.builder.get_object("MainTabs")

        self.overview_tab = OverviewPage()
        main_tabs.append_page(self.overview_tab.template,
                              Gtk.Label("Overview"))
Пример #36
0
via Qubes RPC '''
# pylint: disable=invalid-name,wrong-import-position

import asyncio
import math
import os
import fcntl

import gi
gi.require_version('Gtk', '3.0')  # isort:skip
from gi.repository import Gtk, Gio, Gdk  # isort:skip

import gbulb
import pyinotify

gbulb.install()

DATA = "/var/run/qubes/qubes-clipboard.bin"
FROM = "/var/run/qubes/qubes-clipboard.bin.source"
FROM_DIR = "/var/run/qubes/"
XEVENT = "/var/run/qubes/qubes-clipboard.bin.xevent"
APPVIEWER_LOCK = "/var/run/qubes/appviewer.lock"


class EventHandler(pyinotify.ProcessEvent):
    # pylint: disable=arguments-differ
    def my_init(self, loop=None, gtk_app=None):
        '''  This method is called from ProcessEvent.__init__(). '''
        self.gtk_app = gtk_app
        self.loop = loop if loop else asyncio.get_event_loop()
Пример #37
0
 def setUp(self):
     gbulb.install()
     self.loop = asyncio.get_event_loop()
     self.bluetoothAudioBridge = BluetoothAudioBridge(self.loop)
     self.fakes = TestFakeMethods(self.bluetoothAudioBridge)
Пример #38
0
def main(argv):
    progname = argv.pop(0).rpartition('/')[2]
    parser = argparse.ArgumentParser(prog=progname)
    parser.add_argument("DEVICE", help="The joystick device name.")
    parser.add_argument('-t', '--type', default='auto',
                        help="Specify the controller type to use")
    parser.add_argument('-l', '--layout', default='distance',
                        help="Name of the layout to use")
    parser.add_argument('-T', '--theme', default='default',
                        help="Specify the theme to use")
    args = parser.parse_args(argv)

    import overlayapi as api
    api.import_all_config()

    try:
        ctype = api.CONTROLLER_TYPES[args.type]()
    except KeyError:
        raise ArgvError("no such controller type: %r" % (args.type,), parser)
    try:
        layoutcls = api.LAYOUTS[args.layout]
    except KeyError:
        raise ArgvError("no such layout: %r" % (args.layout,), parser)
    try:
        theme = api.THEMES[args.theme]()
    except KeyError:
        raise ArgvError("no such theme: %s" % (args.theme,), parser)

    import gi
    gi.require_version('Gtk', '3.0')
    import gbulb
    import gbulb.gtk
    from gi.repository import Gtk
    from live import JsWidget, LiveWorker

    asyncio.set_event_loop_policy(gbulb.gtk.GtkEventLoopPolicy())
    gbulb.install(gtk=True)
    loop = asyncio.get_event_loop()

    layout = layoutcls(ctype)
    evs = js.HandlerJsEvents()
    context = api.Context(theme, ctype, evs)

    anim = api.LiveControlsAnimation(context, layout.controls)
    anim.init()
    jswidget = JsWidget(layout, anim)

    win = Gtk.Window()
    win.connect("delete-event", lambda *args: task.cancel())
    win.set_property('decorated', False)
    screen = win.get_screen()
    argb = screen.get_rgba_visual()
    if argb:
        win.set_visual(argb)
    win.add(jswidget)
    win.show_all()

    worker = LiveWorker(args.DEVICE, evs)
    worker.on_init = lambda: jswidget.enable()
    worker.on_event = lambda: jswidget.queue_draw()
    task = asyncio.ensure_future(worker.do_work())

    with suppress(asyncio.CancelledError):
        loop.run_until_complete(task)
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
''' Sends notifications via D-Bus when something is Copy-Pasted via Qubes RPC '''

import asyncio
import math
import os
import time

import dbus
import dbus.mainloop.glib
import gbulb
import pyinotify

gbulb.install()
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)


class EventHandler(pyinotify.ProcessEvent):
    def my_init(self, loop=None):  # pylint: disable=arguments-differ
        '''  This method is called from ProcessEvent.__init__(). '''
        bus = dbus.SessionBus()
        proxy = bus.get_object('org.freedesktop.Notifications',
                               '/org/freedesktop/Notifications',
                               follow_name_owner_changes=True)
        self.notifications_iface = dbus.Interface(
            proxy, dbus_interface='org.freedesktop.Notifications')

        self.last_id = 0
        self._copy()
Пример #40
0
def main():
    p = ArgumentParser()
    p.add_argument("config")
    args = p.parse_args()

    cfg = ConfigParser()
    cfg.read(args.config)

    gbulb.install()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    loop = asyncio.get_event_loop()

    logging.basicConfig(level=cfg["log"]["level"])

    async def measure(tag):
        try:
            if not (await tag.properties.Get(DEVICE, "Connected")
                    and await tag.properties.Get(DEVICE, "ServicesResolved")
                    and hasattr(tag, "temperature")):
                return
        except AttributeError:
            return
        logger.debug("measuring on %s", tag.path)
        t0 = time.time()
        data = {}
        for k in await asyncio.gather(  # tag.temperature.measure(),
                tag.humidity.measure(),
                tag.pressure.measure(),
                # tag.light.measure(),
                # tag.motion.measure(),
        ):
            data.update(k)
        t = round((t0 + time.time()) / 2) * 1000 * 1000 * 1000
        logger.info("%s: %s", tag.path, data)
        return InfluxLineProtocol.fmt("sensortag",
                                      data,
                                      tags=dict(address=tag.address),
                                      timestamp=t)

    async def log(m):
        idb_transport, idb = await loop.create_datagram_endpoint(
            lambda: InfluxLineProtocol(loop),
            remote_addr=(cfg["influxdb_udp"]["host"],
                         int(cfg["influxdb_udp"]["port"])))

        await m.start()

        while True:
            done, pending = await asyncio.wait(
                [measure(tag) for tag in m.devices.values()],
                timeout=float(cfg["logger"]["timeout"]))
            for fut in pending:
                logger.warning("timeout on %s", fut)
                fut.cancel()
            msg = []
            for fut in done:
                try:
                    r = fut.result()
                except:
                    logger.warning("exception in measure", exc_info=True)
                else:
                    if r:
                        msg.append(r)
            if msg:
                idb.write_many(msg)
            await asyncio.sleep(float(cfg["logger"]["measure"]))

    m = TagManager()

    log_task = loop.create_task(log(m))

    discover_task = loop.create_task(
        m.auto_discover(
            float(cfg["logger"]["discover_interval"]),
            float(cfg["logger"]["discover_duration"]),
        ))

    def stop():
        logger.info("stopping")
        m._auto_discover = False
        discover_task.cancel()
        log_task.cancel()
        loop.stop()

    for sig in signal.SIGINT, signal.SIGTERM:
        loop.add_signal_handler(sig, stop)

    try:
        loop.run_forever()
    finally:
        loop.close()