Пример #1
0
def main():
    app = QApplication(sys.argv)
    #shared= QSharedMemory("wepush")
    #if shared.attach():
    #return 0
    #shared.create(1)

    #sys.stdout=common.Mystd()

    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    win = QWebEngineView()  # QWebEngineView()
    director['root_win'] = win
    #thread.start_new_thread (server.start_server,(28289,))
    #win =QWebView()
    #win.setWindowIcon(QIcon( './html/wechat.ico'))
    win.setMinimumSize(1200, 900)
    win.setWindowTitle('微信群发工具V1.0')
    url = 'file:///%s/test.html' % base_dir.replace('\\', '/')
    win.load(QUrl(url))
    win.show()

    with loop:
        from server import start_server
        #loop.set_debug(True)
        loop.run_until_complete(start_server)
        #loop.create_task(send())
        #loop.create_task(start_server)

        loop.run_forever()
Пример #2
0
def main():
    from quamash import QEventLoop, QtWidgets, QtCore
    from artiq import __artiq_dir__ as artiq_dir
    from concurrent.futures._base import CancelledError
    app = QtWidgets.QApplication(["Real Complicated Grapher"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    class mainWindow(QtWidgets.QMainWindow):
        def __init__(self):
            QtWidgets.QMainWindow.__init__(self)
            icon = QtGui.QIcon(
                os.path.join(artiq_dir, "applets", "rcg", "rcg.svg"))
            self.setWindowIcon(icon)
            self.exit_request = asyncio.Event()
            self.setWindowTitle("Real Complicated Grapher")

        def closeEvent(self, event):
            event.ignore()
            self.exit_request.set()

    main_window = mainWindow()
    dock = rcgDock(main_window)
    dock.setFloating(False)
    main_window.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock)
    main_window.show()
    try:
        loop.run_until_complete(main_window.exit_request.wait())
    except CancelledError:
        # Don't understand this
        pass
    finally:
        loop.close()
Пример #3
0
def start_qt_app(config):
    import sys
    from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMessageBox
    from quamash import QEventLoop
    from ui.main import Window
    from ui.qt_gui_connection import qSignal
    app = QApplication(sys.argv)
    
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    
    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, "Systray",
                             "I couldn't detect any system tray on this system.")
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)
    
    gui_connection = qSignal()
    window = Window(gui_connection)
    
    def closeApp():
        print("Close app signal")
        for task in asyncio.Task.all_tasks():
            print(task)
            task.cancel()
        loop.stop()
    gui_connection.closeApp.connect(closeApp)
    
    with loop:
        #asyncio.run_coroutine_threadsafe(timer(loop, config, gui_connection), loop)
        try:
            loop.run_until_complete(timer(loop, config, gui_connection))
        except asyncio.CancelledError:
            pass
Пример #4
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "browser")

    app = QtWidgets.QApplication(["ARTIQ Browser"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)

    datasets_sub = models.LocalModelManager(datasets.Model)
    datasets_sub.init({})

    smgr = state.StateManager(args.db_file)

    browser = Browser(smgr, datasets_sub, args.browse_root,
                      args.server, args.port)
    widget_log_handler.callback = browser.log.append_message

    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        browser.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    if args.select is not None:
        browser.files.select(args.select)

    browser.show()
    loop.run_until_complete(browser.exit_request.wait())
Пример #5
0
    def main(self):
        connections = dict()
        users = dict()

        # Each client will create a new protocol instance
        self.ins = ChatServerProtocol(self.db_path, connections, users)

        # GUI
        app = Qt.QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)  # NEW must set the event loop

        wnd = ServerMonitorWindow(server_instance=self.ins, parsed_args=self.args)
        wnd.show()

        with loop:
            coro = loop.create_server(lambda: self.ins, self.args["addr"], self.args["port"])
            server = loop.run_until_complete(coro)

            # Serve requests until Ctrl+C
            print('Serving on {}:{}'.format(*server.sockets[0].getsockname()))
            try:
                loop.run_forever()
            except KeyboardInterrupt:
                pass

            server.close()
            loop.run_until_complete(server.wait_closed())
            loop.close()
Пример #6
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    aw = ApplicationWindow()
    aw.show()
    loop.run_until_complete(amain(app, loop, aw))
    loop.run_forever()
Пример #7
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    aw = ApplicationWindow()
    aw.show()
    loop.run_until_complete(amain(app, loop, aw))
    loop.run_forever()
Пример #8
0
class SimpleApplet:
    def __init__(self, main_widget_class, cmd_description=None):
        self.main_widget_class = main_widget_class

        self.argparser = argparse.ArgumentParser(description=cmd_description)
        group = self.argparser.add_argument_group("data server")
        group.add_argument(
            "--server", default="::1",
            help="hostname or IP to connect to")
        group.add_argument(
            "--port", default=3250, type=int,
            help="TCP port to connect to")
        self._arggroup_datasets = self.argparser.add_argument_group("datasets")

    def add_dataset(self, name, help=None):
        if help is None:
            self._arggroup_datasets.add_argument(name)
        else:
            self._arggroup_datasets.add_argument(name, help=help)

    def args_init(self):
        self.args = self.argparser.parse_args()

    def quamash_init(self):
        app = QtWidgets.QApplication([])
        self.loop = QEventLoop(app)
        asyncio.set_event_loop(self.loop)

    def create_main_widget(self):
        self.main_widget = self.main_widget_class(self.args)
        self.main_widget.show()

    def sub_init(self, data):
        self.data = data
        return data

    def sub_mod(self, mod):
        self.main_widget.data_changed(self.data, mod)

    def create_subscriber(self):
        self.subscriber = Subscriber("datasets",
                                     self.sub_init, self.sub_mod)
        self.loop.run_until_complete(self.subscriber.connect(
            self.args.server, self.args.port))

    def run(self):
        self.args_init()
        self.quamash_init()
        try:
            self.create_main_widget()
            self.create_subscriber()
            try:
                self.loop.run_forever()
            finally:
                self.loop.run_until_complete(self.subscriber.close())
        finally:
            self.loop.close()
Пример #9
0
def main() -> int:
    """
    This is the main entry point of the application.
    We must import packages here, in the function, rather than globally, because the logging subsystem
    must be set up correctly at the import time.
    """
    import atexit
    import asyncio
    import datetime
    from PyQt5.QtWidgets import QApplication
    from quamash import QEventLoop
    from . import data_dir, version, resources
    from .fuhrer import Fuhrer

    data_dir.init()

    # Only the main process will be logging into the file
    log_file_name = os.path.join(
        data_dir.LOG_DIR,
        f'{datetime.datetime.now():%Y%m%d-%H%M%S}-{os.getpid()}.log')
    file_handler = logging.FileHandler(log_file_name)
    file_handler.setLevel(LOGGING_LEVEL)
    file_handler.setFormatter(
        logging.Formatter(
            '%(asctime)s pid=%(process)-5d %(levelname)-8s %(name)s: %(message)s'
        ))
    logging.root.addHandler(file_handler)

    if '--profile' in sys.argv:
        try:
            # noinspection PyPep8Naming
            import cProfile as profile
        except ImportError:
            import profile

        def save_profile():
            prof.disable()
            prof.dump_stats(log_file_name.replace('.log', '.pstat'))

        prof = profile.Profile()
        atexit.register(save_profile)
        prof.enable()

    # Configuring the event loop
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    # Running the application
    _logger.info('Starting version %r; package root: %r', version.__version__,
                 resources.PACKAGE_ROOT)
    with loop:
        ctrl = Fuhrer()
        loop.run_until_complete(ctrl.run())

    return 0
Пример #10
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    init_logger(args)

    app = QtWidgets.QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    datasets_sub = models.LocalModelManager(datasets.Model)

    # initialize main window
    main_window = MainWindow()
    smgr.register(main_window)
    status_bar = QtWidgets.QStatusBar()
    main_window.setStatusBar(status_bar)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    d_results = results.ResultsBrowser(datasets_sub)
    smgr.register(d_results)

    d_applets = applets.AppletsDock(main_window, datasets_sub)
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)

    d_datasets = datasets.DatasetsDock(datasets_sub)
    smgr.register(d_datasets)

    main_window.setCentralWidget(d_results)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_applets)
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, d_datasets)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()

    smgr.load()

    if args.PATH:
        d_results.select(args.PATH)

    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Пример #11
0
def main():
    app = QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)

    win = MainWindow(app, None)

    container = QtWidgets.QWidget(win)
    layout = QtWidgets.QGridLayout()
    container.setLayout(layout)
    scanner = scanwidget.ScanWidget()
    layout.addWidget(scanner, 0, 0, 1, -1)

    spinboxes = [QtWidgets.QDoubleSpinBox(), QtWidgets.QDoubleSpinBox(), QtWidgets.QSpinBox()]
    for s in spinboxes:
        if type(s) is QtWidgets.QDoubleSpinBox:
            s.setDecimals(13)
            s.setMaximum(float("Inf"))
            s.setMinimum(float("-Inf"))
        else:
            s.setMinimum(1)
            s.setValue(10)

    for (col, w) in enumerate(
        [
            QtWidgets.QLabel("Start"),
            spinboxes[0],
            QtWidgets.QLabel("Stop"),
            spinboxes[1],
            QtWidgets.QLabel("Points"),
            spinboxes[2],
        ]
    ):
        layout.addWidget(w, 1, col)

    scanner.sigMinMoved.connect(spinboxes[0].setValue)
    scanner.sigMaxMoved.connect(spinboxes[1].setValue)
    # scanner.sigNumChanged.connect(spinboxes[2].setValue)
    spinboxes[0].valueChanged.connect(scanner.setMin)
    spinboxes[1].valueChanged.connect(scanner.setMax)
    # spinboxes[2].valueChanged.connect(scanner.setNumPoints)

    win.setCentralWidget(container)
    win.show()
    scanner.fitToView()
    loop.run_until_complete(win.exit_request.wait())
Пример #12
0
class KnechtQT:
    def __init__(self, args):
        self.port = args.port
        self.address = args.listen

        self.app = None
        self.window = None
        self.loop = None

    def _close_window(self):
        if self.window:
            self.window.showNormal()
            self.window.hide()
            self.window.close()
            self.window = None

    def show_text(self, text, duration=None):
        if duration is None or duration <= 0:
            duration = 10

        if self.window:
            self._close_window()

        try:
            subprocess.call(['xset', 'dpms', 'force', 'on'])
        except FileNotFoundError as e:
            pass

        label = QLabel()
        label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        label.setTextFormat(Qt.RichText)
        label.setWordWrap(True)
        label.setText('<span style="font-size:100px">%s</span>' % text)

        self.window = QMainWindow()
        self.window.setWindowTitle("KnechtQT")
        self.window.setCentralWidget(label)

        self.window.showFullScreen()

        self.loop.call_later(duration, self._close_window)

    def launch(self):
        self.app = QApplication([])
        self.app.setQuitOnLastWindowClosed(False)
        self.loop = QEventLoop(self.app)
        asyncio.set_event_loop(self.loop)

        signal.signal(signal.SIGINT, signal.SIG_DFL)

        with self.loop:
            coro = self.loop.create_server(lambda: CommandReceiver(self),
                                           self.address, self.port)
            server = self.loop.run_until_complete(coro)

            self.loop.run_forever()

            server.close()
            loop.run_until_complete(server.wait_closed())
Пример #13
0
def main():
    logging.basicConfig(level=logging.INFO)
    app = QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)

    win = MainWindow(app, None)

    container = QtWidgets.QWidget(win)
    layout = QtWidgets.QGridLayout()
    container.setLayout(layout)

    scanner = ScanWidget()
    scanner.setFocusPolicy(QtCore.Qt.StrongFocus)
    layout.addWidget(scanner, 0, 0, -1, 1)

    spinbox = ScientificSpinBox()
    spinbox.setFocusPolicy(QtCore.Qt.StrongFocus)
    spinbox.setStyleSheet("QDoubleSpinBox {color:blue}")
    spinbox.setMinimumSize(110, 0)
    layout.addWidget(spinbox, 0, 1)
    scanner.startChanged.connect(spinbox.setValue)
    spinbox.valueChanged.connect(scanner.setStart)
    scanner.setStart(-100)

    spinbox = QtWidgets.QSpinBox()
    spinbox.setFocusPolicy(QtCore.Qt.StrongFocus)
    spinbox.setMinimum(1)
    spinbox.setMaximum((1 << 31) - 1)
    layout.addWidget(spinbox, 1, 1)
    scanner.numChanged.connect(spinbox.setValue)
    spinbox.valueChanged.connect(scanner.setNum)
    scanner.setNum(11)

    spinbox = ScientificSpinBox()
    spinbox.setFocusPolicy(QtCore.Qt.StrongFocus)
    spinbox.setStyleSheet("QDoubleSpinBox {color:red}")
    layout.addWidget(spinbox, 2, 1)
    scanner.stopChanged.connect(spinbox.setValue)
    spinbox.valueChanged.connect(scanner.setStop)
    scanner.setStop(200)

    win.setCentralWidget(container)
    win.show()
    loop.run_until_complete(win.exit_request.wait())
Пример #14
0
def main( argv ):
    # Setup the main event loop that will drive the chat client.
    app = ClientApp( argv )
    main_loop = QEventLoop( app )
    asyncio.set_event_loop( main_loop )

    # Through a brilliant stroke of misfortune, it turns out on Windows the quamash library, which
    # provides the asyncio event loop that interops with Qt, derives from asyncio's ProactorEventLoop,
    # which does NOT support the creation of datagram (UDP) endpoints. If it were possible to change
    # the loop to one based on SelectorEventLoop, then UDP endpoints could be supported, but that's
    # outside my control.
    #
    # To avoid gutting the asynchronous code from the app and starting over with a different socket
    # API, we setup a separate thread to handle UDP traffic with a SelectorEventLoop. We then
    # communicate between the two event loops by submitting coroutines as tasks to the appropriate
    # event loop. It sucks and is ugly but better than rearchitecting late in the game.
    #
    datagram_channel_loop = asyncio.SelectorEventLoop( selectors.SelectSelector() )
    datagram_channel_thread = DatagramChannelThread( datagram_channel_loop )

    # Create the top-level app model state for the chat client.
    app_model = AppModel( main_loop, datagram_channel_thread )

    cli = app.parse_command_line()
    app_model.screenName = cli.screen_name
    app_model.serverAddress = cli.server_address
    app_model.serverPort = cli.server_port

    # Initialize the UI.
    qmlRegisterUncreatableType( AppModel, "Chatter.Client", 1, 0, "AppModel", "AppModel cannot be craeted in QML." )
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty( "appModel", app_model )
    engine.load( "client.qml" )

    with main_loop:
        datagram_channel_thread.start()
        main_loop.run_until_complete( app_model._client_stopped )
        datagram_channel_thread.join()
        print( "Leaving app" )
Пример #15
0
    def __init__(self, serial, printHz=False, bufsize=2048, baudrate=1e6):
        super().__init__()

        self.serial = serial
        self.baudrate = baudrate
        self.bufsize = bufsize
        self.run = True
        self.fs = 80000
        self.c = 34300

        # Filter parameters
        self.alpha = 0.05
        self.cutoff = 100
        self.order = 5

        # Touch detection parameters
        self.threshold = 180.0

        # Creating plot window
        app = QtGui.QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)
        self.resize(800, 400)

        # App ranges
        self.ranges = {'a': (20, 53), 'b': (62, 101), 'c': (110, 150)}

        # Plotting parameters
        p = self.addPlot()
        self.plotline = p.plot(pen='y')
        self.baseline = p.plot(pen='b')
        self.l = pg.TextItem()
        self.l.setText('')
        self.l.setColor('y')
        self.l.setTextWidth(500)
        p.addItem(self.l)
        self.show()

        loop.run_until_complete(self.read_data())
Пример #16
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    if args.db_file is None:
        args.db_file = os.path.join(get_user_config_dir(),
                                    "artiq_browser.pyon")
    widget_log_handler = log.init_log(args, "browser")

    app = QtWidgets.QApplication(["ARTIQ Browser"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    # https://github.com/harvimt/quamash/issues/123
    if sys.version_info >= (3, 8):
        asyncio.events._set_running_loop(loop)
    atexit.register(loop.close)

    datasets_sub = models.LocalModelManager(datasets.Model)
    datasets_sub.init({})

    smgr = state.StateManager(args.db_file)

    browser = Browser(smgr, datasets_sub, args.browse_root, args.server,
                      args.port)
    widget_log_handler.callback = browser.log.append_message

    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        browser.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    if args.select is not None:
        browser.files.select(args.select)

    browser.show()
    loop.run_until_complete(browser.exit_request.wait())
Пример #17
0
def start_qt_app(config):
    import sys
    from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMessageBox
    from quamash import QEventLoop
    from ui.main import Window
    from ui.qt_gui_connection import qSignal
    app = QApplication(sys.argv)

    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(
            None, "Systray",
            "I couldn't detect any system tray on this system.")
        sys.exit(1)

    QApplication.setQuitOnLastWindowClosed(False)

    gui_connection = qSignal()
    window = Window(gui_connection)

    def closeApp():
        print("Close app signal")
        for task in asyncio.Task.all_tasks():
            print(task)
            task.cancel()
        loop.stop()

    gui_connection.closeApp.connect(closeApp)

    with loop:
        #asyncio.run_coroutine_threadsafe(timer(loop, config, gui_connection), loop)
        try:
            loop.run_until_complete(timer(loop, config, gui_connection))
        except asyncio.CancelledError:
            pass
Пример #18
0
    def main(self):

        # create event loop
        app = Qt.QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)  # NEW must set the event loop

        # authentication process
        auth_ = ClientAuth(db_path=self.db_path)
        login_wnd = LoginWindow(auth_instance=auth_)

        if login_wnd.exec_() == QtWidgets.QDialog.Accepted:
            # Each client will create a new protocol instance
            client_ = ChatClientProtocol(db_path=self.db_path,
                                         loop=loop,
                                         username=login_wnd.username,
                                         password=login_wnd.password)

            # create Contacts window
            wnd = ContactsWindow(client_instance=client_, user_name=login_wnd.username)
            client_.gui_instance = wnd  # reference from protocol to GUI, for msg update

            with loop:
                # cleaning old instances
                del auth_
                del login_wnd

                # connect to our server
                try:
                    coro = loop.create_connection(lambda: client_, self.args["addr"], self.args["port"])
                    server = loop.run_until_complete(coro)
                except ConnectionRefusedError:
                    print('Error. wrong server')
                    exit(1)

                # start GUI client
                wnd.show()
                client_.get_from_gui()  # asyncio.ensure_future(client_.get_from_gui(loop))

                # Serve requests until Ctrl+C
                try:
                    loop.run_forever()
                except KeyboardInterrupt:
                    pass
                except Exception:
                    pass
Пример #19
0
            window = engine.rootObjects()[0]
            myObject = window.findChild(QObject, "myObject")
            #loop.call_soon(myObject.funcRetClicked())
            #myObject.funcRetClicked()
            loop.run_in_executor(exec, myObject.funcRetClicked)
        '''

with loop:
    try:
        test = Test()
        service = Service(loop)

        #loop.run_forever()

        print('1')
        # rootObjects 실행전 context를 선언/추가해줍니다.
        ctx = engine.rootContext()
        ctx.setContextProperty('Service', service)

        #engine.load("main.qml")
        engine.load("qml/tytrader.qml")
        window = engine.rootObjects()[0]
        #window.setContextProperty('Service', service)

        loop.run_until_complete(test.printInterval())
        loop.run_forever()
    except:
        pass


Пример #20
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "dashboard")

    app = QtWidgets.QApplication(["ARTIQ Dashboard"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(client.connect_rpc(args.server, args.port_control, "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    sub_clients = dict()
    for notifier_name, modelf in (
        ("explist", explorer.Model),
        ("explist_status", explorer.StatusUpdater),
        ("datasets", datasets.Model),
        ("schedule", schedule.Model),
    ):
        subscriber = ModelSubscriber(notifier_name, modelf)
        loop.run_until_complete(subscriber.connect(args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    log_receiver = Receiver("log", [])
    loop.run_until_complete(log_receiver.connect(args.server, args.port_broadcast))
    atexit_register_coroutine(log_receiver.close)

    # initialize main window
    main_window = MainWindow(args.server)
    smgr.register(main_window)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(
        main_window,
        sub_clients["explist"],
        sub_clients["schedule"],
        rpc_clients["schedule"],
        rpc_clients["experiment_db"],
    )
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(
        expmgr,
        d_shortcuts,
        sub_clients["explist"],
        sub_clients["explist_status"],
        rpc_clients["schedule"],
        rpc_clients["experiment_db"],
    )
    smgr.register(d_explorer)

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"], rpc_clients["dataset_db"])
    smgr.register(d_datasets)

    d_applets = applets.AppletsDock(main_window, sub_clients["datasets"])
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)

    d_ttl_dds = moninj.MonInj()
    loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
    atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(rpc_clients["schedule"], sub_clients["schedule"])
    smgr.register(d_schedule)

    logmgr = log.LogDockManager(main_window)
    smgr.register(logmgr)
    log_receiver.notify_cbs.append(logmgr.append_message)
    widget_log_handler.callback = logmgr.append_message

    # lay out docks
    right_docks = [d_explorer, d_shortcuts, d_ttl_dds.ttl_dock, d_ttl_dds.dds_dock, d_datasets, d_applets]
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, right_docks[0])
    for d1, d2 in zip(right_docks, right_docks[1:]):
        main_window.tabifyDockWidget(d1, d2)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_schedule, d_log0)

    logging.info("ARTIQ dashboard %s connected to %s", artiq_version, args.server)

    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Пример #21
0
                # some process
            #print('elapsed:{}'.format(self.elapsed))
            if self.elapsed < 1:
                step = 1 - self.elapsed
            else :
                step = 1
            #self.elapsed > 1 ? (step = 2 - self.elapsed) : step = 1
            #print('step:{}'.format(step))
            yield from asyncio.sleep(step)


with loop:
    window = MyWindow(loop)
    #asyncio.async(window.initialize())
    window.initialize()
    window.show()
    loop.run_until_complete(window.connect_and_timer())
    #loop.run_until_complete(window.initialize())
    #loop.call_soon(window.initialize())
    loop.run_forever()

'''
if __name__ == "__main__":
    QCoreApplication.setLibraryPaths([qt5_url])

    #app = QApplication(sys.argv)
    window = MyWindows()
    window.show()
    #app.exec_()
'''
Пример #22
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    init_logger(args)

    app = QtGui.QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(client.connect_rpc(
            args.server, args.port_control, "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    sub_clients = dict()
    for notifier_name, module in (("explist", explorer),
                                  ("datasets", datasets),
                                  ("schedule", schedule),
                                  ("log", log)):
        subscriber = ModelSubscriber(notifier_name, module.Model)
        loop.run_until_complete(subscriber.connect(
            args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    # initialize main window
    win = MainWindow(args.server)
    dock_area = dockarea.DockArea()
    smgr.register(dock_area)
    smgr.register(win)
    win.setCentralWidget(dock_area)
    status_bar = QtGui.QStatusBar()
    status_bar.showMessage("Connected to {}".format(args.server))
    win.setStatusBar(status_bar)

    # create UI components
    expmgr = experiments.ExperimentManager(status_bar, dock_area,
                                           sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(win, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(status_bar, expmgr, d_shortcuts,
                                       sub_clients["explist"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"])

    d_datasets = datasets.DatasetsDock(win, dock_area, sub_clients["datasets"])
    smgr.register(d_datasets)

    if os.name != "nt":
        d_ttl_dds = moninj.MonInj()
        loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
        atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(
        status_bar, rpc_clients["schedule"], sub_clients["schedule"])

    logmgr = log.LogDockManager(dock_area, sub_clients["log"])
    smgr.register(logmgr)

    d_console = console.ConsoleDock(sub_clients["datasets"],
                                    rpc_clients["dataset_db"])

    # lay out docks
    if os.name != "nt":
        dock_area.addDock(d_ttl_dds.dds_dock, "top")
        dock_area.addDock(d_ttl_dds.ttl_dock, "above", d_ttl_dds.dds_dock)
        dock_area.addDock(d_datasets, "above", d_ttl_dds.ttl_dock)
    else:
        dock_area.addDock(d_datasets, "top")
    dock_area.addDock(d_shortcuts, "above", d_datasets)
    dock_area.addDock(d_explorer, "above", d_shortcuts)
    dock_area.addDock(d_console, "bottom")
    dock_area.addDock(d_schedule, "above", d_console)

    # load/initialize state
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        dock_area.addDock(d_log0, "right", d_explorer)

    # run
    win.show()
    loop.run_until_complete(win.exit_request.wait())
Пример #23
0
class SimpleApplet:
    def __init__(self,
                 main_widget_class,
                 cmd_description=None,
                 default_update_delay=0.0):
        self.main_widget_class = main_widget_class

        self.argparser = argparse.ArgumentParser(description=cmd_description)

        self.argparser.add_argument(
            "--update-delay",
            type=float,
            default=default_update_delay,
            help="time to wait after a mod (buffering other mods) "
            "before updating (default: %(default).2f)")

        group = self.argparser.add_argument_group("standalone mode (default)")
        group.add_argument("--server",
                           default="::1",
                           help="hostname or IP of the master to connect to "
                           "for dataset notifications "
                           "(ignored in embedded mode)")
        group.add_argument("--port",
                           default=3250,
                           type=int,
                           help="TCP port to connect to")

        self.argparser.add_argument("--embed",
                                    default=None,
                                    help="embed into GUI",
                                    metavar="IPC_ADDRESS")

        self._arggroup_datasets = self.argparser.add_argument_group("datasets")

        self.dataset_args = set()

    def add_dataset(self, name, help=None, required=True):
        kwargs = dict()
        if help is not None:
            kwargs["help"] = help
        if required:
            self._arggroup_datasets.add_argument(name, **kwargs)
        else:
            self._arggroup_datasets.add_argument("--" + name, **kwargs)
        self.dataset_args.add(name)

    def args_init(self):
        self.args = self.argparser.parse_args()
        self.datasets = {
            getattr(self.args, arg.replace("-", "_"))
            for arg in self.dataset_args
        }

    def quamash_init(self):
        app = QtWidgets.QApplication([])
        self.loop = QEventLoop(app)
        asyncio.set_event_loop(self.loop)

    def ipc_init(self):
        if self.args.embed is not None:
            self.ipc = AppletIPCClient(self.args.embed)
            self.loop.run_until_complete(self.ipc.connect())

    def ipc_close(self):
        if self.args.embed is not None:
            self.ipc.close()

    def create_main_widget(self):
        self.main_widget = self.main_widget_class(self.args)
        if self.args.embed is not None:
            self.ipc.set_close_cb(self.main_widget.close)
            if os.name == "nt":
                # HACK: if the window has a frame, there will be garbage
                # (usually white) displayed at its right and bottom borders
                #  after it is embedded.
                self.main_widget.setWindowFlags(QtCore.Qt.FramelessWindowHint)
                self.main_widget.show()
                win_id = int(self.main_widget.winId())
                self.loop.run_until_complete(self.ipc.embed(win_id))
            else:
                # HACK:
                # Qt window embedding is ridiculously buggy, and empirical
                # testing has shown that the following procedure must be
                # followed exactly on Linux:
                # 1. applet creates widget
                # 2. applet creates native window without showing it, and
                #    gets its ID
                # 3. applet sends the ID to host, host embeds the widget
                # 4. applet shows the widget
                # 5. parent resizes the widget
                win_id = int(self.main_widget.winId())
                self.loop.run_until_complete(self.ipc.embed(win_id))
                self.main_widget.show()
                self.ipc.fix_initial_size()
        else:
            self.main_widget.show()

    def sub_init(self, data):
        self.data = data
        return data

    def filter_mod(self, mod):
        if self.args.embed is not None:
            # the parent already filters for us
            return True

        if mod["action"] == "init":
            return True
        if mod["path"]:
            return mod["path"][0] in self.datasets
        elif mod["action"] in {"setitem", "delitem"}:
            return mod["key"] in self.datasets
        else:
            return False

    def emit_data_changed(self, data, mod_buffer):
        self.main_widget.data_changed(data, mod_buffer)

    def flush_mod_buffer(self):
        self.emit_data_changed(self.data, self.mod_buffer)
        del self.mod_buffer

    def sub_mod(self, mod):
        if not self.filter_mod(mod):
            return

        if self.args.update_delay:
            if hasattr(self, "mod_buffer"):
                self.mod_buffer.append(mod)
            else:
                self.mod_buffer = [mod]
                asyncio.get_event_loop().call_later(self.args.update_delay,
                                                    self.flush_mod_buffer)
        else:
            self.emit_data_changed(self.data, [mod])

    def subscribe(self):
        if self.args.embed is None:
            self.subscriber = Subscriber("datasets", self.sub_init,
                                         self.sub_mod)
            self.loop.run_until_complete(
                self.subscriber.connect(self.args.server, self.args.port))
        else:
            self.ipc.subscribe(self.datasets, self.sub_init, self.sub_mod)

    def unsubscribe(self):
        if self.args.embed is None:
            self.loop.run_until_complete(self.subscriber.close())

    def run(self):
        self.args_init()
        self.quamash_init()
        try:
            self.ipc_init()
            try:
                self.create_main_widget()
                self.subscribe()
                try:
                    self.loop.run_forever()
                finally:
                    self.unsubscribe()
            finally:
                self.ipc_close()
        finally:
            self.loop.close()
Пример #24
0
def main():
    args = get_argparser().parse_args()
    init_logger(args)

    app = QtGui.QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(lambda: loop.close())

    smgr = StateManager(args.db_file)

    schedule_ctl = AsyncioClient()
    loop.run_until_complete(schedule_ctl.connect_rpc(
        args.server, args.port_control, "master_schedule"))
    atexit.register(lambda: schedule_ctl.close_rpc())

    win = MainWindow(app, args.server)
    area = dockarea.DockArea()
    smgr.register(area)
    smgr.register(win)
    win.setCentralWidget(area)
    status_bar = QtGui.QStatusBar()
    status_bar.showMessage("Connected to {}".format(args.server))
    win.setStatusBar(status_bar)

    d_explorer = ExplorerDock(win, status_bar, schedule_ctl)
    smgr.register(d_explorer)
    loop.run_until_complete(d_explorer.sub_connect(
        args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_explorer.sub_close()))

    d_datasets = DatasetsDock(win, area)
    smgr.register(d_datasets)
    loop.run_until_complete(d_datasets.sub_connect(
        args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_datasets.sub_close()))

    if os.name != "nt":
        d_ttl_dds = MonInj()
        loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
        atexit.register(lambda: loop.run_until_complete(d_ttl_dds.stop()))

    if os.name != "nt":
        area.addDock(d_ttl_dds.dds_dock, "top")
        area.addDock(d_ttl_dds.ttl_dock, "above", d_ttl_dds.dds_dock)
        area.addDock(d_datasets, "above", d_ttl_dds.ttl_dock)
    else:
        area.addDock(d_datasets, "top")
    area.addDock(d_explorer, "above", d_datasets)

    d_schedule = ScheduleDock(status_bar, schedule_ctl)
    loop.run_until_complete(d_schedule.sub_connect(
        args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_schedule.sub_close()))

    d_log = LogDock()
    smgr.register(d_log)
    loop.run_until_complete(d_log.sub_connect(
        args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_log.sub_close()))

    dataset_db = AsyncioClient()
    loop.run_until_complete(dataset_db.connect_rpc(
        args.server, args.port_control, "master_dataset_db"))
    atexit.register(lambda: dataset_db.close_rpc())
    def _set_dataset(k, v):
        asyncio.ensure_future(dataset_db.set(k, v))
    def _del_dataset(k):
        asyncio.ensure_future(dataset_db.delete(k))
    d_console = ConsoleDock(
        d_datasets.get_dataset,
        _set_dataset,
        _del_dataset)

    area.addDock(d_console, "bottom")
    area.addDock(d_log, "above", d_console)
    area.addDock(d_schedule, "above", d_log)

    smgr.load()
    smgr.start()
    atexit.register(lambda: loop.run_until_complete(smgr.stop()))
    win.show()
    loop.run_until_complete(win.exit_request.wait())
Пример #25
0
class WandGUI():
    def __init__(self):

        self.args = args = get_argparser().parse_args()
        init_logger_from_args(args)

        if args.log_to_file:
            log_file = pkg_resources.resource_filename("wand", "log.txt")
            fh = logging.FileHandler(log_file, mode="wt")
            fh.setLevel(logger.getEffectiveLevel())
            logger.addHandler(fh)
            logging.getLogger("quamash").addHandler(fh)
            sys.excepthook = lambda exc_type, exc_value, exc_traceback: \
                logger.exception("".join(
                    traceback.format_exception(exc_type,
                                               exc_value,
                                               exc_traceback)))

        self.config = load_config(args, "_gui")

        self.laser_db = {}
        self.freq_db = {}
        self.osa_db = {}
        self.subscribers = {}

        self.qapp = QtWidgets.QApplication(["WAnD"])
        self.loop = QEventLoop(self.qapp)
        asyncio.set_event_loop(self.loop)
        atexit.register(self.loop.close)

        # set program icon
        icon = QtGui.QIcon()
        icon.addFile(pkg_resources.resource_filename("wand", "wand.svg"))
        self.qapp.setWindowIcon(icon)

        # create main window
        self.win = MainWindow()
        self.area = dock.DockArea()
        self.win.setCentralWidget(self.area)
        self.win.setWindowTitle("Super-duper Python Wavemeter Viewer!")

        # populate GUI
        self.laser_displays = {}
        for row in self.config["layout"]:
            prev = None
            pos = 'bottom'
            for display_name in row:
                display = LaserDisplay(display_name, self)
                self.laser_displays.update({display.laser: display})
                self.area.addDock(display.dock, position=pos, relativeTo=prev)
                pos = 'right'
                prev = display.dock

    def notifier_cb(self, db, server, mod):
        """ Called whenever we get new data from a server "notifier" interface.

        NB sync_struct takes care of updating the relevant db for us, so all we
        do here is call the relevant GUI update function.
        """
        if mod["action"] == "init":
            self.subscribers[server][db]["connected"] = True

        # check we're fully connected to the server before processing updates
        if (not self.subscribers[server]["laser_db"]["connected"]
                or not self.subscribers[server]["freq_db"]["connected"]
                or not self.subscribers[server]["osa_db"]["connected"]):
            return

        if mod["action"] == "init":
            # called when we first connect to a Notifier
            # we only activate the GUI channel for a laser once we have initial
            # data from all three Notifier interfaces (laser, freq, osa)
            displays = self.laser_displays

            for laser in mod["struct"].keys():
                if laser not in self.laser_displays.keys():
                    continue

                if displays[laser].server not in [server, ""]:
                    logger.error("laser '{}' found on multiple servers")
                    displays.server = ""
                else:
                    displays[laser].server = server

                displays[laser].wake_loop.set()

        elif mod["action"] == "setitem":
            if mod["path"] == []:
                laser = mod["key"]
            else:
                laser = mod["path"][0]

            if laser not in self.laser_displays.keys():
                return

            if db == "freq_db":
                self.laser_displays[laser].update_freq()
            elif db == "osa_db":
                self.laser_displays[laser].update_osa_trace()
            elif db == "laser_db":
                if mod["key"] == "f_ref":
                    self.laser_displays[laser].update_reference()
                elif (mod["key"] == "exposure" or
                      (len(mod["path"]) > 1 and mod["path"][1] == "exposure")):
                    self.laser_displays[laser].update_exposure()
                elif mod["key"] == "fast_mode":
                    self.laser_displays[laser].update_fast_mode()
                elif mod["key"] == "auto_exposure":
                    self.laser_displays[laser].update_auto_exposure()
                elif mod["key"] in ["locked", "lock_owner"]:
                    self.laser_displays[laser].update_laser_status()
            else:
                raise ValueError("Unexpected notifier interface")
        else:
            raise ValueError(
                "Unexpected 'notifier' modification: {}".format(mod))

    def start(self):
        """ Connect to the WaND servers """
        def init_cb(db, mod):
            db.update(mod)
            return db

        async def subscriber_reconnect(self, server, db):
            logger.info("No connection to server '{}'".format(server))

            for _, display in self.laser_displays.items():
                if display.server == server:
                    display.server = ""
                    display.wake_loop.set()

            server_cfg = self.config["servers"][server]
            subscriber = self.subscribers[server][db]["subscriber"]

            if self.win.exit_request.is_set():
                return

            def make_fut(self, server, db):
                fut = asyncio.ensure_future(
                    subscriber_reconnect(self, server, db))
                self.subscribers[server][db]["connected"] = False
                self.subscribers[server][db]["future"] = fut

            subscriber.disconnect_cb = functools.partial(
                make_fut, self, server, db)

            while not self.win.exit_request.is_set():
                try:
                    await subscriber.connect(server_cfg["host"],
                                             server_cfg["notify"])

                    logger.info("Reconnected to server '{}'".format(server))
                    break
                except OSError:
                    logger.info(
                        "could not connect to '{}' retry in 10s...".format(
                            server))
                    await asyncio.sleep(10)

        for server, server_cfg in self.config["servers"].items():
            self.subscribers[server] = {}

            # ask the servers to keep us updated with changes to laser settings
            # (exposures, references, etc)
            subscriber = Subscriber(
                "laser_db", functools.partial(init_cb, self.laser_db),
                functools.partial(self.notifier_cb, "laser_db", server))
            fut = asyncio.ensure_future(
                subscriber_reconnect(self, server, "laser_db"))
            self.subscribers[server]["laser_db"] = {
                "subscriber": subscriber,
                "connected": False,
                "future": fut
            }

            # ask the servers to keep us updated with the latest frequency data
            subscriber = Subscriber(
                "freq_db", functools.partial(init_cb, self.freq_db),
                functools.partial(self.notifier_cb, "freq_db", server))
            fut = asyncio.ensure_future(
                subscriber_reconnect(self, server, "freq_db"))
            self.subscribers[server]["freq_db"] = {
                "subscriber": subscriber,
                "connected": False,
                "future": fut
            }

            # ask the servers to keep us updated with the latest osa traces
            subscriber = Subscriber(
                "osa_db", functools.partial(init_cb, self.osa_db),
                functools.partial(self.notifier_cb, "osa_db", server))
            fut = asyncio.ensure_future(
                subscriber_reconnect(self, server, "osa_db"))
            self.subscribers[server]["osa_db"] = {
                "subscriber": subscriber,
                "connected": False,
                "future": fut
            }

        atexit_register_coroutine(self.shutdown)

        self.win.showMaximized()
        atexit.register(self.win.exit_request.set)
        self.loop.run_until_complete(self.win.exit_request.wait())

    async def shutdown(self):
        self.win.exit_request.set()

        for _, server in self.subscribers.items():
            for _, subs_dict in server.items():
                subs = subs_dict["subscriber"]
                fut = subs_dict["future"]
                try:
                    await subs.close()
                except Exception:
                    pass
                if fut is not None and not fut.done():
                    fut.cancel()
        for _, display in self.laser_displays.items():
            display.fut.cancel()
Пример #26
0
    while 1:
        if await dr.connect():
            print("蓝牙连接成功......")
            break

    mAutoJoy = auto_joy.AutoJoy(dr, date_list_[0], date_list_[1],
                                date_list_[2])
    await mAutoJoy.run_in_gui()
    logger.info('Stopping communication...')
    await transport.close()


if __name__ == '__main__':
    # check if root
    if not os.geteuid() == 0:
        raise PermissionError('Script must be run as root!')

    app = QApplication(sys.argv)

    mMainWindow = MainWindow()
    mMainWindow.show()

    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    date_list_num = [2020, 3, 10]
    with loop:
        loop.run_until_complete(_main(date_list_num))

    # start.
Пример #27
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "dashboard")

    if args.db_file is None:
        args.db_file = os.path.join(get_user_config_dir(),
                           "artiq_dashboard_{server}_{port}.pyon".format(
                            server=args.server.replace(":","."),
                            port=args.port_notify))

    app = QtWidgets.QApplication(["ARTIQ Dashboard"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(client.connect_rpc(
            args.server, args.port_control, "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    config = Client(args.server, args.port_control, "master_config")
    try:
        server_name = config.get_name()
    finally:
        config.close_rpc()

    disconnect_reported = False
    def report_disconnect():
        nonlocal disconnect_reported
        if not disconnect_reported:
            logging.error("connection to master lost, "
                          "restart dashboard to reconnect")
        disconnect_reported = True

    sub_clients = dict()
    for notifier_name, modelf in (("explist", explorer.Model),
                                  ("explist_status", explorer.StatusUpdater),
                                  ("datasets", datasets.Model),
                                  ("schedule", schedule.Model)):
        subscriber = ModelSubscriber(notifier_name, modelf,
            report_disconnect)
        loop.run_until_complete(subscriber.connect(
            args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    broadcast_clients = dict()
    for target in "log", "ccb":
        client = Receiver(target, [], report_disconnect)
        loop.run_until_complete(client.connect(
            args.server, args.port_broadcast))
        atexit_register_coroutine(client.close)
        broadcast_clients[target] = client

    # initialize main window
    main_window = MainWindow(args.server if server_name is None else server_name)
    smgr.register(main_window)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(main_window,
                                           sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(expmgr, d_shortcuts,
                                       sub_clients["explist"],
                                       sub_clients["explist_status"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"])
    smgr.register(d_explorer)

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"],
                                       rpc_clients["dataset_db"])
    smgr.register(d_datasets)

    d_applets = applets_ccb.AppletsCCBDock(main_window, sub_clients["datasets"])
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)
    broadcast_clients["ccb"].notify_cbs.append(d_applets.ccb_notify)

    d_ttl_dds = moninj.MonInj()
    loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
    atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(
        rpc_clients["schedule"], sub_clients["schedule"])
    smgr.register(d_schedule)

    logmgr = log.LogDockManager(main_window)
    smgr.register(logmgr)
    broadcast_clients["log"].notify_cbs.append(logmgr.append_message)
    widget_log_handler.callback = logmgr.append_message

    # lay out docks
    right_docks = [
        d_explorer, d_shortcuts,
        d_ttl_dds.ttl_dock, d_ttl_dds.dds_dock, d_ttl_dds.dac_dock,
        d_datasets, d_applets
    ]
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, right_docks[0])
    for d1, d2 in zip(right_docks, right_docks[1:]):
        main_window.tabifyDockWidget(d1, d2)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_schedule, d_log0)


    if server_name is not None:
        server_description = server_name + " ({})".format(args.server)
    else:
        server_description = args.server
    logging.info("ARTIQ dashboard %s connected to %s",
                 artiq_version, server_description)

    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Пример #28
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    init_logger(args)

    app = QtWidgets.QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(client.connect_rpc(
            args.server, args.port_control, "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    sub_clients = dict()
    for notifier_name, module in (("explist", explorer),
                                  ("datasets", datasets),
                                  ("schedule", schedule),
                                  ("log", log)):
        subscriber = ModelSubscriber(notifier_name, module.Model)
        loop.run_until_complete(subscriber.connect(
            args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    # initialize main window
    main_window = MainWindow(args.server)
    smgr.register(main_window)
    status_bar = QtWidgets.QStatusBar()
    status_bar.showMessage("Connected to {}".format(args.server))
    main_window.setStatusBar(status_bar)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(main_window,
                                           sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(status_bar, expmgr, d_shortcuts,
                                       sub_clients["explist"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"])

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"],
                                       rpc_clients["dataset_db"])

    d_applets = applets.AppletsDock(main_window, sub_clients["datasets"])
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)

    if os.name != "nt":
        d_ttl_dds = moninj.MonInj()
        loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
        atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(
        status_bar, rpc_clients["schedule"], sub_clients["schedule"])

    logmgr = log.LogDockManager(main_window, sub_clients["log"])
    smgr.register(logmgr)

    # lay out docks
    if os.name != "nt":
        main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, d_ttl_dds.dds_dock)
        main_window.tabifyDockWidget(d_ttl_dds.dds_dock, d_ttl_dds.ttl_dock)
        main_window.tabifyDockWidget(d_ttl_dds.ttl_dock, d_applets)
        main_window.tabifyDockWidget(d_applets, d_datasets)
    else:
        main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, d_applets)
        main_window.tabifyDockWidget(d_applets, d_datasets)
    main_window.tabifyDockWidget(d_datasets, d_shortcuts)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)
    main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, d_explorer)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_shortcuts, d_log0)

    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Пример #29
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "dashboard")

    app = QtWidgets.QApplication(["ARTIQ Dashboard"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(client.connect_rpc(
            args.server, args.port_control, "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    sub_clients = dict()
    for notifier_name, modelf in (("explist", explorer.Model),
                                  ("explist_status", explorer.StatusUpdater),
                                  ("datasets", datasets.Model),
                                  ("schedule", schedule.Model)):
        subscriber = ModelSubscriber(notifier_name, modelf)
        loop.run_until_complete(subscriber.connect(
            args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    log_receiver = Receiver("log", [])
    loop.run_until_complete(log_receiver.connect(
        args.server, args.port_broadcast))
    atexit_register_coroutine(log_receiver.close)

    # initialize main window
    main_window = MainWindow(args.server)
    smgr.register(main_window)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(main_window,
                                           sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(expmgr, d_shortcuts,
                                       sub_clients["explist"],
                                       sub_clients["explist_status"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"])

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"],
                                       rpc_clients["dataset_db"])
    smgr.register(d_datasets)

    d_applets = applets.AppletsDock(main_window, sub_clients["datasets"])
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)

    d_ttl_dds = moninj.MonInj()
    loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
    atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(
        rpc_clients["schedule"], sub_clients["schedule"])
    smgr.register(d_schedule)

    logmgr = log.LogDockManager(main_window)
    smgr.register(logmgr)
    log_receiver.notify_cbs.append(logmgr.append_message)
    widget_log_handler.callback = logmgr.append_message

    # lay out docks
    right_docks = [
        d_explorer, d_shortcuts,
        d_ttl_dds.ttl_dock, d_ttl_dds.dds_dock,
        d_datasets, d_applets
    ]
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, right_docks[0])
    for d1, d2 in zip(right_docks, right_docks[1:]):
        main_window.tabifyDockWidget(d1, d2)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_schedule, d_log0)

    logging.info("ARTIQ dashboard %s connected to %s", artiq_version, args.server)

    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Пример #30
0
        '''
        with QThreadExecutor(1) as exec:
            window = engine.rootObjects()[0]
            myObject = window.findChild(QObject, "myObject")
            #loop.call_soon(myObject.funcRetClicked())
            #myObject.funcRetClicked()
            loop.run_in_executor(exec, myObject.funcRetClicked)
        '''


with loop:
    try:
        test = Test()
        service = Service(loop)

        #loop.run_forever()

        print('1')
        # rootObjects 실행전 context를 선언/추가해줍니다.
        ctx = engine.rootContext()
        ctx.setContextProperty('Service', service)

        engine.load("main.qml")
        window = engine.rootObjects()[0]
        #window.setContextProperty('Service', service)

        loop.run_until_complete(test.printInterval())
        loop.run_forever()
    except:
        pass
Пример #31
0
            #print('step:{}'.format(step))
            yield from asyncio.sleep(step)


class Test():
    def __init__(self, loop):
        pass

    pass


with loop:
    window = MyWindow(loop)
    test = Test(loop)
    #asyncio.async(window.initialize())
    window.initialize()
    window.show()
    loop.run_until_complete(window.connect_and_timer())
    #loop.run_until_complete(window.initialize())
    #loop.call_soon(window.initialize())
    loop.run_forever()
'''
if __name__ == "__main__":
    QCoreApplication.setLibraryPaths([qt5_url])

    #app = QApplication(sys.argv)
    window = MyWindows()
    window.show()
    #app.exec_()
'''
Пример #32
0
        self.loop.run_until_complete(self.nats.master(loop))
        try:
            self.loop.run_forever()
        finally:
            self.loop.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)  # NEW must set the event loop

    ui = Me(loop)
    ui.show()

    # Example using NATS client from another thread.
    #thr = Thread(target=another_thread, args=(component,))
    #thr.start()
    #tt = TestMyThread(ccc=loop)
    #tt.start()


#'''
    with loop: ## context manager calls .close() when loop completes, and releases all resources
        loop.run_until_complete(ui.nats.master(loop))
#        loop.run_until_complete(run(loop))
        try:
            loop.run_forever()
        finally:
            loop.close()
#'''
Пример #33
0


# bind Qt application with Python asyncio loop
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)

g = app.desktop().screenGeometry()
size = g.width() + 256 * 2, g.height() + 256 * 2

pos = (0, 0)
if len(sys.argv) == 3:
    pos = float(sys.argv[1]), float(sys.argv[2])

mm = geotiler.Map(size=size, center=pos, zoom=18)

window = MapWindow(mm)
window.show()

queue = asyncio.Queue()
t1 = read_gps(queue)
t2 = locate(window, queue)
t3 = refresh_map(window)
task = asyncio.gather(t1, t2, t3)

window.refresh_map.set()
loop.run_until_complete(task)

# vim: sw=4:et:ai
Пример #34
0

async def process_events(qapp):
    while True:
        await asyncio.sleep(0)
        qapp.processEvents()


if __name__ == "__main__":

    app = QApplication([])

    if QUAMASH:
        from quamash import QEventLoop

        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)
    else:
        loop = asyncio.get_event_loop()

    main = MainWindow(loop)
    loop.add_signal_handler(signal.SIGINT, main.shutdown, None)

    if QUAMASH:
        with loop:
            loop.run_forever()
    else:
        loop.run_until_complete(process_events(app))

    app.closeAllWindows()
Пример #35
0
def main():
    args = get_argparser().parse_args()
    init_logger(args)

    app = QtGui.QApplication([])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(lambda: loop.close())

    smgr = StateManager(args.db_file)

    schedule_ctl = AsyncioClient()
    loop.run_until_complete(
        schedule_ctl.connect_rpc(args.server, args.port_control,
                                 "master_schedule"))
    atexit.register(lambda: schedule_ctl.close_rpc())

    win = MainWindow(app, args.server)
    area = dockarea.DockArea()
    smgr.register(area)
    smgr.register(win)
    win.setCentralWidget(area)
    status_bar = QtGui.QStatusBar()
    status_bar.showMessage("Connected to {}".format(args.server))
    win.setStatusBar(status_bar)

    d_explorer = ExplorerDock(win, status_bar, schedule_ctl)
    smgr.register(d_explorer)
    loop.run_until_complete(
        d_explorer.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_explorer.sub_close()))

    d_datasets = DatasetsDock(win, area)
    smgr.register(d_datasets)
    loop.run_until_complete(
        d_datasets.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_datasets.sub_close()))

    if os.name != "nt":
        d_ttl_dds = MonInj()
        loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
        atexit.register(lambda: loop.run_until_complete(d_ttl_dds.stop()))

    if os.name != "nt":
        area.addDock(d_ttl_dds.dds_dock, "top")
        area.addDock(d_ttl_dds.ttl_dock, "above", d_ttl_dds.dds_dock)
        area.addDock(d_datasets, "above", d_ttl_dds.ttl_dock)
    else:
        area.addDock(d_datasets, "top")
    area.addDock(d_explorer, "above", d_datasets)

    d_schedule = ScheduleDock(status_bar, schedule_ctl)
    loop.run_until_complete(
        d_schedule.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_schedule.sub_close()))

    d_log = LogDock()
    smgr.register(d_log)
    loop.run_until_complete(d_log.sub_connect(args.server, args.port_notify))
    atexit.register(lambda: loop.run_until_complete(d_log.sub_close()))

    dataset_db = AsyncioClient()
    loop.run_until_complete(
        dataset_db.connect_rpc(args.server, args.port_control,
                               "master_dataset_db"))
    atexit.register(lambda: dataset_db.close_rpc())

    def _set_dataset(k, v):
        asyncio.ensure_future(dataset_db.set(k, v))

    def _del_dataset(k):
        asyncio.ensure_future(dataset_db.delete(k))

    d_console = ConsoleDock(d_datasets.get_dataset, _set_dataset, _del_dataset)

    area.addDock(d_console, "bottom")
    area.addDock(d_log, "above", d_console)
    area.addDock(d_schedule, "above", d_log)

    smgr.load()
    smgr.start()
    atexit.register(lambda: loop.run_until_complete(smgr.stop()))
    win.show()
    loop.run_until_complete(win.exit_request.wait())
Пример #36
0
        scroll_map(self, self.position)


# bind Qt application with Python asyncio loop
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)

g = app.desktop().screenGeometry()
size = g.width() + 256 * 2, g.height() + 256 * 2

pos = (0, 0)
if len(sys.argv) == 3:
    pos = float(sys.argv[1]), float(sys.argv[2])

mm = geotiler.Map(size=size, center=pos, zoom=18)

window = MapWindow(mm)
window.show()

queue = asyncio.Queue()
t1 = read_gps(queue)
t2 = locate(window, queue)
t3 = refresh_map(window)
task = asyncio.gather(t1, t2, t3)

window.refresh_map.set()
loop.run_until_complete(task)

# vim: sw=4:et:ai
Пример #37
0
from widgets.main import Main
from service.util import open_session,close_session

if __name__ == "__main__":
    """
    在PyQt5中,如果在Python 代码中抛出了异常,没有进行捕获,异常只要进入事件循环,程序就崩溃,而没有任何提示,给程序调试带来不少麻烦,通过在程序运行前加入以下代码,则能避免程序崩溃.
    import cgitb 
    cgitb.enable( format = ‘text’)
    """
    import sys
    import qdarkstyle
    import cgitb
    cgitb.enable(format='text')#
    app = QApplication(sys.argv)
    # 将Qt事件循环写到asyncio事件循环里。
    # QEventLoop不是Qt原生事件循环,
    # 是被asyncio重写的事件循环。
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    with loop:
        Form = Main()
        loop.run_until_complete(open_session())
        app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        Form.initUI()
        Form.resize(1022, 700)
        #Form.resize(600, 400)
        Form.show()
        #sys.exit(app.exec_())
        loop.run_forever()
        loop.run_until_complete(close_session())
        #print("close")
Пример #38
0
        self.discovered = True

    def _fullpath(self, join=None):
        p = [self.name]
        target = self._parent()
        while target:
            p.append(target.name)
            target = target.parent()
        p.reverse()
        if join is not None: return join.join(p)
        return p


async def main():
    await asyncio.wait([
        slow_operation(1),
        slow_operation(2),
        slow_operation(3),
    ])


app = QtGui.QApplication([])
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
atexit.register(loop.close)
#loop = asyncio.get_event_loop()
win = MainWindow(app, None)

win.show()
loop.run_until_complete(win.exit_request.wait())
loop.run_until_complete(main())
Пример #39
0
def wire_tap(msg):
    ex.insertText(msg.data.decode())


def main(loop, subject):
    nc = NATS()
    yield from nc.connect(f"{sys.argv[1]}:{sys.argv[2]}", loop=loop)

    async def mh_s1(msg):
        await wire_tap(msg)

    yield from nc.subscribe(subject, cb=wire_tap)


if __name__ == '__main__':

    if len(sys.argv) != 4:
        print(
            "Usage: python nats_scrolling_plaintext_edit.py [host] [port] [queue]"
        )
    else:
        app = QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)

        loop.run_until_complete(main(loop, subject=sys.argv[3]))

        ex = QtWiretap()
        loop.run_forever()
Пример #40
0
class BadgecmdMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app, device, baudrate):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.device = device
        self.baudrate = baudrate

        self.app = app
        self.setupUi(self)
        self.setWindowTitle('Badgecmd')

        self.main_loop = QEventLoop(self.app)
        asyncio.set_event_loop(self.main_loop)

        self.io = IoSignals()
        self.proto = BadgeProtocol(self.io)
        self.serial_coro = None
        self.awaiting = None
        self.paused = False

        # connect all of the signals
        for method in self.__dir__():
            if method.startswith('_when_'):
                emitter_name, signal_name = method.split('_')[-2:]
                signal = getattr(getattr(self, emitter_name), signal_name)
                signal.connect(getattr(self, method))

    def _serial_connect(self):
        if not self.serial_coro:
            self.serial_coro = create_serial_connection(
                self.main_loop,
                self.proto,
                self.device,
                # baudrate=9600
                baudrate=self.baudrate)
            self.main_loop.run_until_complete(self.serial_coro)

    def _serial_disconnect(self):
        if self.serial_coro:
            self.proto.close()
            self.serial_coro = None

    def _when_clear_clicked(self):
        self.output.clear()

    def _when_connect_clicked(self):
        if self.connect.text() == 'connect':
            self._serial_connect()
            self.connect.setText('disconnect')
            self.pause.setText('pause')
            self.paused = False
        else:
            self._serial_disconnect()
            self.connect.setText('connect')

    def _when_io_disconnect(self):
        self.connect.setText('connect')

    def _when_io_rx(self, packet):
        # if packet.command == 0xAF and packet.slave_reply == 0:
        #     logging.warn('skipping 0xAF')
        # return
        if self.paused:
            return
        if self.awaiting == packet.command and packet.slave_reply:
            self.output.setTextColor(qGreen)
            self.awaiting = None
        else:
            self.output.setTextColor(qBlue)
        self.output.append(' '.join([
            'rx:',
            repr(packet),
            ','.join(["0x{:02X}".format(i) for i in packet.to_bytes()])
        ]))
        self.output.setTextColor(qBlack)

    def _when_input_returnPressed(self):
        raw = self.input.text()
        if len(raw):
            try:
                data = [int(i, 16) for i in raw.split(' ')]
            except ValueError as e:
                logging.error(e)
                return
            packet = Packet(command=data[0],
                            data=data[1:],
                            include_checksum=self.crc.isChecked(),
                            slave_reply=self.mode.text() == 'S')
            packet_bytes = packet.to_bytes()
            if self.mode.text() == 'M':
                self.awaiting = packet.command
            self.proto.send(packet_bytes)
            self.output.setTextColor(qRed)
            self.output.append(' '.join([
                'tx:',
                repr(packet),
                ','.join(["0x{:02X}".format(i) for i in packet_bytes])
            ]))
            self.output.setTextColor(qBlack)

    def _when_mode_clicked(self):
        if self.mode.text() == 'M':
            self.mode.setText('S')
        else:
            self.mode.setText('M')

    def _when_pause_clicked(self):
        if self.pause.text() == 'pause':
            self.pause.setText('unpause')
            self.paused = True
            # self.proto.pause()
        else:
            self.pause.setText('pause')
            self.paused = False
            # self.proto.unpause()

    def exec_(self):
        return self.main_loop.run_forever()
Пример #41
0
def main():
    # initialize application
    args = get_argparser().parse_args()
    widget_log_handler = log.init_log(args, "dashboard")

    if args.db_file is None:
        args.db_file = os.path.join(
            get_user_config_dir(),
            "artiq_dashboard_{server}_{port}.pyon".format(
                server=args.server.replace(":", "."), port=args.port_notify))

    app = QtWidgets.QApplication(["ARTIQ Dashboard"])
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    atexit.register(loop.close)
    smgr = state.StateManager(args.db_file)

    # create connections to master
    rpc_clients = dict()
    for target in "schedule", "experiment_db", "dataset_db":
        client = AsyncioClient()
        loop.run_until_complete(
            client.connect_rpc(args.server, args.port_control,
                               "master_" + target))
        atexit.register(client.close_rpc)
        rpc_clients[target] = client

    config = Client(args.server, args.port_control, "master_config")
    try:
        server_name = config.get_name()
    finally:
        config.close_rpc()

    disconnect_reported = False

    def report_disconnect():
        nonlocal disconnect_reported
        if not disconnect_reported:
            logging.error("connection to master lost, "
                          "restart dashboard to reconnect")
        disconnect_reported = True

    sub_clients = dict()
    for notifier_name, modelf in (("explist", explorer.Model),
                                  ("explist_status", explorer.StatusUpdater),
                                  ("datasets", datasets.Model),
                                  ("schedule", schedule.Model)):
        subscriber = ModelSubscriber(notifier_name, modelf, report_disconnect)
        loop.run_until_complete(
            subscriber.connect(args.server, args.port_notify))
        atexit_register_coroutine(subscriber.close)
        sub_clients[notifier_name] = subscriber

    broadcast_clients = dict()
    for target in "log", "ccb":
        client = Receiver(target, [], report_disconnect)
        loop.run_until_complete(
            client.connect(args.server, args.port_broadcast))
        atexit_register_coroutine(client.close)
        broadcast_clients[target] = client

    # initialize main window
    main_window = MainWindow(
        args.server if server_name is None else server_name)
    smgr.register(main_window)
    mdi_area = MdiArea()
    mdi_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    mdi_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
    main_window.setCentralWidget(mdi_area)

    # create UI components
    expmgr = experiments.ExperimentManager(main_window, sub_clients["explist"],
                                           sub_clients["schedule"],
                                           rpc_clients["schedule"],
                                           rpc_clients["experiment_db"])
    smgr.register(expmgr)
    d_shortcuts = shortcuts.ShortcutsDock(main_window, expmgr)
    smgr.register(d_shortcuts)
    d_explorer = explorer.ExplorerDock(expmgr, d_shortcuts,
                                       sub_clients["explist"],
                                       sub_clients["explist_status"],
                                       rpc_clients["schedule"],
                                       rpc_clients["experiment_db"])
    smgr.register(d_explorer)

    d_datasets = datasets.DatasetsDock(sub_clients["datasets"],
                                       rpc_clients["dataset_db"])
    smgr.register(d_datasets)

    d_applets = applets_ccb.AppletsCCBDock(main_window,
                                           sub_clients["datasets"])
    atexit_register_coroutine(d_applets.stop)
    smgr.register(d_applets)
    broadcast_clients["ccb"].notify_cbs.append(d_applets.ccb_notify)

    d_ttl_dds = moninj.MonInj()
    loop.run_until_complete(d_ttl_dds.start(args.server, args.port_notify))
    atexit_register_coroutine(d_ttl_dds.stop)

    d_schedule = schedule.ScheduleDock(rpc_clients["schedule"],
                                       sub_clients["schedule"])
    smgr.register(d_schedule)

    logmgr = log.LogDockManager(main_window)
    smgr.register(logmgr)
    broadcast_clients["log"].notify_cbs.append(logmgr.append_message)
    widget_log_handler.callback = logmgr.append_message

    # lay out docks
    right_docks = [
        d_explorer, d_shortcuts, d_ttl_dds.ttl_dock, d_ttl_dds.dds_dock,
        d_ttl_dds.dac_dock, d_datasets, d_applets
    ]
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, right_docks[0])
    for d1, d2 in zip(right_docks, right_docks[1:]):
        main_window.tabifyDockWidget(d1, d2)
    main_window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, d_schedule)

    # load/initialize state
    if os.name == "nt":
        # HACK: show the main window before creating applets.
        # Otherwise, the windows of those applets that are in detached
        # QDockWidgets fail to be embedded.
        main_window.show()
    smgr.load()
    smgr.start()
    atexit_register_coroutine(smgr.stop)

    # create first log dock if not already in state
    d_log0 = logmgr.first_log_dock()
    if d_log0 is not None:
        main_window.tabifyDockWidget(d_schedule, d_log0)

    if server_name is not None:
        server_description = server_name + " ({})".format(args.server)
    else:
        server_description = args.server
    logging.info("ARTIQ dashboard %s connected to %s", artiq_version,
                 server_description)

    # run
    main_window.show()
    loop.run_until_complete(main_window.exit_request.wait())
Пример #42
0
    def __init__(self,
                 serialport,
                 *,
                 baudrate=115200,
                 outpath=None,
                 printlines=False,
                 firstline='',
                 printHz=False,
                 bufsize=2048,
                 pMin=0,
                 pMax=25,
                 convert_pressure=False,
                 socket_start=False):
        super().__init__()

        self.serialport = serialport
        self.baudrate = baudrate
        self.outpath = outpath
        self.outfile = None
        self.printlines = printlines
        self.printHz = printHz
        self.bufsize = bufsize
        self.plotbuf = deque(maxlen=self.bufsize)
        self.rawdata = deque(maxlen=self.bufsize)
        self.pMin = pMin
        self.pMax = pMax

        self.convert_pressure = convert_pressure
        self.f = OneEuroFilter(100, .25, .1)
        self.event = 0
        self.run = True
        self.filterflag = True

        #Touch event detection
        self.diffsamps = 100  #How far back to look for diff
        self.event_thresh = 7  #Standard Deviation value to consider an event is happening
        self.touch = False  #Is a touch happening?
        self.touchcount = 0  #How many touch samples so far?
        self.touchthresh = 1000  #Number of touch samples to check
        self.touch_data = [
        ]  #Data from touch to be sent to machine learning thingy
        self.touch_buf = []
        #		self.model        = load(model) # Path to compiled model file
        self.printed = False

        self.socket = socket_start

        #Keep values to update baseline
        self.baselinebuf = deque(maxlen=self.bufsize // 4)

        app = QtGui.QApplication(sys.argv)
        loop = QEventLoop(app)
        asyncio.set_event_loop(loop)

        self.resize(800, 400)

        p = self.addPlot()
        self.plotline = p.plot(pen='y')
        self.baseline = p.plot(pen='b')
        self.show()

        if self.socket:
            # Create socket and wait for connection
            ip = ''
            port = 6969
            connected = False
            s = socket.socket()
            print('Waiting on connection')
            s.bind((ip, port))
            s.listen(1)
            self.conn, self.addr = s.accept()
            loop.run_until_complete(self.read_data())

        if self.outpath:
            with open(self.outpath, 'w') as self.outfile:
                if firstline:
                    self.log('#{}'.format(firstline))
                loop.run_until_complete(self.read_data())
        else:
            if firstline:
                self.log('#{}'.format(firstline))
            loop.run_until_complete(self.read_data())
Пример #43
0
class SimpleApplet:
    def __init__(self, main_widget_class, cmd_description=None,
                 default_update_delay=0.0):
        self.main_widget_class = main_widget_class

        self.argparser = argparse.ArgumentParser(description=cmd_description)

        self.argparser.add_argument(
            "--update-delay", type=float, default=default_update_delay,
            help="time to wait after a mod (buffering other mods) "
                 "before updating (default: %(default).2f)")

        group = self.argparser.add_argument_group("standalone mode (default)")
        group.add_argument(
            "--server", default="::1",
            help="hostname or IP of the master to connect to "
                 "for dataset notifications "
                 "(ignored in embedded mode)")
        group.add_argument(
            "--port", default=3250, type=int,
            help="TCP port to connect to")

        self.argparser.add_argument(
            "--embed", default=None, help="embed into GUI",
            metavar="IPC_ADDRESS")

        self._arggroup_datasets = self.argparser.add_argument_group("datasets")

        self.dataset_args = set()

    def add_dataset(self, name, help=None, required=True):
        kwargs = dict()
        if help is not None:
            kwargs["help"] = help
        if required:
            self._arggroup_datasets.add_argument(name, **kwargs)
        else:
            self._arggroup_datasets.add_argument("--" + name, **kwargs)
        self.dataset_args.add(name)

    def args_init(self):
        self.args = self.argparser.parse_args()
        self.datasets = {getattr(self.args, arg.replace("-", "_"))
                         for arg in self.dataset_args}

    def quamash_init(self):
        app = QtWidgets.QApplication([])
        self.loop = QEventLoop(app)
        asyncio.set_event_loop(self.loop)

    def ipc_init(self):
        if self.args.embed is not None:
            self.ipc = AppletIPCClient(self.args.embed)
            self.loop.run_until_complete(self.ipc.connect())

    def ipc_close(self):
        if self.args.embed is not None:
            self.ipc.close()

    def create_main_widget(self):
        self.main_widget = self.main_widget_class(self.args)
        if self.args.embed is not None:
            self.ipc.set_close_cb(self.main_widget.close)
            if os.name == "nt":
                # HACK: if the window has a frame, there will be garbage
                # (usually white) displayed at its right and bottom borders
                #  after it is embedded.
                self.main_widget.setWindowFlags(QtCore.Qt.FramelessWindowHint)
                self.main_widget.show()
                win_id = int(self.main_widget.winId())
                self.loop.run_until_complete(self.ipc.embed(win_id))
            else:
                # HACK:
                # Qt window embedding is ridiculously buggy, and empirical
                # testing has shown that the following procedure must be
                # followed exactly on Linux:
                # 1. applet creates widget
                # 2. applet creates native window without showing it, and
                #    gets its ID
                # 3. applet sends the ID to host, host embeds the widget
                # 4. applet shows the widget
                # 5. parent resizes the widget
                win_id = int(self.main_widget.winId())
                self.loop.run_until_complete(self.ipc.embed(win_id))
                self.main_widget.show()
                self.ipc.fix_initial_size()
        else:
            self.main_widget.show()

    def sub_init(self, data):
        self.data = data
        return data

    def filter_mod(self, mod):
        if self.args.embed is not None:
            # the parent already filters for us
            return True

        if mod["action"] == "init":
            return True
        if mod["path"]:
            return mod["path"][0] in self.datasets
        elif mod["action"] in {"setitem", "delitem"}:
            return mod["key"] in self.datasets
        else:
            return False

    def emit_data_changed(self, data, mod_buffer):
        self.main_widget.data_changed(data, mod_buffer)

    def flush_mod_buffer(self):
        self.emit_data_changed(self.data, self.mod_buffer)
        del self.mod_buffer

    def sub_mod(self, mod):
        if not self.filter_mod(mod):
            return

        if self.args.update_delay:
            if hasattr(self, "mod_buffer"):
                self.mod_buffer.append(mod)
            else:
                self.mod_buffer = [mod]
                asyncio.get_event_loop().call_later(self.args.update_delay,
                                                    self.flush_mod_buffer)
        else:
            self.emit_data_changed(self.data, [mod])

    def subscribe(self):
        if self.args.embed is None:
            self.subscriber = Subscriber("datasets",
                                         self.sub_init, self.sub_mod)
            self.loop.run_until_complete(self.subscriber.connect(
                self.args.server, self.args.port))
        else:
            self.ipc.subscribe(self.datasets, self.sub_init, self.sub_mod)

    def unsubscribe(self):
        if self.args.embed is None:
            self.loop.run_until_complete(self.subscriber.close())

    def run(self):
        self.args_init()
        self.quamash_init()
        try:
            self.ipc_init()
            try:
                self.create_main_widget()
                self.subscribe()
                try:
                    self.loop.run_forever()
                finally:
                    self.unsubscribe()
            finally:
                self.ipc_close()
        finally:
            self.loop.close()
Пример #44
0
progress = QProgressBar()
progress.setRange(0, 99)
progress.show()


@asyncio.coroutine
def master():
    yield from first_50()
    with QThreadExecutor(1) as exec:
        yield from loop.run_in_executor(exec, last_50)

@asyncio.coroutine
def first_50():
    for i in range(50):
        progress.setValue(i)
        yield from asyncio.sleep(.1)

def last_50():
    for i in range(50, 100):
        loop.call_soon_threadsafe(progress.setValue, i)
        time.sleep(.1)


with loop:
    loop.run_until_complete(master())